* Allow the '-S' command line option, so the cipher suites can be specified without...
[citadel.git] / webcit / webserver.c
1 /*
2  * $Id$
3  *
4  * This contains a simple multithreaded TCP server manager.  It sits around
5  * waiting on the specified port for incoming HTTP connections.  When a
6  * connection is established, it calls context_loop() from context_loop.c.
7  *
8  * Copyright (c) 1996-2009 by the citadel.org developers.
9  * This program is released under the terms of the GNU General Public License v3.
10  *
11  */
12
13 #include "webcit.h"
14 #include "webserver.h"
15
16 #if HAVE_BACKTRACE
17 #include <execinfo.h>
18 #endif
19 #include "modules_init.h"
20 #ifndef HAVE_SNPRINTF
21 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
22 #endif
23
24 int verbosity = 9;              /* Logging level */
25 int msock;                      /* master listening socket */
26 int is_https = 0;               /* Nonzero if I am an HTTPS service */
27 int follow_xff = 0;             /* Follow X-Forwarded-For: header */
28 int home_specified = 0;         /* did the user specify a homedir? */
29 int time_to_die = 0;            /* Nonzero if server is shutting down */
30 int DisableGzip = 0;
31 extern void *context_loop(ParsedHttpHdrs *Hdr);
32 extern void *housekeeping_loop(void);
33 extern pthread_mutex_t SessionListMutex;
34 extern pthread_key_t MyConKey;
35
36 extern int ig_tcp_server(char *ip_addr, int port_number, int queue_len);
37 extern int ig_uds_server(char *sockpath, int queue_len);
38
39
40 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
41 char file_crpt_file_key[PATH_MAX]="";
42 char file_crpt_file_csr[PATH_MAX]="";
43 char file_crpt_file_cer[PATH_MAX]="";
44
45 char socket_dir[PATH_MAX];                      /* where to talk to our citadel server */
46 const char editor_absolut_dir[PATH_MAX]=EDITORDIR;      /* nailed to what configure gives us. */
47 char static_dir[PATH_MAX];              /* calculated on startup */
48 char static_local_dir[PATH_MAX];                /* calculated on startup */
49 char static_icon_dir[PATH_MAX];          /* where should we find our mime icons? */
50 char  *static_dirs[]={                          /* needs same sort order as the web mapping */
51         (char*)static_dir,                      /* our templates on disk */
52         (char*)static_local_dir,                /* user provided templates disk */
53         (char*)editor_absolut_dir,              /* the editor on disk */
54         (char*)static_icon_dir                  /* our icons... */
55 };
56
57 /*
58  * Subdirectories from which the client may request static content
59  *
60  * (If you add more, remember to increment 'ndirs' below)
61  */
62 char *static_content_dirs[] = {
63         "static",                     /* static templates */
64         "static.local",               /* site local static templates */
65         "tiny_mce"                    /* rich text editor */
66 };
67
68 int ndirs=3;
69
70
71 char *server_cookie = NULL;     /* our Cookie connection to the client */
72 int http_port = PORT_NUM;       /* Port to listen on */
73 char *ctdlhost = DEFAULT_HOST;  /* our name */
74 char *ctdlport = DEFAULT_PORT;  /* our Port */
75 int setup_wizard = 0;           /* should we run the setup wizard? \todo */
76 char wizard_filename[PATH_MAX]; /* where's the setup wizard? */
77 int running_as_daemon = 0;      /* should we deamonize on startup? */
78
79
80
81 /*
82  * Shut us down the regular way.
83  * signum is the signal we want to forward
84  */
85 pid_t current_child;
86 void graceful_shutdown_watcher(int signum) {
87         lprintf (1, "bye; shutting down watcher.");
88         kill(current_child, signum);
89         if (signum != SIGHUP)
90                 exit(0);
91 }
92
93
94
95
96 /*
97  * Shut us down the regular way.
98  * signum is the signal we want to forward
99  */
100 pid_t current_child;
101 void graceful_shutdown(int signum) {
102         FILE *FD;
103         int fd;
104
105         lprintf (1, "WebCit is being shut down on signal %d.\n", signum);
106         fd = msock;
107         msock = -1;
108         time_to_die = 1;
109         FD=fdopen(fd, "a+");
110         fflush (FD);
111         fclose (FD);
112         close(fd);
113 }
114
115
116 /*
117  * Start running as a daemon.
118  */
119 void start_daemon(char *pid_file) 
120 {
121         int status = 0;
122         pid_t child = 0;
123         FILE *fp;
124         int do_restart = 0;
125         int rv;
126         FILE *rvfp = NULL;
127
128         current_child = 0;
129
130         /* Close stdin/stdout/stderr and replace them with /dev/null.
131          * We don't just call close() because we don't want these fd's
132          * to be reused for other files.
133          */
134         rv = chdir("/");
135
136         signal(SIGHUP, SIG_IGN);
137         signal(SIGINT, SIG_IGN);
138         signal(SIGQUIT, SIG_IGN);
139
140         child = fork();
141         if (child != 0) {
142                 exit(0);
143         }
144
145         setsid();
146         umask(0);
147         rvfp = freopen("/dev/null", "r", stdin);
148         rvfp = freopen("/dev/null", "w", stdout);
149         rvfp = freopen("/dev/null", "w", stderr);
150         signal(SIGTERM, graceful_shutdown_watcher);
151         signal(SIGHUP, graceful_shutdown_watcher);
152
153         do {
154                 current_child = fork();
155
156         
157                 if (current_child < 0) {
158                         perror("fork");
159                         ShutDownLibCitadel ();
160                         exit(errno);
161                 }
162         
163                 else if (current_child == 0) {  /* child process */
164                         signal(SIGHUP, graceful_shutdown);
165
166                         return; /* continue starting webcit. */
167                 }
168                 else { /* watcher process */
169                         if (pid_file) {
170                                 fp = fopen(pid_file, "w");
171                                 if (fp != NULL) {
172                                         fprintf(fp, "%d\n", getpid());
173                                         fclose(fp);
174                                 }
175                         }
176                         waitpid(current_child, &status, 0);
177                 }
178
179                 do_restart = 0;
180
181                 /* Did the main process exit with an actual exit code? */
182                 if (WIFEXITED(status)) {
183
184                         /* Exit code 0 means the watcher should exit */
185                         if (WEXITSTATUS(status) == 0) {
186                                 do_restart = 0;
187                         }
188
189                         /* Exit code 101-109 means the watcher should exit */
190                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
191                                 do_restart = 0;
192                         }
193
194                         /* Any other exit code means we should restart. */
195                         else {
196                                 do_restart = 1;
197                         }
198                 }
199
200                 /* Any other type of termination (signals, etc.) should also restart. */
201                 else {
202                         do_restart = 1;
203                 }
204
205         } while (do_restart);
206
207         if (pid_file) {
208                 unlink(pid_file);
209         }
210         ShutDownLibCitadel ();
211         exit(WEXITSTATUS(status));
212 }
213
214 /*
215  * Spawn an additional worker thread into the pool.
216  */
217 void spawn_another_worker_thread()
218 {
219         pthread_t SessThread;   /* Thread descriptor */
220         pthread_attr_t attr;    /* Thread attributes */
221         int ret;
222
223         lprintf(3, "Creating a new thread.  Pool size is now %d\n", ++num_threads);
224
225         /* set attributes for the new thread */
226         pthread_attr_init(&attr);
227         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
228
229         /*
230          * Our per-thread stacks need to be bigger than the default size,
231          * otherwise the MIME parser crashes on FreeBSD.
232          */
233         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
234                 lprintf(1, "pthread_attr_setstacksize: %s\n",
235                         strerror(ret));
236                 pthread_attr_destroy(&attr);
237         }
238
239         /* now create the thread */
240         if (pthread_create(&SessThread, &attr,
241                            (void *(*)(void *)) worker_entry, NULL)
242             != 0) {
243                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
244         }
245
246         /* free up the attributes */
247         pthread_attr_destroy(&attr);
248 }
249
250 /* #define DBG_PRINNT_HOOKS_AT_START */
251 #ifdef DBG_PRINNT_HOOKS_AT_START
252 const char foobuf[32];
253 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
254 #endif 
255 extern int dbg_analyze_msg;
256 extern int dbg_bactrace_template_errors;
257 extern int DumpTemplateI18NStrings;
258 extern StrBuf *I18nDump;
259 void InitTemplateCache(void);
260 extern int LoadTemplates;
261
262 extern HashList *HandlerHash;
263
264
265
266 void
267 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
268 {
269         char dirbuffer[PATH_MAX]="";
270         /* calculate all our path on a central place */
271     /* where to keep our config */
272         
273 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
274         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
275                          (home&!relh)?webcitdir:basedir, \
276              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
277              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
278                          relhome, \
279              (relhome[0]!='\0')?"/":"",\
280                          dirbuffer,\
281                          (dirbuffer[0]!='\0')?"/":"");
282         basedir=RUNDIR;
283         COMPUTE_DIRECTORY(socket_dir);
284         basedir=WWWDIR "/static";
285         COMPUTE_DIRECTORY(static_dir);
286         basedir=WWWDIR "/static/icons";
287         COMPUTE_DIRECTORY(static_icon_dir);
288         basedir=WWWDIR "/static.local";
289         COMPUTE_DIRECTORY(static_local_dir);
290         StripSlashes(static_dir, 1);
291         StripSlashes(static_icon_dir, 1);
292         StripSlashes(static_local_dir, 1);
293
294         snprintf(file_crpt_file_key,
295                  sizeof file_crpt_file_key, 
296                  "%s/citadel.key",
297                  ctdl_key_dir);
298         snprintf(file_crpt_file_csr,
299                  sizeof file_crpt_file_csr, 
300                  "%s/citadel.csr",
301                  ctdl_key_dir);
302         snprintf(file_crpt_file_cer,
303                  sizeof file_crpt_file_cer, 
304                  "%s/citadel.cer",
305                  ctdl_key_dir);
306
307         /* we should go somewhere we can leave our coredump, if enabled... */
308         lprintf(9, "Changing directory to %s\n", socket_dir);
309         if (chdir(webcitdir) != 0) {
310                 perror("chdir");
311         }
312 }
313 /*
314  * Here's where it all begins.
315  */
316 int main(int argc, char **argv)
317 {
318         size_t basesize = 2;            /* how big should strbufs be on creation? */
319         pthread_t SessThread;           /* Thread descriptor */
320         pthread_attr_t attr;            /* Thread attributes */
321         int a, i;                       /* General-purpose variables */
322         char tracefile[PATH_MAX];
323         char ip_addr[256]="0.0.0.0";
324         int relh=0;
325         int home=0;
326         int home_specified=0;
327         char relhome[PATH_MAX]="";
328         char webcitdir[PATH_MAX] = DATADIR;
329         char *pidfile = NULL;
330         char *hdir;
331         const char *basedir = NULL;
332         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
333         const char *I18nDumpFile = NULL;
334         FILE *rvfp = NULL;
335
336         WildFireInitBacktrace(argv[0], 2);
337
338         start_modules ();
339
340 #ifdef DBG_PRINNT_HOOKS_AT_START
341 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
342 #endif
343
344         /* Ensure that we are linked to the correct version of libcitadel */
345         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
346                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
347                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
348                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
349                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
350                 return(1);
351         }
352
353         strcpy(uds_listen_path, "");
354
355         /* Parse command line */
356 #ifdef HAVE_OPENSSL
357         while ((a = getopt(argc, argv, "h:i:p:t:T:B:x:dD:G:cfsS:Z")) != EOF)
358 #else
359         while ((a = getopt(argc, argv, "h:i:p:t:T:B:x:dD:G:cfZ")) != EOF)
360 #endif
361                 switch (a) {
362                 case 'h':
363                         hdir = strdup(optarg);
364                         relh=hdir[0]!='/';
365                         if (!relh) {
366                                 safestrncpy(webcitdir, hdir, sizeof webcitdir);
367                         }
368                         else {
369                                 safestrncpy(relhome, relhome, sizeof relhome);
370                         }
371                         /* free(hdir); TODO: SHOULD WE DO THIS? */
372                         home_specified = 1;
373                         home=1;
374                         break;
375                 case 'd':
376                         running_as_daemon = 1;
377                         break;
378                 case 'D':
379                         pidfile = strdup(optarg);
380                         running_as_daemon = 1;
381                         break;
382                 case 'B': /* Basesize */
383                         basesize = atoi(optarg);
384                         if (basesize > 2)
385                                 StartLibCitadel(basesize);
386                         break;
387                 case 'i':
388                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
389                         break;
390                 case 'p':
391                         http_port = atoi(optarg);
392                         if (http_port == 0) {
393                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
394                         }
395                         break;
396                 case 't':
397                         safestrncpy(tracefile, optarg, sizeof tracefile);
398                         rvfp = freopen(tracefile, "w", stdout);
399                         rvfp = freopen(tracefile, "w", stderr);
400                         rvfp = freopen(tracefile, "r", stdin);
401                         break;
402                 case 'T':
403                         LoadTemplates = atoi(optarg);
404                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
405                         dbg_bactrace_template_errors = (LoadTemplates && (1<<2)) != 0;
406                         break;
407                 case 'Z':
408                         DisableGzip = 1;
409                         break;
410                 case 'x':
411                         verbosity = atoi(optarg);
412                         break;
413                 case 'f':
414                         follow_xff = 1;
415                         break;
416                 case 'c':
417                         server_cookie = malloc(256);
418                         if (server_cookie != NULL) {
419                                 safestrncpy(server_cookie,
420                                        "Set-cookie: wcserver=",
421                                         256);
422                                 if (gethostname
423                                     (&server_cookie[strlen(server_cookie)],
424                                      200) != 0) {
425                                         lprintf(2, "gethostname: %s\n",
426                                                 strerror(errno));
427                                         free(server_cookie);
428                                 }
429                         }
430                         break;
431 #ifdef HAVE_OPENSSL
432                 case 's':
433                         is_https = 1;
434                         break;
435                 case 'S':
436                         is_https = 1;
437                         ssl_cipher_list = strdup(optarg);
438                         break;
439 #endif
440                 case 'G':
441                         DumpTemplateI18NStrings = 1;
442                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
443                         I18nDumpFile = optarg;
444                         break;
445                 default:
446                         fprintf(stderr, "usage: webcit "
447                                 "[-i ip_addr] [-p http_port] "
448                                 "[-t tracefile] [-c] [-f] "
449                                 "[-T Templatedebuglevel] "
450                                 "[-d] [-Z] [-G i18ndumpfile] "
451 #ifdef HAVE_OPENSSL
452                                 "[-s] [-S cipher_suites]"
453 #endif
454                                 "[remotehost [remoteport]]\n");
455                         return 1;
456                 }
457
458         if (optind < argc) {
459                 ctdlhost = argv[optind];
460                 if (++optind < argc)
461                         ctdlport = argv[optind];
462         }
463
464         /* daemonize, if we were asked to */
465         if (!DumpTemplateI18NStrings && running_as_daemon) {
466                 start_daemon(pidfile);
467         }
468         else {
469                 signal(SIGHUP, graceful_shutdown);
470         }
471
472         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
473         LoadIconDir(static_icon_dir);
474
475         /* Tell 'em who's in da house */
476         lprintf(1, PACKAGE_STRING "\n");
477         lprintf(1, "Copyright (C) 1996-2009 by the Citadel development team.\n"
478                 "This software is distributed under the terms of the "
479                 "GNU General Public License.\n\n"
480         );
481
482
483         /* initialize the International Bright Young Thing */
484
485         initialise_modules();
486         initialize_viewdefs();
487         initialize_axdefs();
488
489         InitTemplateCache();
490         if (DumpTemplateI18NStrings) {
491                 FILE *fd;
492                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
493                 if (StrLength(I18nDump) < 50) {
494                         lprintf(1, "********************************************************************************\n");
495                         lprintf(1, "*        No strings found in templates! are you shure they're there?           *\n");
496                         lprintf(1, "********************************************************************************\n");
497                         return -1;
498                 }
499                 fd = fopen(I18nDumpFile, "w");
500                 if (fd == NULL) {
501                         lprintf(1, "********************************************************************************\n");
502                         lprintf(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
503                         lprintf(1, "********************************************************************************\n");
504                         return -1;
505                 }
506                 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
507                 fclose(fd);
508                 return 0;
509         }
510
511
512         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
513         icalerror_errors_are_fatal = 0;
514
515         /* Use our own prefix on tzid's generated from system tzdata */
516         icaltimezone_set_tzid_prefix("/citadel.org/");
517
518         /*
519          * Set up a place to put thread-specific data.
520          * We only need a single pointer per thread - it points to the
521          * wcsession struct to which the thread is currently bound.
522          */
523         if (pthread_key_create(&MyConKey, NULL) != 0) {
524                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
525         }
526         InitialiseSemaphores ();
527
528         /*
529          * Set up a place to put thread-specific SSL data.
530          * We don't stick this in the wcsession struct because SSL starts
531          * up before the session is bound, and it gets torn down between
532          * transactions.
533          */
534 #ifdef HAVE_OPENSSL
535         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
536                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
537         }
538 #endif
539
540         /*
541          * Bind the server to our favorite port.
542          * There is no need to check for errors, because ig_tcp_server()
543          * exits if it doesn't succeed.
544          */
545
546         if (!IsEmptyStr(uds_listen_path)) {
547                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
548                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
549         }
550         else {
551                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
552                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
553         }
554
555         lprintf(2, "Listening on socket %d\n", msock);
556         signal(SIGPIPE, SIG_IGN);
557
558         pthread_mutex_init(&SessionListMutex, NULL);
559
560         /*
561          * Start up the housekeeping thread
562          */
563         pthread_attr_init(&attr);
564         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
565         pthread_create(&SessThread, &attr,
566                        (void *(*)(void *)) housekeeping_loop, NULL);
567
568
569         /*
570          * If this is an HTTPS server, fire up SSL
571          */
572 #ifdef HAVE_OPENSSL
573         if (is_https) {
574                 init_ssl();
575         }
576 #endif
577
578         /* Start a few initial worker threads */
579         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
580                 spawn_another_worker_thread();
581         }
582
583         /* now the original thread becomes another worker */
584         worker_entry();
585         ShutDownLibCitadel ();
586         return 0;
587 }
588
589
590 void ShutDownWebcit(void)
591 {
592         free_zone_directory ();
593         icaltimezone_release_zone_tab ();
594         icalmemory_free_ring ();
595         ShutDownLibCitadel ();
596         shutdown_modules ();
597 #ifdef HAVE_OPENSSL
598         if (is_https) {
599                 shutdown_ssl();
600         }
601 #endif
602 }
603
604 /*
605  * Entry point for worker threads
606  */
607 void worker_entry(void)
608 {
609         int ssock;
610         int i = 0;
611         int fail_this_transaction = 0;
612         int ret;
613         struct timeval tv;
614         fd_set readset, tempset;
615         ParsedHttpHdrs Hdr;
616
617         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
618         Hdr.HR.eReqType = eGET;
619         http_new_modules(&Hdr); 
620         tv.tv_sec = 0;
621         tv.tv_usec = 10000;
622         FD_ZERO(&readset);
623         FD_SET(msock, &readset);
624
625         do {
626                 /* Only one thread can accept at a time */
627                 fail_this_transaction = 0;
628                 ssock = -1; 
629                 errno = EAGAIN;
630                 do {
631                         ret = -1; /* just one at once should select... */
632                         begin_critical_section(S_SELECT);
633
634                         FD_ZERO(&tempset);
635                         if (msock > 0) FD_SET(msock, &tempset);
636                         tv.tv_sec = 0;
637                         tv.tv_usec = 10000;
638                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
639                         end_critical_section(S_SELECT);
640                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
641                         {/* EINTR and EAGAIN are thrown but not of interest. */
642                                 lprintf(2, "accept() failed:%d %s\n",
643                                         errno, strerror(errno));
644                         }
645                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
646                         {/* Successfully selected, and still not shutting down? Accept! */
647                                 ssock = accept(msock, NULL, 0);
648                         }
649                         
650                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
651
652                 if ((msock == -1)||(time_to_die))
653                 {/* ok, we're going down. */
654                         int shutdown = 0;
655
656                         /* the first to come here will have to do the cleanup.
657                          * make shure its realy just one.
658                          */
659                         begin_critical_section(S_SHUTDOWN);
660                         if (msock == -1)
661                         {
662                                 msock = -2;
663                                 shutdown = 1;
664                         }
665                         end_critical_section(S_SHUTDOWN);
666                         if (shutdown == 1)
667                         {/* we're the one to cleanup the mess. */
668                                 http_destroy_modules(&Hdr);
669                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
670                                 shutdown_sessions();
671                                 lprintf(2, "master shutdown: waiting for others\n");
672                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
673                                 lprintf(2, "master shutdown: cleaning up sessions\n");
674                                 do_housekeeping();
675                                 lprintf(2, "master shutdown: cleaning up libical\n");
676
677                                 ShutDownWebcit();
678
679                                 lprintf(2, "master shutdown exiting!.\n");                              
680                                 exit(0);
681                         }
682                         break;
683                 }
684                 if (ssock < 0 ) continue;
685
686                 if (msock < 0) {
687                         if (ssock > 0) close (ssock);
688                         lprintf(2, "inbetween.");
689                         pthread_exit(NULL);
690                 } else { /* Got it? do some real work! */
691                         /* Set the SO_REUSEADDR socket option */
692                         i = 1;
693                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
694                                    &i, sizeof(i));
695
696                         /* If we are an HTTPS server, go crypto now. */
697 #ifdef HAVE_OPENSSL
698                         if (is_https) {
699                                 if (starttls(ssock) != 0) {
700                                         fail_this_transaction = 1;
701                                         close(ssock);
702                                 }
703                         }
704                         else 
705                         {
706                                 int fdflags; 
707                                 fdflags = fcntl(ssock, F_GETFL);
708                                 if (fdflags < 0)
709                                         lprintf(1, "unable to get server socket flags! %s \n",
710                                                 strerror(errno));
711                                 fdflags = fdflags | O_NONBLOCK;
712                                 if (fcntl(ssock, F_SETFD, fdflags) < 0)
713                                         lprintf(1, "unable to set server socket nonblocking flags! %s \n",
714                                                 strerror(errno));
715                         }
716 #endif
717
718                         if (fail_this_transaction == 0) {
719                                 Hdr.http_sock = ssock;
720
721                                 /* Perform an HTTP transaction... */
722                                 context_loop(&Hdr);
723
724                                 /* Shut down SSL/TLS if required... */
725 #ifdef HAVE_OPENSSL
726                                 if (is_https) {
727                                         endtls();
728                                 }
729 #endif
730
731                                 /* ...and close the socket. */
732                                 if (Hdr.http_sock > 0)
733                                         lingering_close(ssock);
734                                 http_detach_modules(&Hdr);
735
736                         }
737
738                 }
739
740         } while (!time_to_die);
741
742         http_destroy_modules(&Hdr);
743         lprintf (1, "bye\n");
744         pthread_exit(NULL);
745 }
746
747 /*
748  * print log messages 
749  * logs to stderr if loglevel is lower than the verbosity set at startup
750  *
751  * loglevel     level of the message
752  * format       the printf like format string
753  * ...          the strings to put into format
754  */
755 int lprintf(int loglevel, const char *format, ...)
756 {
757         va_list ap;
758
759         if (loglevel <= verbosity) {
760                 va_start(ap, format);
761                 vfprintf(stderr, format, ap);
762                 va_end(ap);
763                 fflush(stderr);
764         }
765         return 1;
766 }
767
768
769 /*
770  * print the actual stack frame.
771  */
772 void wc_backtrace(void)
773 {
774 #ifdef HAVE_BACKTRACE
775         void *stack_frames[50];
776         size_t size, i;
777         char **strings;
778
779
780         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
781         strings = backtrace_symbols(stack_frames, size);
782         for (i = 0; i < size; i++) {
783                 if (strings != NULL)
784                         lprintf(1, "%s\n", strings[i]);
785                 else
786                         lprintf(1, "%p\n", stack_frames[i]);
787         }
788         free(strings);
789 #endif
790 }
791
792
793
794