12 February 2014

Contents:

HTTP Server in C, explained

HTTP Authentication in C/C++

HTTP Server in C, source example

Handle POST Multipart and X-Form in C

HTTP Server in C++ from C source

Simple Authentication in Node.js

Simple HTTP Server in Java

Server simple Authentication in Java

Java server Authentication based on Cookies

Handling POST requests in Node JS

POST requests in Java application

Classes and objects in C

* * *

HTTP Server in C, explained

What would itch you to write a server in C? Well, for that you might have four legit reasons: overheads, speed and control, your love for plain C, and (my favourite) ➝ the artistic combination of the previous three :) Link here, and the C source code is here.

Simple Authentication in Node.js

When you write a server, ordinarily you have to protect it (or its specific routes) from unauthorised access. It could be done through the HTTP cookies, which are persistent and live only within the communication between the client ('s browser) and the server. Link here.

Handle POST Multipart and X-Form in C Server

Often, uh, very often, writing a POST reader/handler is a sort of embarrassing predicament. Some browsers send the POST content along with the request (in the request's body); some send them exceptionally as a separate chunks of bytes; some combine the two strategies depending on the POST message size. More here.

HTTP Server in C++

First off, you can compile the C code with the C++ compiler without a hitch. You should only pay attention to the (char*) and (const char*) reciprocal referencing, which is not a big deal at all. Put bluntly, you may take the C source (compiled with gcc ver. 7.5 [Ubuntu]) and compiled with g++ ver. 7.5 [Ubuntu]) without issues, although, as concerns the C code, gcc seems to do a slightly better job. Here is the C++ source.

HTTP Authentication in C/C++

When the servers requires the client's credential (usually, username and password, but it could be any other information as well), the server respond with HTTP/1.1 401 Unauthorized. It also includes the expected scheme (which in this case is WWW-Authenticate: Basic) and could also include the realm (e.g. realm="Protected. Enter your password"). Then the server waits for the client's reply. Continue here.

Simple HTTP Server in Java

You may meticulously take care of  correctly setting and configuring sockets' options, binding, accepting and listening to the port, as you have to in C/C++, or you may prefer to benefit of what the Java developers have already done (com.sun.net.httpserver), and focus on your application's logics. With Java you are always on the safe side. More here.

Server simple Authentication in Java

You may adopt one of two strategies: (1) use the provided Basic Authenticator, or (2) implement the authentication by cookies, as explained in Node.js authentication. More here.

Classes and objects in C

If, for reasons other than sheer amusement, you need C with classes/objects, you better use C++. This is what C++ is primarily for. However, you can also simulate classes/objects in plain C. More here.

11 February 2014

POST requests in Java application

If you need more control over the POST requests, you might wish to implement your own POST handler within your Java server application.

Then you'll come across three ENCTYPEs to deal with:

  1. application/x-www-form-urlencoded:
    read the stream (message body), parse and URL decode the fields (key-value pairs);

  2. text/plain:
    read the stream and... be happy. No need to decode or parse, as the it arrives just as it was sent. ;

  3. multipart/form-data:
    here everything gets more complicated, since the stream is organised in packages, sent one by one. Each chunk might have multiple form fields, files or parts of the file. Handling the files is a bit tricky, because in one chunk the file could be started, then several chunk could convey parts of this large file, then it could be consumed in another chunk.
For files, there are two main strategies:
  • read all the chunks into one big buffer, and then parse it as one huge string, by splitting it into sections, parsing each header of the section and retrieving its value. The obvious downside of such an approach is that you consume a lot of resources, by which reason many POST implementations restrict the transmission to 2Mb, 5Mb, 10Mb, allocated for the entire transmission;

  • another strategy is to deal with each chunk apart and as it is available for reading. It allows you to use the minimum of resources along with no restrictions on the transmission. The core of this approach is marking the points when the file starts and when it ends, which might occur in different chunks/packages.
The example below implements the second approach: chunk by chunk, no limits, low resources. The application is minimalistic too and provides only one route (context):
  • for the GET method, which delivers an HTML with three ENCTYPEs (x-www-form, plain text and multipart) to experiment with:

X-WWW-Form:

First name:


Last name:


Text/Plain:

First name:


Last name:


Multipart:

First name:


Last name:





  • and one POST channel to consume the three POST enctype submissions. For that, we wrote the class doPost with three main methods, respectively, as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import java.io.*;
import java.util.*;
import com.sun.net.httpserver.*;

public class httpserver {

  public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new java.net.InetSocketAddress(8080), 0);
    server.createContext("/", new info());
    server.setExecutor(null);
    server.start();
    System.out.println("> Server running on PORT: 8080...");
  }

  static class info implements HttpHandler {
    public void handle(HttpExchange t) {
      
      if("POST".equals(t.getRequestMethod())) { new doPost(t); return; }

      String RES = "<html><head><style>input { margin-bottom: 10px; }</style></head><body><table border='1' cellpadding='12' bgcolor='#eee'><tr>";

      RES += "<td valign='top'><h3>X-Form:</h3><form action='/' method='post' enctype='application/x-www-form-urlencoded'>";
      RES += "First name:<br><input type='text' id='fname' name='fname' value='First Name'><br>";
      RES += "Last name:<br><input type='text' id='lname' name='lname' value='Last Name'><br>";
      RES += "<input type='submit' value='Submit'>";
      RES += "</form></td>";

      RES += "<td valign='top'><h3>Text/Plain:</h3><form action='/' method='post' enctype='text/plain'>";
      RES += "First name:<br><input type='text' id='fname' name='fname' value='First Name'><br>";
      RES += "Last name:<br><input type='text' id='lname' name='lname' value='Last Name'><br>";
      RES += "<input type='submit' value='Submit'>";
      RES += "</form></td>";

      RES += "<td valign='top'><h3>Multipart:</h3><form action='/' method='post' enctype='multipart/form-data'>";
      RES += "First name:<br><input type='text' id='fname' name='fname' value='First Name'><br>";
      RES += "Last name:<br><input type='text' id='lname' name='lname' value='Last Name'><br>";
      RES += "<input type='file' id='myfile' name='myfile'><br>";
      RES += "<input type='submit' value='Submit'>";
      RES += "</form></td>";
      RES += "</tr></table></body></html>";

      try {
        t.getResponseHeaders().set("Content-Type", "text/html");
        t.sendResponseHeaders(200, 0);
        OutputStream os = t.getResponseBody();
        os.write(RES.getBytes()); os.close();
      } catch(IOException ex) { ex.printStackTrace(); }
    }
  }

/* --- Class to handle POST requests --- */
static class doPost {

  private String bndry, contType;
  private int contLength;
  private Map<String, String> data;

  public doPost(HttpExchange t) { // constructor
    getParams(t);
    if(contType.equals("application/x-www-form-urlencoded")) { xForm(t); return; }
    else if(contType.equals("text/plain")) { textPlain(t); return; }
    else if(contType.equals("multipart/form-data")) { multiPart(t); return; }
    else {
      pr("\nContent-Type: " + contType + "\nContent-Length: " + contLength + "\nBoundary: [" + bndry + "]\n");
      writeBack(t, "Unknown request ENCTYPE!".getBytes());
      return;
    }
  }

  void xForm(HttpExchange t) { // handle application/x-www-form-urlencoded
    writeBack(t, mapQueries(getBody(t)) ? getMapItems().getBytes() : "Unresolved queries.".getBytes());
  }

  void textPlain(HttpExchange t) { // handle text/plain
    writeBack(t, getBody(t).getBytes());
  }

  void multiPart(HttpExchange t) { // handle multipart/form-data
    if(bndry == null) return;

    String FL = "";
    boolean fFlag = false;
    byte[] chunk;
    int bLen = bndry.length();
    Map<String, String> FLDS = new HashMap<String, String>();
    
    while(true) {
      
      try {
        chunk = t.getRequestBody().readAllBytes();
        if(chunk == null ) return;
      } catch(IOException ioe) { ioe.printStackTrace(); return; }

      pr("\n ---- NEW CHUNK ----\n");
      int ix = 0;
      boolean first = true;
      while(true) {

        ix = find(chunk, bndry, ix);
        if(ix < 0) {
          if(fFlag) {
            pr("Continue reading file.");
            FL += chunk;
            break;
          }
          else { pr("Uncaught error"); return; }
        }

        if(first) {
          first = false;
          if(fFlag && ix > 0) {
            pr("Finishing reading.");
            FL += cut(chunk, 0, find(chunk, bndry, 0)-2);
            fFlag = false;
            continue;
          }
        }

        if(chunk[ix + bLen] == '-' && chunk[ix + bLen + 1] == '-'){
            data = FLDS;
            writeBack(t, (getMapItems() + (FL.isEmpty()?"":("\n" + FL + ']'))).getBytes());
            pr("FINISH");
            return;
        }

        fFlag = false;

        int fi = find(chunk, "\r\n\r\n", ix + bLen + 2);
        parseHeader(cut(chunk, ix+bLen+2, fi));
        //pr(getMapItems());

        String fileName = data.get("filename");
        if(fileName != null) {
          pr("File: " + fileName + ", Type: " + data.get("Content-Type"));
          if(fileName.isEmpty()) {
            pr("No file sent.");
            ix = fi + 4;
            continue;
          }

          ix = find(chunk, bndry, fi + 4);
          if(ix < 0) ix = chunk.length;
          FLDS.put(data.get("name"), fileName);
          FL += fileName + '[' + cut(chunk, fi+4, ix-2);
          fFlag = true;
        }
        else {
          ix = find(chunk, bndry, fi + 4);
          if(ix < 0) ix = chunk.length;
          FLDS.put(data.get("name"), cut(chunk, fi+4, ix-2).toString());
          pr("VALUE = [" + cut(chunk, fi+4, ix-2).toString() + ']');
          ix = fi + 4;
        }
      }
    }    
  }

  void writeBack(HttpExchange t, byte[] str) {
    try {
      t.getResponseHeaders().set("Content-Type", "text/plain");
      t.sendResponseHeaders(200, str.length); // or 0 instead of str.length
      OutputStream os = t.getResponseBody();
      os.write(str); os.flush(); os.close();        
    } catch(IOException ioe) { pr("ACHTUNG!"); ioe.printStackTrace(); }
  }

  static String cut(byte[] src, int start, int end) {
    byte[] res = new byte[end-start];
    System.arraycopy(src, start, res, 0, end-start);
    return new String(res);
  }

  static int find(byte[] in, String whatin, int startAt) {
    byte[] what = whatin.getBytes();
    int inLen = in.length, whatLen = what.length, i, j;
    for(i = startAt; i < inLen; i++)
      if(in[i] == what[0]) {
        j=1; while(j < whatLen && in[i+j] == what[j]) j++;
        if(j == whatLen) return i;
      }
    return -1;
  }

  String getMapItems() {
    String qs = "";
    for(Map.Entry<String,String> el : data.entrySet())
      qs += el.getKey()+ '=' + el.getValue() + '\n';
    return qs;
  }

  String getBody(HttpExchange t) {
    try {
      return new String(t.getRequestBody().readAllBytes());
    } catch(IOException ioe) { ioe.printStackTrace(); return null; }
  }

  boolean mapQueries(String q) {
    if(q == null) return false;
    String[] arr = q.split("&");
    data = new HashMap<String, String>();
    try {
      for(int i=0; i<arr.length; i++) {
        int ix = arr[i].indexOf('='); if(ix<0) return false;
        data.put(arr[i].substring(0, ix), java.net.URLDecoder.decode(arr[i].substring(ix+1), "UTF-8"));
      }
    } catch(UnsupportedEncodingException ex) { ex.printStackTrace(); return false; }
    return true;
  }

  void getParams(HttpExchange t) {
    contType = t.getRequestHeaders().get("Content-Type").get(0);
    contLength = Integer.parseInt(t.getRequestHeaders().get("Content-Length").get(0));
    int ix = contType.indexOf("boundary=");
    if(ix < 0) { bndry = null; }
    else { bndry = "--" + contType.substring(ix + 9); contType = contType.substring(0, ix-2); }
    return;
  }

  void parseHeader(String hd) {
    data = new HashMap<String, String>();
    String[] arr = hd.split("; |\r\n");
    for(String el: arr) {
      if(el.isEmpty()) continue;
      String[] pairs = el.split(": |=");
      if(pairs.length < 2) data.put("value", pairs[0]);
      else data.put(pairs[0], pairs[1].indexOf('"') < 0?pairs[1]:pairs[1].substring(1,pairs[1].length()-1));
    }
    return;
  }

  void pr(String s) { System.out.println(s); }
}

}

Handling POST requests in Node JS

If you need more control over the POST requests, you might wish to implement your own POST handler within your Node JS server application.

Then you'll come across three ENCTYPEs to deal with:

  1. application/x-www-form-urlencoded:
    read the stream (message body), parse and URL decode the fields (key-value pairs);

  2. text/plain:
    read the stream and... be happy. No need to decode or parse, as the it arrives as it was sent. Quite handy when it comes to JSON structures, using only JSON.stringify() and JSON.parse() at the both ends of the communication;

  3. multipart/form-data:
    here everything gets more complicated, since the stream is organised in packages, sent one by one. Each chunk might have multiple form fields, files or parts of the file. Handling the files is a bit tricky, because in one chunk the file could be started, then several chunk could convey parts of this large file, then it could be consumed in another chunk.
For files, there are two main strategies:
  • read all the chunks into one big buffer, and then parse it as one huge string, by splitting it into sections, parsing each header of the section and retrieving its value. The obvious downside of such an approach is that you consume a lot of resources, by which reason many POST implementations restrict the transmission to 2Mb, 5Mb, 10Mb, allocated for the entire transmission;

  • another strategy is to deal with each chunk apart and as it is available for reading. It allows you to use the minimum of resources along with no restrictions on the transmission. The core of this approach is marking the points when the file starts and when it ends, which might occur in different chunks/packages.
The example below implements the second approach: chunk by chunk, no limits, low resources. The application is minimalistic too and provides only:
  • one GET route to deliver an HTML with three ENCTYPEs (x-www-form, plain text and multipart) to experiment with:

X-WWW-Form:

First name:


Last name:


Text/Plain:

First name:


Last name:


Multipart:

First name:


Last name:





  • and one POST channel to consume the three POST enctype submissions. For that, we wrote the class doPost with three main methods, respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const http = require('http'),
    fs = require('fs'),
    doPost = require('./doPost');

const server = http.createServer( (req, res) => {
  if(req.method == 'POST') new doPost(req, res);
  else doGet(req, res);
});

server.listen(8080);
console.log("> Server listens on 8080");

function doGet(req, res) {
    let RES = "<html><head><style>input { margin-bottom: 10px; }</style></head><body><table border='1' cellpadding='12' bgcolor='#eee'><tr>";
    RES += "<td valign='top'><h3>X-Form:</h3><form action='/' method='post' enctype='application/x-www-form-urlencoded'>";
    RES += "First name:<br><input type='text' id='fname' name='fname' value='First Name'><br>";
    RES += "Last name:<br><input type='text' id='lname' name='lname' value='Last Name'><br>";
    RES += "<input type='submit' value='Submit'>";
    RES += "</form></td>";

    RES += "<td valign='top'><h3>Text/Plain:</h3><form action='/' method='post' enctype='text/plain'>";
    RES += "First name:<br><input type='text' id='fname' name='fname' value='First Name'><br>";
    RES += "Last name:<br><input type='text' id='lname' name='lname' value='Last Name'><br>";
    RES += "<input type='submit' value='Submit'>";
    RES += "</form></td>";

    RES += "<td valign='top'><h3>Multipart:</h3><form action='/' method='post' enctype='multipart/form-data'>";
    RES += "First name:<br><input type='text' id='fname' name='fname' value='First Name'><br>";
    RES += "Last name:<br><input type='text' id='lname' name='lname' value='Last Name'><br>";
    RES += "<input type='file' id='myfile' name='myfile'><br>";
    RES += "<input type='submit' value='Submit'>";
    RES += "</form></td>";
    RES += "</tr></table></body></html>";
  res.end(RES);
}


And here is the class doPost (module):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
module.exports = class doPost {
    
    constructor(req, res) {
        const encType = req.headers['content-type'].split(';')[0];
        if(encType == "application/x-www-form-urlencoded") this.doXForm(req, res);
        else if(encType == "text/plain") this.doTextPlain(req, res);
        else if(encType == "multipart/form-data") this.doMultiPart(req, res);
        else {
            var r = "Unknown ENCTYPE: " + req.headers['content-type'];
            console.log(r); res.end(r);
        }
        return;
    }
    
    doXForm(req, res) { /* --- handle application/x-www-form-urlencoded --- */
        var body = '';
        req.on('data', chunk => body += chunk);
        req.on('end', () => {
          var r = 'FIELDS:\n', arr = body.split('&');
		      for(var s of arr) {
			      var itms = s.split('=');
			      r += itms[0] + '=' + decodeURI(itms[1].replace(/\+/g, ' ')) + '\n';
		      }
		      res.end(r);
        });
    }
    
    doTextPlain(req, res) { /* --- handle text/plain ---*/
        var body = '';
        req.on('data', chunk => body += chunk);
        req.on('end', () => res.end(body));       
    }
    
    doMultiPart(req, res) { /* --- handle multipart/form-data --- */
        var Js = this.parseHeader(req.headers['content-type']);
        var bndry = "--" + Js.boundary, bLen = bndry.length;
        var FL = '';
        var fFlag = false;
        var FLDS = 'FIELDS:\n';

        req.on('data', chunk => {

            var ix = 0, first = true;
            while(true) {

                ix = chunk.indexOf(bndry, ix);
          
                if(ix < 0){
                    if(fFlag) { console.log('Continue writting file.'); FL+=chunk; return; }
                    console.log('Don\'t know what is happening.'); return;
                }
        
                if(first) {
                    first = false;
                    if(fFlag && ix > 0) {
                        console.log('Finishing writting file.');
                        FL += chunk.slice(0, chunk.indexOf(bndry)-2);
                        fFlag = false;
                        continue;
                    }
                }
    
                if(chunk.slice(ix+bLen, ix+bLen+2) == '--') { console.log("FINISH"); return; }
        
                /* --- section --- */
        
                fFlag = false;
        
                var fi = chunk.indexOf("\r\n\r\n", ix+bLen+2);
                var J = this.parseHeader(chunk.slice(ix+bLen+2, fi).toString());
                this.listObj(J);
            
                if("filename" in J) {
                    console.log('filename=' + J.filename + ', Type=' + J['Content-Type']);
                    if(J.filename === '') {
                        console.log("No file transmitted.");
                        ix = fi+4;
                        continue;
                    }
                
                    ix = chunk.indexOf(bndry, fi+4);
                    if(ix < 0 ) ix = chunk.length;
                    //console.log('FILE>\n['+chunk.slice(fi+4, ix-2).toString()+']');
                    FL += J.filename + '[' + chunk.slice(fi+4, ix-2).toString();
                    FLDS += J.name + '=' + J.filename + '\n';
                    fFlag = true;
                }
                else {
                    ix = chunk.indexOf(bndry, fi+4);
                    if(ix < 0 ) ix = chunk.length;
                    FLDS += J.name + '=' + chunk.slice(fi+4, ix-2).toString() + '\n';
                    console.log('VALUE = ['+chunk.slice(fi+4, ix-2).toString()+']');
                }
                ix = fi+4;
            }
        });
  
        req.on('end', () => res.end(FLDS + (FL !== ''?('\n' + FL + ']'):'')));        
    }

    parseHeader(hd) {
        var js = {};
        var els = hd.split(/; |\r\n/);
        for(var el of els) {
            if(el === '') continue;
            var pair = el.split(/: |=/);
            if(pair.length < 2) { pair[1] = pair[0]; pair[0] = 'value'; }
            js[pair[0]] = pair[1].indexOf('"') < 0 ? pair[1] : pair[1].replace(/\"/g,'');
        }
        return js;
    }
    
    listObj(Js) {
        console.log(".");
        for(var k in Js) console.log(">[" + k + "]=[" + Js[k] + ']');
    }
}

HTTP Server in C++

First off, you can compile the C code with the C++ compiler without a hitch. You should only pay attention to the (char*) and (const char*) reciprocal referencing, which is not a big deal at all. Put bluntly, you may take the C source (compiled with gcc ver. 7.5 [Ubuntu]) and compiled with g++ ver. 7.5 [Ubuntu]) without issues, although, as concerns the C code, gcc seems to do a slightly better job.

g++ server.cpp -o server
./server
> Server started on port 8080.


The only (but rather significant) feature of C++ I used is its object-oriented style. I created a class Server and mechanically re-arranged the C functions in that class's private and public methods and properties, as shown below. Now the code looks prettier, better structured and with a larger potential for development and adaptation to your tasks. It also comes in handy when writing multi-thread applications.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <...>
using ...;
#define ...

class Server {

  private:

    int port, nSocket, conn, total, qTotal;
    size_t MemLen, MemTotal;
    char buffer[BUF_SIZE], ioBuffer[BUF_SIZE]; // For reading Files and Posts
    char *method, *URI, *protocol, methCode, *body;
    struct keyValue hdr[20]; // headers
    struct keyValue fld[20]; // fields

    void respond() {... }
    char *readSocket() {...}
    char *getHeader() {...}
    char *getQueryItem() {...}
    char Lk() {...}
    void getQueries() {...}
    void addInReqList() {...}
    char *urlDecode() {...}
    char *addToMem() {...}
    void serveFile() {...}
    void dynamicHTML() {...}
    char *extract() {...}
    int parseSection() {...}
    void readMultipart() {...}

  public:

    Server(){...} /* Constructor */
    void Listen() {...}
    void parseRequest() {...}
    void listReqInfo() {...}
    void router() {...}
    void cleanUp() {...}
    ~Server() {...} /* Distructor */

};


int main() {

    Server server(8080);
    LISTEN:

        server.Listen();
        server.parseRequest();
        server.listReqInfo();
        server.router();
        server.cleanUp();

    goto LISTEN;
}


The complete code looks like this:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
#include <iostream>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
using namespace std;

struct keyValue
{
 char *item, *value, *filename;
};

#define BUF_SIZE 2048

class Server
{

    private:

 int port, nSocket, conn, total, qTotal;
 size_t MemLen, MemTotal;
 char buffer[BUF_SIZE], ioBuffer[BUF_SIZE]; // For reading Files and Posts
 char *method, *URI, *protocol, methCode, *body;
 struct keyValue hdr[20]; // headers
 struct keyValue fld[20]; // fields

 void ERR(const char *err)
 {
  cout << err << "\n";
  exit(1);
 }
 
 void respond(const char *st)
 {
  write(conn, st, strlen(st));
 }

 char *readSocket()
 {
  size_t vRead = read(conn, buffer, BUF_SIZE);
  buffer[vRead] = '\0';
  if (vRead < 0) ERR("> CANNOT READ FROM SOCKET");
  printf("\n\e[42m\e[30m Socket #%d (%d bytes) \e[39m\e[49m\n", conn, (int) vRead);
  MemLen = vRead;
  return buffer;
 }

 char *getHeader(const char *item)
 {
  for (int i = 0; i < total; i++)
   if (strcmp(hdr[i].item, item) == 0) return hdr[i].value;
  return NULL;
 }

 char *getQueryItem(const char *item)
 {
  for (int i = 0; i < qTotal; i++)
   if (strcmp(fld[i].item, item) == 0) return fld[i].value;
  return NULL;
 }

 char Lk(const char *ce, const char *src)
 {
  do {  const char *p = ce;
   while (*p)
    if (*p != *src) break;
    else
    {
     p++;
     src++;
    }
   if (*p == '\0' && (*src == '\0' || *src == '.')) return '\1';
   while (*src && *src != '.') src++;
  } while (*src);
  return '\0';
 }

 void getQueries(char *q)
 {
  char *eq, *am;
  while (eq = strchr(q, '='))
  { *eq++ = '\0';
   if (am = strchr(eq, '&'))
   {  *am = '\0';
    addInReqList(q, urlDecode(eq), NULL);
    q = am + 1;
   }
   else addInReqList(q, urlDecode(eq), NULL);
  }
 }

 void addInReqList(char *item, char *value, char *filename)
 {
  int t = qTotal;
  fld[t].item = item;
  fld[t].value = urlDecode(value);
  fld[t].filename = filename;
  qTotal++;
 }

 char *urlDecode(char *src)
 {
  char a, b, *ret = src, *dst = src, Fst = 'a' - 'A', Sec = 'A' - 10;
  while (*src)
  {
   if (*src == '%' && (a = src[1]) && (b = src[2]) && isxdigit(a) && isxdigit(b))
   {
    a -= (a >= 'a') ? Fst : ((a >= 'A') ? Sec : '0');
    b -= (b >= 'a') ? Fst : ((b >= 'A') ? Sec : '0');
    *dst++ = 16 *a + b;
    src += 3;
   }
   else if (*src == '+')
   {*dst++ = ' ';
    src++;
   }
   else *dst++ = *src++;
  }
  *dst = '\0';
  return ret;
 }

 char *addToMem(char *p)
 {
  int l = strlen(p) + 1;
  if ((MemLen + l) >= BUF_SIZE) ERR("Not enough memory.");
  char *ret = strcpy(buffer + MemLen + 1, p);
  MemLen += l;
  return ret;
 }

 //----------------------- SERVE FILE -------------------------
 void serveFile(const char *name)
 {
  int file, rs;
  char *Buf = ioBuffer;

  if ((file = open(name, 0, S_IREAD)) < 0)
  {
   respond("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nFile[");
   respond(name);
   respond("] not found.");
   printf("File %s not found.", name);
   return;
  }

  char *ext = (char*) name + strlen(name) - 1;
  while (ext > name && *ext != '.') ext--;
  respond("HTTP/1.1 200 OK\r\nContent-Type: ");

  if (ext == name) respond("text/plain");
  else if (Lk(ext, ".js")) respond("text/javascript");
  else if (Lk(ext, ".css.html"))
  {
   respond("text/");
   respond(ext + 1);
  }
  else if (Lk(ext, ".jpeg.png.gif.bmp.webp.ico"))
  {
   respond("image/");
   respond(ext + 1);
  }
  else if (Lk(ext, ".xml.pdf"))
  {
   respond("application/");
   respond(ext + 1);
  }
  else respond("text/plain");
  respond("\r\n\r\n");

  while ((rs = read(file, Buf, BUF_SIZE)) > 0) write(conn, Buf, rs);
  close(file);
 }

 void dynamicHTML()
 {

  respond("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
  respond("<html><head> < link rel='stylesheet' type='text/css' href='res/theme.css'>");
  respond("</head><body> < h1>Server Info:</h1>");

  respond("Method:<b>");
  respond(method);
  respond("</b>, URI:<b>");
  respond(URI);
  respond("</b>, Protocol:<b>");
  respond(protocol);
  respond("</b><br>");

  respond("<h3>Headers:</h3>");
  respond("<table cellSpacing=0 cellPadding=6><tr><th>Header</th><th>Value</th></tr>");
  for (int i = 0; i < total; i++)
  {
   respond("<tr><td>");
   respond(hdr[i].item);
   respond("</td><td>");
   respond(hdr[i].value);
   respond("</td><tr>");
  }
  respond("</table><br>");

  if (qTotal > 0)
  {
   respond("<h3>Queries:</h3>");
   respond("<table cellSpacing=0 cellPadding=6><tr><th>Item</th><th>Value</th></tr>");
   for (int i = 0; i < qTotal; i++)
   {
    respond("<tr><td>");
    respond(fld[i].item);
    respond("</td><td>");
    respond(fld[i].value);
    respond("</td><tr>");
   }
  }
  respond("</table><br>");

  char *val = getQueryItem("name");
  respond("Query value for \"name\" =<b>");
  respond(val ? val : "NULL");
  respond("</b><hr> < a href='/run.sh?server=Server&port=Port'>Arguments</a > | ");
  respond("<a href='/dyn.c'>Not found</a > | ");
  respond("<a href='/'>Index</a > | ");
  respond("<a href='/info?name=Darius&Occupation=Student&Hobby=Computers'>Info</a > | ");

  if (methCode == '\1' && body)
  {
   respond("<hr>POST body:<b>");
   respond(body);
   respond("</b>");
  }

  respond("</body></html>");
 }

 char *extract(char *pool, const char *fish)
 {
  char *x = strstr(pool, fish);
  if (!x) return NULL;
  x += strlen(fish) + 1;
  int i = 0;
  while (x[i] && x[i] != '\"') i++;
  x[i] = '\0';
  return x;
 }

 int parseSection(char *buf, char *bndry, char ifInMemory)
 {
  int bLen = strlen(bndry), totSec = 0;
  char *sec[20];
  while (sec[totSec] = strstr(buf, bndry))
  {
   if (totSec > 0) sec[totSec][-2] = '\0';
   buf = sec[totSec] + bLen;
   totSec++;
  }

  if (totSec == 0)
  {
   // handle the file content
   printf("FILE:\n[\e[33m%s\e[0m]\n", buf);
   return 2;
  }

  for (int i = 0; i < totSec; i++)
  {
   char *p = sec[i] + bLen;
   if (*p == '-' && *(p + 1) == '-') return 0; // end of Multipart
   p += 2;
   char *val = strstr(p, "\r\n\r\n"); *val = '\0';
   val += 4; // points to Value
   char *filename = extract(p, " filename="), *name = extract(p, " name=");

   if (ifInMemory) addInReqList(name, val, (filename && *filename) ? filename : NULL);
   else addInReqList(addToMem(name), addToMem(val), (filename && *filename) ? addToMem(filename) : NULL);
  }
  return 1;
 }
 //----------------------- READ MULTIPART -------------------------
 void readMultipart(const char *ctype, size_t len)
 {
  const char *boundary = "boundary=";
  char *buf = ioBuffer, *p, *bry = (char*) strstr(ctype, boundary) + strlen(boundary);
  bry -= 2;
  bry[0] = bry[1] = '-';
  int bytes, bryLen = strlen(bry), fileOngoing = 0;
  char *file, *name;
  char timeStampt[17];
  time_t local; // timestampt

  //printf("\nPOST Boundary:[\e[32m%s\e[0m] (%d bytes)\n\n", bry, bryLen);

  if (body)
   if (!parseSection(body, bry, '\1')) return;

  while ((bytes = read(conn, buf, BUF_SIZE)) >= 0)
  {
   buf[bytes] = '\0';
   //printf("\t\t\t[%d bytes]\n[%s]\n", bytes, buf);
   if (!parseSection(buf, bry, '\0')) return;
  }
 }

 void readXForm(const char *ctype, size_t len)
 {
  char *buf = ioBuffer, *beg = buffer + MemLen + 1;
  size_t bytes, totBytes = 0;
  while ((bytes = read(conn, buf, BUF_SIZE)) >= 0)
  {
   buf[bytes] = '\0';
   totBytes += bytes;
   //printf("\t\t\t[%d/%d bytes]\n[%s]\n", (int)bytes, (int)len, buf);
   if ((MemLen + bytes + 1) >= BUF_SIZE) ERR("Not enough memory.");
   strcpy(buffer + MemLen + 1, buf);
   MemLen += bytes + 1;

   if (totBytes >= len) break;
  }
  if (*ctype == 'a') getQueries(beg);
  else body = beg; // for plain text
 }

    public:

 Server(int _port)
 {
  int option = 1;
  struct sockaddr_in address;
  if ((nSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) ERR("> SOCKET CREATION");
  memset((char*) &address, '\0', sizeof(address));
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = INADDR_ANY;
  address.sin_port = htons(_port);
  if (setsockopt(nSocket, SOL_SOCKET, (SO_REUSEPORT | SO_REUSEADDR), (char*) &option, sizeof(option)) < 0) ERR("SOCKET SET OPTIONS");
  if (bind(nSocket, (struct sockaddr *) &address, sizeof(address)) < 0) ERR("> BINDING ERROR");
  port = _port;
  cout << "> Server started on port " << port << "\n";
 }

 void Listen()
 {
  if (listen(nSocket, 10) < 0) ERR("server: listen"); // pendings backlogs
  if ((conn = accept(nSocket, NULL, NULL)) < 0) ERR("SOCKET[server] ACCEPT");
 }

 void parseRequest()
 {

  char *buf = readSocket(), *qs;
  total = 0;
  qTotal = 0;

  if ((qs = strstr(buf, "\r\n\r\n")) && *(qs + 4))
  { *qs = '\0'; body = qs + 4; }
  else body = NULL;

  method = buf;
  buf = strchr(buf, ' '); *buf++ = '\0';
  URI = buf;
  buf = strchr(buf, ' '); *buf++ = '\0';
  protocol = buf;
  buf = strchr(buf, '\r'); *buf = '\0';
  buf += 2;

  if (strcmp(method, "GET") == 0) methCode = '\0';
  else if (strcmp(method, "POST") == 0) methCode = '\1';
  else methCode = '\2';

  if (qs = strchr(URI, '?'))
  { *qs++ = '\0'; getQueries(qs); }

  char *key = buf, *val;
  while (val = strchr(buf, ':'))
  { *val = '\0';
   val += 2;
   if (buf = strchr(val, '\r'))
   { *buf = '\0'; buf += 2; }
   hdr[total].item = key;
   hdr[total].value = val;
   hdr[total].filename = NULL;
   total++;
   if (buf) key = buf;
   else break;
  }

  if (methCode == '\1')
  {
   //--- handle Post
   char *CL = getHeader("Content-Length"), *CT = getHeader("Content-Type");
   if (*CT == 'a')
   {
    //--- app www-form-url
    if (body) getQueries(body);
    else readXForm(CT, (size_t) atoi(CL));
   }
   else if (*CT == 't')
   {
    //--- text/plain
    if (!body) readXForm(CT, (size_t) atoi(CL));
   }
   else if (*CT == 'm')
   {
    //--- Multipart
    if (!CL || !CT) ERR("Post request without Length or Type headers.\n");
    readMultipart(CT, (size_t) atoi(CL));
   }
  }
 }

 void listReqInfo()
 {

  printf("\nMethod \e[32m%s\e[0m (%d) URI: \e[32m%s\e[0m Query: \e[32m%d\e[0m Protocol: \e[32m%s\e[0m Body: \e[32m%s\e[0m\n",
   method, methCode, URI, qTotal, protocol, body ? "EXISTS" : "Empty");

  if (qTotal > 0)
  {
   printf("\nQUERY STRINGs (%d):\n\n", qTotal);
   for (int i = 0; i < qTotal; i++)
    printf("\t%s = \e[32m%s\e[0m (%s)\n", fld[i].item, fld[i].value, fld[i].filename ? fld[i].filename : "-");
  }

  printf("\nHEADERS\' LIST (%d):\n\n", total);
  for (int i = 0; i < total; i++)
  {
   printf("\t(%d) %s: \e[32m%s\e[0m\n", i, hdr[i].item, hdr[i].value);
  }

  if (methCode == '\1' && body)
  {
   const char *n = getHeader("Content-Type"); // if 't' text/plain
   if (n && *n == 't') printf("\nPOST BODY:\n\e[32m%s\e[0m\n", body);
  }

  fflush(stdout);
 }

 void router()
 {
  if (strcmp(URI, "/") == 0) serveFile("res/index.html");
  else if (strcmp(URI, "/info") == 0) dynamicHTML();
  else if (strcmp(URI, "/exit") == 0)
  {
   close(nSocket);
   cout << "> Server (on port " << port << ") stopped.\n";
   exit(0);
  }
  else serveFile(URI + 1);
 }

 void cleanUp()
  {
   close(conn);
   //if(body) free(body); // if malloc-ed
  }

  ~Server()
  {
   close(nSocket);
   cout << "> Server stopped, port " << port << "\n";
  }
};

int main()
{

 Server server(8080);
 LISTEN:

            server.Listen();
            server.parseRequest();
            server.listReqInfo();
            server.router();
            server.cleanUp();

 goto LISTEN;
}


*The initial sources in C can be found here.