11 February 2014

HTTP Server in C, source example

Below is the source. It compiles with both gcc and g++ compilers (for C and C++). The tested versions are 7.5 on Ubuntu, which produces an executable of 26,7Kb and 27,1Kb respectively (gcc and g++).

gcc server.c -o server
./server
> Server started on port 8080.
or
g++ server.c -o server
./server
> Server started on port 8080.

*Here you can see the explanations of the code.

  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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <fcntl.h>
#include <ctype.h>

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

#define BUF_SIZE 2048

struct _request
{
 int conn, total, qTotal, socket, port;
 char *method, *URI, *protocol, methCode, *body; // methcode 0-GET 1-POST X-Others
 struct keyValue hdr[20]; // headers
 struct keyValue fld[20]; // fields
 size_t MemLen, MemTotal;
 char buffer[BUF_SIZE], ioBuffer[BUF_SIZE]; // For reading File and Post
};

void listenOn(int, struct _request *);
void readMultipart(struct _request *, const char *, size_t, void(*func)(struct _request *, char *, int));

void ERR(const char *s)
{
 perror(s);
 exit(1);
}

//----------------------- URL DECODE -------------------------
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;
}
//----------------------- BASE64 DECODE -------------------------
char *base64_decode(char *data)
{
 char encoding_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
 char decoding_table[256];
 int i, j;
 size_t inpL = strlen(data), outL;
 for (i = 0; i < 64; i++) decoding_table[(unsigned char) encoding_table[i]] = i;
 if (inpL % 4 != 0) return NULL;
 outL = inpL / 4 * 3;
 if (data[inpL - 1] == '=') outL--;
 if (data[inpL - 2] == '=') outL--;
 for (i = 0, j = 0; i < inpL;)
 {
  size_t sextet_a = data[i] == '=' ? 0 &i++ : decoding_table[data[i++]];
  size_t sextet_b = data[i] == '=' ? 0 &i++ : decoding_table[data[i++]];
  size_t sextet_c = data[i] == '=' ? 0 &i++ : decoding_table[data[i++]];
  size_t sextet_d = data[i] == '=' ? 0 &i++ : decoding_table[data[i++]];

  size_t triple = (sextet_a << 3 *6) + (sextet_b << 2 *6) + (sextet_c << 1 *6) + (sextet_d << 0 *6);

  if (j < outL) data[j++] = (triple >> 2 *8) &0xFF;
  if (j < outL) data[j++] = (triple >> 1 *8) &0xFF;
  if (j < outL) data[j++] = (triple >> 0 *8) &0xFF;
 }
 data[outL] = '\0';
 return data;
}

//----------------------- RESPOND -------------------------
void respond(int sk, const char *st)
{
 write(sk, st, strlen(st));
}

//----------------------- READ FROM SOCKET -------------------------
char *readSocket(struct _request *H)
{
 size_t vRead = read(H->conn, H->buffer, BUF_SIZE);
 H->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", H->conn, (int) vRead);
 H->MemLen = vRead;
 return H->buffer;
}

//----------------------- LOOK EXTENSTION -------------------------
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';
}

/*--- If you need to log the requests
//----------------------- LOG FILE -------------------------
void logFile(const char *pth) {
  pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;
  char loc_time[40]; time_t local; time(&local);
  strftime(loc_time, 40, "%a, %d %b %Y %X %Z", localtime(&local));

  pthread_mutex_lock(&Mutex);
      FILE *log = fopen("res/logs.txt","a");
      fprintf(log, "%s | file %s requested\n", loc_time, pth);
      fclose(log);
  pthread_mutex_unlock(&Mutex);
}
*/
//----------------------- SERVE FILE -------------------------
void serveFile(struct _request *H, const char *name)
{
 int file, rs, sk = H->conn;
 char *Buf = H->ioBuffer;

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

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

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

 while ((rs = read(file, Buf, BUF_SIZE)) > 0) write(sk, Buf, rs);
 close(file);
}
//----------------------- GET HEADER / QUERY ITEM -------------------------
char *getHeader(struct _request *Headers, const char *item)
{
 for (int i = 0; i < Headers->total; i++)
  if (strcmp(Headers->hdr[i].item, item) == 0) return Headers->hdr[i].value;
 return NULL;
}

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

//----------------------- LOGIN, LOGOUT, IS LOGGED -------------------------
#define MAX_ATTEMPTS 3
#define MAX_LOG_MIN 1 /*max login period in minutes */
time_t loginTime;

void login(struct _request *H)
{
 char ratio[] = " / \0";
 ratio[2] = '0' + MAX_ATTEMPTS;
 for (int i = 0; i < MAX_ATTEMPTS; i++)
 {
  respond(H->conn, "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"Protected. Attempt ");
  ratio[0] = '0' + (i + 1);
  respond(H->conn, ratio);
  respond(H->conn, "\"\r\n\r\n");

  close(H->conn);
  listenOn(0, H);
  const char *find = "Authorization: Basic ";
  char *buf = readSocket(H);

  buf = strstr(buf, find) + strlen(find);
  char *cr = strchr(buf, '\r'); *cr = '\0';
  if (strcmp(base64_decode(buf), "user:pass") == 0)
  {
   time(&loginTime);
   respond(H->conn, "HTTP/1.1 200 OK\r\nSet-Cookie: user=user,Today,Tomorrow\r\nContent-Type: text/plain\r\n\r\nLogged in succesfully.");
   return;
  }
 }
 respond(H->conn, "HTTP/1.1 200 OK\r\nSet-Cookie: user=?\r\nContent-Type: text/plain\r\n\r\nUnauthorised.");
 //respond(H->conn, "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\n\r\nYou have no access!");
}

void logout(struct _request *H)
{
 respond(H->conn, "HTTP/1.1 200 OK\r\nSet-Cookie: user=?\r\nContent-Type: text/plain\r\n\r\nYou have just logged out.");
 printf("Logged out.\n");
}

char isLogged(struct _request *H, const char *userName)
{
 char *coo = getHeader(H, "Cookie");
 if (coo && (coo = strstr(coo, "user=")) && strstr(coo + 5, userName))
 {
  time_t curr;
  time(&curr);
  unsigned period = (unsigned int) difftime(curr, loginTime);
  if ((unsigned int) difftime(curr, loginTime) < MAX_LOG_MIN *60)
  {
   printf("\n > Logged %d secs ago...\n", (unsigned int) difftime(curr, loginTime));
   return '\1';
  }
  else printf("> Time of login (%d vs. %d)[in secs] expired.\n", period, MAX_LOG_MIN *60);
 }
 respond(H->conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nUnauthorised.");
 return '\0';
}

//----------------------- LIST HEADERS & QUERIES-------------------------
void listReqInfo(struct _request *H)
{

 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", H->method, H->methCode, H->URI, H->qTotal, H->protocol, H->body ? "EXISTS" : "Empty");

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

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

 const char *test[] = { "Host", "Connection", "Content-Type", "Content-Length" };
 printf("\nGET HEADERS:\n\n");
 for (int i = 0; i < 4; i++)
 {
  char *n = getHeader(H, test[i]);
  printf("\tHeader \"%s\": \e[32m%s\e[0m\n", test[i], n ? n : "None");
 }

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

 fflush(stdout);
}

//----------------------- ADD IN REQUEST LIST -------------------------
void addInReqList(struct _request *H, char *item, char *value, char *filename)
{
 int t = H->qTotal;
 H->fld[t].item = item;
 H->fld[t].value = urlDecode(value);
 H->fld[t].filename = filename;
 H->qTotal++;
}

//----------------------- GET QUERIES -------------------------
void getQueries(struct _request *H, char *q)
{
 char *eq, *am;
 while (eq = strchr(q, '='))
 {
  *eq++ = '\0';
  if (am = strchr(eq, '&'))
  { *am = '\0'; addInReqList(H, q, eq, NULL); q = am + 1; }
  else addInReqList(H, q, eq, NULL);
 }
}
//----------------------- FILE HANDLER IN POST -------------------------
void handleFile(struct _request *H, char *buf, int fStatus)
{
 if (buf) printf("[\e[36m%s\e[0m]\n", buf);
 else
 {
  if (fStatus)
  {
   char *fName = H->fld[H->qTotal - 1].filename;
   printf("\t\t\t\e[33m-<BOF>-\e[0m (%s)\n", fName);
  }
  else printf("\t\t\t\e[33m-<EOF>-\e[0m\n");
 }
}

//----------------------- READ POST  -------------------------
void readXForm(struct _request *H, const char *ctype, size_t len)
{
 char *buf = H->ioBuffer, *beg = H->buffer + H->MemLen + 1;
 size_t bytes, totBytes = 0;
 while ((bytes = read(H->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 ((H->MemLen + bytes + 1) >= BUF_SIZE) ERR("Not enough memory.");
  strcpy(H->buffer + H->MemLen + 1, buf);
  H->MemLen += bytes + 1;

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

//----------------------- PARSE REQUEST -------------------------
void parseRequest(struct _request *H)
{
 char *buf = readSocket(H), *qs;
 H->total = 0;
 H->qTotal = 0;

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

 H->method = buf;
 buf = strchr(buf, ' '); *buf++ = '\0';
 H->URI = buf;
 buf = strchr(buf, ' '); *buf++ = '\0';
 H->protocol = buf;
 buf = strchr(buf, '\r'); *buf = '\0';
 buf += 2;
 if (strcmp(H->method, "GET") == 0) H->methCode = '\0';
 else if (strcmp(H->method, "POST") == 0) H->methCode = '\1';
 else H->methCode = '\2';

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

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

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

//----------------------- EXTRACT -------------------------
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;
}

//----------------------- ADD TO POST memory -------------------------
char *addToMem(struct _request *H, char *p)
{
 int l = strlen(p) + 1;
 if ((H->MemLen + l) >= BUF_SIZE) ERR("Not enough memory.");
 char *ret = strcpy(H->buffer + H->MemLen + 1, p);
 H->MemLen += l;
 return ret;
}

//----------------------- PARSE A SECTION -------------------------
int parseSection(struct _request *H, 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++;
 }

 for (int i = 0; i < totSec; i++) printf("\t\t\tSEC #%d:\n[%s]\n", i, sec[i]);

 if (totSec == 0)
 {
  // might be a file
  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) == '-')
  {
   printf("FINAL\n");
   return 0;
  } // final
  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(H, name, val, (filename && *filename) ? filename : NULL);
  else addInReqList(H, addToMem(H, name), addToMem(H, val), (filename && *filename) ? addToMem(H, filename) : NULL);
 }
 return 1;
}

//----------------------- READ MULTIPART -------------------------
void readMultipart(struct _request *H, const char *ctype, size_t len, void(*fileHandler)(struct _request *, char *buf, int status))
{
 const char *boundary = "boundary=";
 char *buf = H->ioBuffer, *p, *bry = (char*) strstr(ctype, boundary) + strlen(boundary);
 bry -= 2;
 bry[0] = bry[1] = '-';
 int conn = H->conn, 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 (H->body)
  if (!parseSection(H, H->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(H, buf, bry, '\0')) return;
 }
}

//----------------------- DYNAMIC HTML -------------------------
void dynamicHTML(struct _request *H)
{

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

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

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

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

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

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

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

//----------------------- ROUTER -------------------------
void router(struct _request *H)
{
 if (strcmp(H->URI, "/") == 0) serveFile(H, "res/index.html");
 else if (strcmp(H->URI, "/info") == 0)
 {
  //if (isLogged(H, "user")) dynamicHTML(H);
  dynamicHTML(H);
 }
 else if (strcmp(H->URI, "/logout") == 0) logout(H);
 else if (strcmp(H->URI, "/login") == 0) login(H);
 else if (strcmp(H->URI, "/exit") == 0)
 {
  respond(H->conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nServer stopped.");
  close(H->conn);
  close(H->socket);
  printf("> Server on port %d stopped.\n", H->port);
  exit(0);
 }
 else serveFile(H, H->URI + 1);
}

//--------------------- INIT SERVER -------------------------
void listenOn(int port, struct _request *H)
{
 // return socket
 static int nSocket = -1;
 if (nSocket < 0)
 {
  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");
  H->socket = nSocket;
  H->port = port;

  printf("> Server started on port %d.\n", port);
 }
 int newSocket;
 if (listen(nSocket, 10) < 0) ERR("server: listen"); // pendings backlogs
 if ((newSocket = accept(nSocket, NULL, NULL)) < 0) ERR("SOCKET[server] ACCEPT");
 H->conn = newSocket;
}

//------------------------ MAIN ------------------------------
int main()
{

 struct _request REQ;

 LISTEN:

            listenOn(8080, &REQ);

     parseRequest(&REQ);
     listReqInfo(&REQ);
     router(&REQ);
     close(REQ.conn);

 goto LISTEN;
}


*You can see the explanations of the code here.

No comments:

Post a Comment