11 February 2014

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.

No comments:

Post a Comment