summaryrefslogtreecommitdiffstats
path: root/nanohttp/nanohttp-server.c
blob: c885a72d2b8e255cff66a1432d67e5502909f6eb (plain)
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
/******************************************************************
*  $Id: nanohttp-server.c,v 1.50 2006/02/21 16:40:47 mrcsys Exp $
*
* CSOAP Project:  A http client/server library in C
* Copyright (C) 2003  Ferhat Ayaz
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA  02111-1307, USA.
*
* Email: ayaz@jprogrammer.net
******************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif

#ifdef HAVE_SOCKET_H
#include <sys/socket.h>
#endif

#ifdef WIN32
#include <process.h>
#define snprintf(buffer, num, s1, s2) sprintf(buffer, s1,s2)
#endif

#ifdef MEM_DEBUG
#include <utils/alloc.h>
#endif

#include "nanohttp-server.h"
#include "nanohttp-base64.h"
#include "nanohttp-ssl.h"

typedef struct _conndata
{
  hsocket_t sock;
#ifdef WIN32
  HANDLE tid;
#else
  pthread_t tid;
  pthread_attr_t attr;
#endif
  time_t atime;
}
conndata_t;

/*
 * -----------------------------------------------------
 * nano httpd
 * internally globals
 * -----------------------------------------------------
 */
static int _httpd_port = 10000;
static int _httpd_max_connections = 20;
static hsocket_t _httpd_socket;
static hservice_t *_httpd_services_default = NULL;
static hservice_t *_httpd_services_head = NULL;
static hservice_t *_httpd_services_tail = NULL;
static int _httpd_run = 1;
static conndata_t *_httpd_connection;

#ifdef WIN32
static DWORD _httpd_terminate_signal = CTRL_C_EVENT;
static int _httpd_max_idle = 120;
static void WSAReaper (void *x);
#define strncasecmp(s1, s2, num) strncmp(s1, s2, num)
#else
static int _httpd_terminate_signal = SIGINT;
static sigset_t thrsigset;
#endif

#ifdef HAVE_SSL
/*extern SSL_CTX *SSLctx;*/
#endif


/*
 * -----------------------------------------------------
 * FUNCTION: httpd_init
 * NOTE: This will be called from soap_server_init_args()
 * -----------------------------------------------------
 */
herror_t
httpd_init (int argc, char *argv[])
{
  int i;
  herror_t status;
#ifdef HAVE_SSL
  char *SSLCert = NULL, *SSLPass = NULL, *SSLCA = NULL;
#endif

  hoption_init_args (argc, argv);

  if ((status = hsocket_module_init()) != H_OK)
    return status;

  /* write argument information */
  log_verbose1 ("Arguments:");
  for (i = 0; i < argc; i++)
    log_verbose3 ("argv[%i] = '%s'", i, SAVE_STR (argv[i]));

  /* initialize from arguments */
  for (i = 0; i < argc; i++)
  {
    if (!strcmp (argv[i], NHTTPD_ARG_PORT) && i < argc - 1)
    {
      _httpd_port = atoi (argv[i + 1]);
    }
    else if (!strcmp (argv[i], NHTTPD_ARG_TERMSIG) && i < argc - 1)
    {
      _httpd_terminate_signal = atoi (argv[i + 1]);
    }
    else if (!strcmp (argv[i], NHTTPD_ARG_MAXCONN) && i < argc - 1)
    {
      _httpd_max_connections = atoi (argv[i + 1]);
    }
  }

  log_verbose2 ("socket bind to port '%d'", _httpd_port);

  /* init built-in services */

  /* httpd_register("/httpd/list", service_list); */

  _httpd_connection = calloc (_httpd_max_connections, sizeof (conndata_t));
  for (i = 0; i < _httpd_max_connections; i++)
  {
    memset ((char *) &_httpd_connection[i], 0, sizeof (_httpd_connection[i]));
  }

#ifdef WIN32
  /* 
     if (_beginthread (WSAReaper, 0, NULL) == -1) { log_error1 ("Winsock
     reaper thread failed to start"); return herror_new("httpd_init",
     THREAD_BEGIN_ERROR, "_beginthread() failed while starting WSAReaper"); } 
   */
#endif

  /* create socket */
#ifdef HAVE_SSL
  SSLCert = hoption_get(HOPTION_SSL_CERT);
  SSLPass = hoption_get(HOPTION_SSL_PASS);
  SSLCA = hoption_get(HOPTION_SSL_CA);
  log_verbose3("SSL: %s %s", SSLCert, SSLCA);
  if (SSLCert[0] != '\0'){

    start_ssl();
    status = hsocket_init_ssl(&_httpd_socket, SSLCert, SSLPass, SSLCA);
  }
  else
#endif
  {
    status = hsocket_init (&_httpd_socket);
  }

  if (status != H_OK)
  {
    return status;
  }

  return hsocket_bind (&_httpd_socket, _httpd_port);
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_register
 * -----------------------------------------------------
 */

int
httpd_register_secure(const char *ctx, httpd_service func, httpd_auth auth)
{
  hservice_t *service;

  if (!(service = (hservice_t *) malloc (sizeof (hservice_t))))
  {
    log_error1("malloc failed");
    return -1;
  }

  service->next = NULL;
  service->auth = auth;
  service->func = func;
  strcpy (service->ctx, ctx);

  log_verbose3 ("register service:t(%p):%s", service, SAVE_STR (ctx));
  if (_httpd_services_head == NULL)
  {
    _httpd_services_head = _httpd_services_tail = service;
  }
  else
  {
    _httpd_services_tail->next = service;
    _httpd_services_tail = service;
  }

  return 1;
}

int
httpd_register(const char *ctx, httpd_service service)
{
  return httpd_register_secure(ctx, service, NULL);
}

int
httpd_register_default_secure(const char *ctx, httpd_service service, httpd_auth auth)
{
  int ret;

  ret = httpd_register_secure(ctx, service, auth);

  /* this is broken, but working */
  _httpd_services_default = _httpd_services_tail;

  return ret;
}

int
httpd_register_default(const char *ctx, httpd_service service)
{
  return httpd_register_default_secure(ctx, service, NULL);
}

int
httpd_get_port(void)
{
  return _httpd_port;
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_services
 * -----------------------------------------------------
 */
hservice_t *
httpd_services ()
{
  return _httpd_services_head;
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_services
 * -----------------------------------------------------
 */
static void
hservice_free (hservice_t * service)
{
  free (service);
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_find_service
 * -----------------------------------------------------
 */
static hservice_t *
httpd_find_service (const char *ctx)
{
  hservice_t *cur = _httpd_services_head;

  while (cur != NULL)
  {
    if (!strcmp (cur->ctx, ctx))
    {
      return cur;
    }
    cur = cur->next;
  }

  return _httpd_services_default;
}


/*
 * -----------------------------------------------------
 * FUNCTION: httpd_response_set_content_type
 * -----------------------------------------------------
 */
void
httpd_response_set_content_type (httpd_conn_t * res, const char *content_type)
{
  strncpy (res->content_type, content_type, 25);
}


/*
 * -----------------------------------------------------
 * FUNCTION: httpd_response_send_header
 * -----------------------------------------------------
 */
herror_t
httpd_send_header (httpd_conn_t * res, int code, const char *text)
{
  struct tm stm;
  time_t nw;
  char buffer[255];
  char header[1024];
  hpair_t *cur;
  herror_t status;

  /* set status code */
  sprintf (header, "HTTP/1.1 %d %s\r\n", code, text);

  /* set date */
  nw = time (NULL);
  localtime_r (&nw, &stm);
  strftime (buffer, 255, "Date: %a, %d %b %Y %H:%M:%S GMT\r\n", &stm);
  strcat (header, buffer);

  /* set content-type */
  /* 
   * if (res->content_type[0] == '\0') { strcat(header, "Content-Type:
   * text/html\r\n"); } else { sprintf(buffer, "Content-Type: %s\r\n",
   * res->content_type); strcat(header, buffer); }
   */

  /* set server name */
  strcat (header, "Server: Nano HTTPD library\r\n");

  /* set _httpd_connection status */
  // strcat (header, "Connection: close\r\n");

  /* add pairs */
  for(cur = res->header; cur; cur = cur->next)
  {
    sprintf (buffer, "%s: %s\r\n", cur->key, cur->value);
    strcat (header, buffer);
  }

  /* set end of header */
  strcat (header, "\r\n");

  /* send header */
  if ((status = hsocket_nsend (res->sock, header, strlen (header))) != H_OK)
    return status;

  res->out = http_output_stream_new (res->sock, res->header);
  return H_OK;
}


herror_t
httpd_send_internal_error (httpd_conn_t * conn, const char *errmsg)
{
  const char *template1 =
    "<html><body><h3>Error!</h3><hr> Message: '%s' </body></html>\r\n";

  char buffer[4064];
  char buflen[5];
  sprintf (buffer, template1, errmsg);
  snprintf (buflen, 5, "%d", strlen (buffer));
  httpd_set_header (conn, HEADER_CONTENT_LENGTH, buflen);
  httpd_send_header (conn, 500, "INTERNAL");
  return hsocket_nsend (conn->sock, buffer, strlen (buffer));
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_request_print
 * -----------------------------------------------------
 */
static void
httpd_request_print (hrequest_t * req)
{
  hpair_t *pair;

  log_verbose1 ("++++++ Request +++++++++");
  log_verbose2 (" Method : '%s'",
                (req->method == HTTP_REQUEST_POST) ? "POST" : "GET");
  log_verbose2 (" Path   : '%s'", req->path);
  log_verbose2 (" Spec   : '%s'",
                (req->version == HTTP_1_0) ? "HTTP/1.0" : "HTTP/1.1");
  log_verbose1 (" Parsed query string :");

  pair = req->query;
  while (pair != NULL)
  {
    log_verbose3 (" %s = '%s'", pair->key, pair->value);
    pair = pair->next;
  }
  log_verbose1 (" Parsed header :");
  pair = req->header;
  while (pair != NULL)
  {
    log_verbose3 (" %s = '%s'", pair->key, pair->value);
    pair = pair->next;
  }
  log_verbose1 ("++++++++++++++++++++++++");

}


httpd_conn_t *
httpd_new (hsocket_t sock)
{
  httpd_conn_t *conn = (httpd_conn_t *) malloc (sizeof (httpd_conn_t));
  conn->sock = sock;
  conn->out = NULL;
  conn->content_type[0] = '\0';
  conn->header = NULL;

  return conn;
}


void
httpd_free (httpd_conn_t * conn)
{
  if(!conn)
  return;
  if (conn->out != NULL)
    http_output_stream_free (conn->out);

  if (conn->header != NULL)
    hpairnode_free_deep (conn->header);

  free (conn);
}

void
do_req_timeout (int signum)
{
/*
    struct sigaction req_timeout;
    memset(&req_timeout, 0, sizeof(&req_timeout));
    req_timeout.sa_handler=SIG_IGN;
    sigaction(SIGALRM, &req_timeout, NULL);
*/

  // XXX this is not real pretty, is there a better way?
  log_verbose1 ("Thread timeout.");
#ifdef WIN32
  _endthread ();
#else
  pthread_exit (0);
#endif
}

static int httpd_decode_authorization(const char *value, char **user, char **pass)
{

  unsigned char *tmp, *tmp2;

  tmp = malloc(strlen(value) * 2);
#ifdef WIN32
  memset(tmp, 0, strlen(value)*2);
  value = strstr(value, ' ');
#else
  bzero(tmp, strlen(value) * 2);
  value = index(value, ' ');
#endif

  
  value++;
  log_debug2("Authorization (base64) = \"%s\"", value);

  base64_decode(value, tmp);

  log_debug2("Authorization (ascii) = \"%s\"", tmp);

#ifdef WIN32
  tmp2 = strstr(tmp, ':');
#else
  tmp2 = index(tmp, ':');
#endif
  *tmp2++ = '\0';

  *pass = strdup(tmp2);
  *user = strdup(tmp);

  free(tmp);

  return 1;
}

static int httpd_authenticate_request(hrequest_t *req, httpd_auth auth)
{
  char *user, *pass;
  char *authorization;
  int ret;

  if (!auth)
    return 1;

  if (!(authorization = hpairnode_get_ignore_case(req->header, HEADER_AUTHORIZATION))) {
    return 0;
  }

  if (!httpd_decode_authorization(authorization, &user, &pass))
  {
    log_error1("httpd_base64_decode_failed");
    return 0;
  }

  if (!(ret = auth(user, pass)))
    log_info1("Authentication failed");

  free(user);
  free(pass);

  return ret;
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_session_main
 * -----------------------------------------------------
 */
#ifdef WIN32
static unsigned _stdcall
httpd_session_main (void *data)
#else
static void *
httpd_session_main (void *data)
#endif
{
  conndata_t *conn = (conndata_t *) data;
  const char *msg = "SESSION 1.0\n";
  int len = strlen (msg);
  int done = 0;
  char buffer[256];             /* temp buffer for recv() */
  char header[4064];            /* received header */
  hrequest_t *req = NULL;       /* only for test */
  httpd_conn_t *rconn = NULL;
  hservice_t *service = NULL;
  herror_t status;

  header[0] = '\0';
  len = 0;

  log_verbose1 ("starting httpd_session_main()");
#ifdef HAVE_SSL
  if (!_httpd_socket.sslCtx)
  {
    log_verbose1 ("Using HTTP");
  }
  else
  {
    log_verbose1 ("Using HTTPS");
    conn->sock.ssl = init_ssl (_httpd_socket.sslCtx, conn->sock.sock, SSL_SERVER);
    hsocket_block (conn->sock, 0);
    if (conn->sock.ssl == NULL)
    {
      done = 1;
    }
  }
#endif
  conn->atime = time ((time_t) 0);
  /* call the service */
/*  req = hrequest_new_from_buffer (header);*/

  while (!done)
  {
    log_verbose1 ("starting HTTP request");

    rconn = httpd_new (conn->sock);

    if ((status = hrequest_new_from_socket (conn->sock, &req)) != H_OK)
    {
      /* "Request parse error!" */
      if (herror_code (status) != HSOCKET_ERROR_SSLCLOSE)
      {
        httpd_send_internal_error (rconn, herror_message (status));
        herror_release (status);
      }
      done = 1;
    }
    else
    {
      char *conn_str = hpairnode_get_ignore_case (req->header, HEADER_CONNECTION);
      if (conn_str && strncasecmp (conn_str, "close", 5) == 0)
      {
        done = 1;
      }
      if (!done)
      {
        done = req->version == HTTP_1_0 ? 1 : 0;
      }
      httpd_request_print (req);

      service = httpd_find_service (req->path);
      if (service != NULL)
      {
        log_verbose3 ("service '%s' for '%s' found", service->ctx, req->path);

        if (httpd_authenticate_request(req, service->auth)) {

          if (service->func != NULL)
          {
            service->func (rconn, req);
            if (rconn->out && rconn->out->type == HTTP_TRANSFER_CONNECTION_CLOSE) {
              log_verbose1 ("Connection close requested");
              done = 1;
            }
          }
          else
          {
            sprintf (buffer, "service '%s' not registered properly (func == NULL)", req->path);
            log_verbose1 (buffer);
            httpd_send_internal_error (rconn, buffer);
          }
        }
	else {

          httpd_set_header(rconn, HEADER_WWW_AUTHENTICATE, "Basic realm=\"nanoHTTP\"");
          httpd_send_header(rconn, 401, "Unauthorized");
          hsocket_send(conn->sock, "<html><head><title>Unauthorized</title></header><body><h1>Unauthorized</h1></body></html>");
	}
      }
      else
      {
        sprintf (buffer, "service '%s' not found", req->path);
        log_verbose1 (buffer);
        httpd_send_internal_error (rconn, buffer);
      }
    }
  }

  hsocket_close (conn->sock);
  log_verbose1 ("Marking connection as available");
  conn->sock.sock = 0;
  hrequest_free (req);
  httpd_free (rconn);

#ifdef WIN32
  CloseHandle ((HANDLE) conn->tid);
  _endthread ();
  return 0;
#else
  /* pthread_exits automagically */
  return NULL;
#endif
}

int
httpd_set_header (httpd_conn_t * conn, const char *key, const char *value)
{
  hpair_t *p;

  if (conn == NULL)
  {
    log_warn1 ("Connection object is NULL");
    return 0;
  }
  p = conn->header;
  while (p != NULL)
  {
    if (p->key != NULL)
    {
      if (!strcmp (p->key, key))
      {
        free (p->value);
        p->value = (char *) malloc (strlen (value) + 1);
        strcpy (p->value, value);
        return 1;
      }
    }
    p = p->next;
  }

  conn->header = hpairnode_new (key, value, conn->header);
  return 0;
}

void
httpd_set_headers (httpd_conn_t * conn, hpair_t * header)
{
  while (header)
  {
    httpd_set_header (conn, header->key, header->value);
    header = header->next;
  }
}

int
httpd_add_header (httpd_conn_t *conn, const char *key, const char *value)
{
  if (!conn)
  {
    log_warn1("Connection object is NULL");
    return 0;
  }

  conn->header = hpairnode_new(key, value, conn->header);

  return 1;
}

void
httpd_add_headers (httpd_conn_t *conn, const hpair_t *values)
{
  if (!conn)
  {
    log_warn1("Connection object is NULL");
    return;
  }

  while (values)
  {
    httpd_add_header(conn, values->key, values->value);
    values = values->next;
  }
  return;
}

/*
 * -----------------------------------------------------
 * FUNCTION: httpd_term
 * -----------------------------------------------------
 */
#ifdef WIN32
BOOL WINAPI
httpd_term (DWORD sig)
{
  // log_debug2 ("Got signal %d", sig);
  if (sig == _httpd_terminate_signal)
    _httpd_run = 0;
  return TRUE;
}

#else

void
httpd_term (int sig)
{
  log_debug2 ("Got signal %d", sig);
  if (sig == _httpd_terminate_signal)
    _httpd_run = 0;
}

#endif

/*
 * -----------------------------------------------------
 * FUNCTION: _httpd_register_signal_handler
 * -----------------------------------------------------
 */
static void
_httpd_register_signal_handler (void)
{
  log_verbose2 ("registering termination signal handler (SIGNAL:%d)",
                _httpd_terminate_signal);
#ifdef WIN32
  if (SetConsoleCtrlHandler ((PHANDLER_ROUTINE) httpd_term, TRUE) == FALSE)
  {
    log_error1 ("Unable to install console event handler!");
  }

#else
  signal (_httpd_terminate_signal, httpd_term);
#endif

  return;
}

/*--------------------------------------------------
FUNCTION: _httpd_wait_for_empty_conn
----------------------------------------------------*/
static conndata_t *
_httpd_wait_for_empty_conn (void)
{
  int i;
  for (i = 0;; i++)
  {
    if (!_httpd_run)
      return NULL;

    if (i >= _httpd_max_connections)
    {
      system_sleep (1);
      i = 0;
    }
    else if (_httpd_connection[i].sock.sock == 0)
    {
      break;
    }
  }

  return &_httpd_connection[i];
}

/*
 * -----------------------------------------------------
 * FUNCTION: _httpd_start_thread
 * -----------------------------------------------------
 */
static void
_httpd_start_thread (conndata_t * conn)
{
  int err;

#ifdef WIN32
  conn->tid = (HANDLE) _beginthreadex (NULL, 65535, httpd_session_main, conn, 0, &err);
#else
  pthread_attr_init (&(conn->attr));

#ifdef PTHREAD_CREATE_DETACHED
  pthread_attr_setdetachstate (&(conn->attr), PTHREAD_CREATE_DETACHED);
#endif

  pthread_sigmask (SIG_BLOCK, &thrsigset, NULL);
  err = pthread_create (&(conn->tid), &(conn->attr), httpd_session_main, conn);
  if (err)
    log_error2 ("Error creating thread: ('%d')", err);
#endif
}


/*
 * -----------------------------------------------------
 * FUNCTION: httpd_run
 * -----------------------------------------------------
 */

herror_t
httpd_run (void)
{
  herror_t err;
  conndata_t *conn;
  fd_set fds;
  struct timeval timeout;

  log_verbose1 ("starting run routine");

  timeout.tv_sec = 1;
  timeout.tv_usec = 0;

#ifndef WIN32
  sigemptyset (&thrsigset);
  sigaddset (&thrsigset, SIGALRM);
#endif

  /* listen to port */
  if ((err = hsocket_listen (_httpd_socket)) != H_OK)
  {
    log_error2 ("httpd_run(): '%d'", herror_message (err));
    return err;
  }
  log_verbose2 ("listening to port '%d'", _httpd_port);

  /* register signal handler */
  _httpd_register_signal_handler ();

  /* make the socket non blocking */
  if ((err = hsocket_block (_httpd_socket, 0)) != H_OK)
  {
    log_error2 ("httpd_run(): '%s'", herror_message (err));
    return err;
  }

  while (_httpd_run)
  {
    /* Get an empty connection struct */
    conn = _httpd_wait_for_empty_conn ();
    if (!_httpd_run)
      break;


    /* Wait for a socket to accept */
    while (_httpd_run)
    {

      /* set struct timeval to the proper timeout */
      timeout.tv_sec = 1;
      timeout.tv_usec = 0;

      /* zero and set file descriptior */
      FD_ZERO (&fds);
      FD_SET (_httpd_socket.sock, &fds);

      /* select socket descriptor */
      switch (select (_httpd_socket.sock + 1, &fds, NULL, NULL, &timeout))
      {
      case 0:
        /* descriptor is not ready */
        continue;
      case -1:
        /* got a signal? */
        continue;
      default:
        /* no nothing */
        break;
      }
      if (FD_ISSET (_httpd_socket.sock, &fds))
      {
        break;
      }
    }

    /* check signal status */
    if (!_httpd_run)
      break;

    /* Accept a socket */
    err = hsocket_accept (_httpd_socket, &(conn->sock));
    if (err != H_OK 
  /* TODO (#1#) is this check neccessary?
     && herror_code (err) == SSL_ERROR_INIT*/
  )
    {
      hsocket_close (conn->sock);

      hsocket_init(&(conn->sock));

      log_error1 (herror_message (err));
      continue;
    }
    else if (err != H_OK)
    {
      log_error2 ("Can not accept socket: %s", herror_message (err));
      return err;               /* this is hard core! */
    }

    /* Now start a thread */
    _httpd_start_thread (conn);
  }
  free (_httpd_connection);
  return 0;
}

void
httpd_destroy (void)
{
  hservice_t *tmp, *cur = _httpd_services_head;

  while (cur != NULL)
  {
    tmp = cur->next;
    hservice_free (cur);
    cur = tmp;
  }

  hsocket_module_destroy ();

  return;
}

#ifdef WIN32

static void
WSAReaper (void *x)
{
  short int connections;
  short int i;
  char junk[10];
  int rc;
  time_t ctime;

  for (;;)
  {
    connections = 0;
    ctime = time ((time_t) 0);
    for (i = 0; i < _httpd_max_connections; i++)
    {
      if (_httpd_connection[i].tid == 0)
        continue;
      GetExitCodeThread ((HANDLE) _httpd_connection[i].tid, (PDWORD) & rc);
      if (rc != STILL_ACTIVE)
        continue;
      connections++;
      if ((ctime - _httpd_connection[i].atime < _httpd_max_idle) ||
          (_httpd_connection[i].atime == 0))
        continue;
      log_verbose3 ("Reaping socket %u from (runtime ~= %d seconds)",
                    _httpd_connection[i].sock,
                    ctime - _httpd_connection[i].atime);
      shutdown (_httpd_connection[i].sock.sock, 2);
      while (recv (_httpd_connection[i].sock.sock, junk, sizeof (junk), 0) >
             0)
      {
      };
      closesocket (_httpd_connection[i].sock.sock);
      _httpd_connection[i].sock.sock = 0;
      TerminateThread (_httpd_connection[i].tid, (DWORD) & rc);
      CloseHandle (_httpd_connection[i].tid);
      memset ((char *) &_httpd_connection[i], 0,
              sizeof (_httpd_connection[i]));
    }
    Sleep (100);
  }
  return;
}

#endif

unsigned char *
httpd_get_postdata (httpd_conn_t * conn, hrequest_t * req, long *received,
                    long max)
{
  char *content_length_str;
  long content_length = 0;
  unsigned char *postdata = NULL;

  if (req->method == HTTP_REQUEST_POST)
  {

    content_length_str = hpairnode_get_ignore_case (req->header, HEADER_CONTENT_LENGTH);

    if (content_length_str != NULL)
      content_length = atol (content_length_str);

  }
  else
  {
    log_warn1 ("Not a POST method");
    return NULL;
  }

  if (content_length > max && max != -1)
    return NULL;

  if (content_length == 0)
  {
    *received = 0;
    postdata = (char *) malloc (1);
    postdata[0] = '\0';
    return postdata;
  }
  postdata = (unsigned char *) malloc (content_length + 1);
  if (postdata == NULL)
  {
    log_error1 ("Not enough memory");
    return NULL;
  }
  if (http_input_stream_read (req->in, postdata, (int) content_length) > 0)
  {
    *received = content_length;
    postdata[content_length] = '\0';
    return postdata;
  }
  free (postdata);
  return NULL;
}




/*
  MIME support httpd_mime_* function set
*/

static void
_httpd_mime_get_boundary (httpd_conn_t * conn, char *dest)
{
  sprintf (dest, "---=.Part_NH_%p", conn);
  log_verbose2 ("boundary= \"%s\"", dest);

  return;
}


/**
  Begin MIME multipart/related POST 
  Returns: H_OK  or error flag
*/
herror_t
httpd_mime_send_header (httpd_conn_t * conn, const char *related_start, const char *related_start_info, const char *related_type, int code, const char *text)
{
  char buffer[300];
  char temp[250];
  char boundary[250];

  /* Set Content-type Set multipart/related parameter type=..; start=.. ; start-info= ..; boundary=...  
  using sprintf instead of snprintf because visual c does not support snprintf */

  sprintf (buffer, "multipart/related;");

  if (related_type)
  {
    snprintf (temp, 75, " type=\"%s\";", related_type);
    strcat (buffer, temp);
  }

  if (related_start)
  {
    snprintf (temp, 250, " start=\"%s\";", related_start);
    strcat (buffer, temp);
  }

  if (related_start_info)
  {
    snprintf (temp, 250, " start-info=\"%s\";", related_start_info);
    strcat (buffer, temp);
  }

  _httpd_mime_get_boundary (conn, boundary);
  snprintf (temp, 250, " boundary=\"%s\"", boundary);
  strcat (buffer, temp);

  httpd_set_header (conn, HEADER_CONTENT_TYPE, buffer);

  return httpd_send_header (conn, code, text);
}


/**
  Send boundary and part header and continue 
  with next part
*/
herror_t
httpd_mime_next (httpd_conn_t * conn, const char *content_id, const char *content_type, const char *transfer_encoding)
{
  herror_t status;
  char buffer[512];
  char boundary[75];

  /* Get the boundary string */
  _httpd_mime_get_boundary (conn, boundary);
  sprintf (buffer, "\r\n--%s\r\n", boundary);

  /* Send boundary */
  status = http_output_stream_write (conn->out, (const byte_t *) buffer, strlen (buffer));

  if (status != H_OK)
    return status;

  /* Send Content header */
  sprintf (buffer, "%s: %s\r\n%s: %s\r\n%s: %s\r\n\r\n",
           HEADER_CONTENT_TYPE, content_type ? content_type : "text/plain",
           HEADER_CONTENT_TRANSFER_ENCODING,
           transfer_encoding ? transfer_encoding : "binary",
           HEADER_CONTENT_ID,
           content_id ? content_id : "<content-id-not-set>");

  status = http_output_stream_write (conn->out, (const byte_t *) buffer, strlen (buffer));

  return status;
}

/**
  Send boundary and part header and continue 
  with next part
*/
herror_t
httpd_mime_send_file (httpd_conn_t * conn, const char *content_id, const char *content_type, const char *transfer_encoding, const char *filename)
{
  byte_t buffer[MAX_FILE_BUFFER_SIZE];
  herror_t status;
  FILE *fd;
  size_t size;

  if ((fd = fopen (filename, "rb")) == NULL)
    return herror_new ("httpd_mime_send_file", FILE_ERROR_OPEN, "Can not open file '%d'", filename);

  status = httpd_mime_next (conn, content_id, content_type, transfer_encoding);
  if (status != H_OK)
  {
    fclose (fd);
    return status;
  }

  while (!feof (fd))
  {
    size = fread (buffer, 1, MAX_FILE_BUFFER_SIZE, fd);
    if (size == -1)
    {
      fclose (fd);
      return herror_new ("httpd_mime_send_file", FILE_ERROR_READ, "Can not read from file '%d'", filename);
    }

    status = http_output_stream_write (conn->out, buffer, size);
    if (status != H_OK)
    {
      fclose (fd);
      return status;
    }
  }

  fclose (fd);
  return H_OK;
}

/**
  Finish MIME request 
  Returns: H_OK  or error flag
*/
herror_t
httpd_mime_end (httpd_conn_t * conn)
{
  herror_t status;
  char buffer[512];
  char boundary[75];

  /* Get the boundary string */
  _httpd_mime_get_boundary (conn, boundary);
  sprintf (buffer, "\r\n--%s--\r\n\r\n", boundary);

  /* Send boundary */
  status = http_output_stream_write (conn->out, (const byte_t *) buffer, strlen (buffer));

  if (status != H_OK)
    return status;

  /* Flush put stream */
  status = http_output_stream_flush (conn->out);

  return status;
}