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