* fix bug in locale declaration array (missing ,)
[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         char wd[SIZ];
103         FILE *FD;
104         int fd;
105         getcwd(wd, SIZ);
106         lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
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
127         current_child = 0;
128
129         /* Close stdin/stdout/stderr and replace them with /dev/null.
130          * We don't just call close() because we don't want these fd's
131          * to be reused for other files.
132          */
133         chdir("/");
134
135         signal(SIGHUP, SIG_IGN);
136         signal(SIGINT, SIG_IGN);
137         signal(SIGQUIT, SIG_IGN);
138
139         child = fork();
140         if (child != 0) {
141                 exit(0);
142         }
143
144         setsid();
145         umask(0);
146         freopen("/dev/null", "r", stdin);
147         freopen("/dev/null", "w", stdout);
148         freopen("/dev/null", "w", stderr);
149         signal(SIGTERM, graceful_shutdown_watcher);
150         signal(SIGHUP, graceful_shutdown_watcher);
151
152         do {
153                 current_child = fork();
154
155         
156                 if (current_child < 0) {
157                         perror("fork");
158                         ShutDownLibCitadel ();
159                         exit(errno);
160                 }
161         
162                 else if (current_child == 0) {  /* child process */
163                         signal(SIGHUP, graceful_shutdown);
164
165                         return; /* continue starting webcit. */
166                 }
167                 else { /* watcher process */
168                         if (pid_file) {
169                                 fp = fopen(pid_file, "w");
170                                 if (fp != NULL) {
171                                         fprintf(fp, "%d\n", getpid());
172                                         fclose(fp);
173                                 }
174                         }
175                         waitpid(current_child, &status, 0);
176                 }
177
178                 do_restart = 0;
179
180                 /* Did the main process exit with an actual exit code? */
181                 if (WIFEXITED(status)) {
182
183                         /* Exit code 0 means the watcher should exit */
184                         if (WEXITSTATUS(status) == 0) {
185                                 do_restart = 0;
186                         }
187
188                         /* Exit code 101-109 means the watcher should exit */
189                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
190                                 do_restart = 0;
191                         }
192
193                         /* Any other exit code means we should restart. */
194                         else {
195                                 do_restart = 1;
196                         }
197                 }
198
199                 /* Any other type of termination (signals, etc.) should also restart. */
200                 else {
201                         do_restart = 1;
202                 }
203
204         } while (do_restart);
205
206         if (pid_file) {
207                 unlink(pid_file);
208         }
209         ShutDownLibCitadel ();
210         exit(WEXITSTATUS(status));
211 }
212
213 /*
214  * Spawn an additional worker thread into the pool.
215  */
216 void spawn_another_worker_thread()
217 {
218         pthread_t SessThread;   /* Thread descriptor */
219         pthread_attr_t attr;    /* Thread attributes */
220         int ret;
221
222         lprintf(3, "Creating a new thread\n");
223
224         /* set attributes for the new thread */
225         pthread_attr_init(&attr);
226         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
227
228         /*
229          * Our per-thread stacks need to be bigger than the default size, otherwise
230          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
231          * 64-bit Linux.
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
335         WildFireInitBacktrace(argv[0], 2);
336
337         start_modules ();
338
339 #ifdef DBG_PRINNT_HOOKS_AT_START
340 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
341 #endif
342
343         /* Ensure that we are linked to the correct version of libcitadel */
344         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
345                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
346                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
347                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
348                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
349                 return(1);
350         }
351
352         strcpy(uds_listen_path, "");
353
354         /* Parse command line */
355 #ifdef HAVE_OPENSSL
356         while ((a = getopt(argc, argv, "h:i:p:t:T:B:x:dD:G:cfsZ")) != EOF)
357 #else
358         while ((a = getopt(argc, argv, "h:i:p:t:T:B:x:dD:G:cfZ")) != EOF)
359 #endif
360                 switch (a) {
361                 case 'h':
362                         hdir = strdup(optarg);
363                         relh=hdir[0]!='/';
364                         if (!relh) safestrncpy(webcitdir, hdir,
365                                                                    sizeof webcitdir);
366                         else
367                                 safestrncpy(relhome, relhome,
368                                                         sizeof relhome);
369                         /* free(hdir); TODO: SHOULD WE DO THIS? */
370                         home_specified = 1;
371                         home=1;
372                         break;
373                 case 'd':
374                         running_as_daemon = 1;
375                         break;
376                 case 'D':
377                         pidfile = strdup(optarg);
378                         running_as_daemon = 1;
379                         break;
380                 case 'B': /* Basesize */
381                         basesize = atoi(optarg);
382                         if (basesize > 2)
383                                 StartLibCitadel(basesize);
384                         break;
385                 case 'i':
386                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
387                         break;
388                 case 'p':
389                         http_port = atoi(optarg);
390                         if (http_port == 0) {
391                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
392                         }
393                         break;
394                 case 't':
395                         safestrncpy(tracefile, optarg, sizeof tracefile);
396                         freopen(tracefile, "w", stdout);
397                         freopen(tracefile, "w", stderr);
398                         freopen(tracefile, "r", stdin);
399                         break;
400                 case 'T':
401                         LoadTemplates = atoi(optarg);
402                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
403                         dbg_bactrace_template_errors = (LoadTemplates && (1<<2)) != 0;
404                         break;
405                 case 'Z':
406                         DisableGzip = 1;
407                         break;
408                 case 'x':
409                         verbosity = atoi(optarg);
410                         break;
411                 case 'f':
412                         follow_xff = 1;
413                         break;
414                 case 'c':
415                         server_cookie = malloc(256);
416                         if (server_cookie != NULL) {
417                                 safestrncpy(server_cookie,
418                                        "Set-cookie: wcserver=",
419                                         256);
420                                 if (gethostname
421                                     (&server_cookie[strlen(server_cookie)],
422                                      200) != 0) {
423                                         lprintf(2, "gethostname: %s\n",
424                                                 strerror(errno));
425                                         free(server_cookie);
426                                 }
427                         }
428                         break;
429                 case 's':
430                         is_https = 1;
431                         break;
432                 case 'G':
433                         DumpTemplateI18NStrings = 1;
434                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
435                         I18nDumpFile = optarg;
436                         break;
437                 default:
438                         fprintf(stderr, "usage: webcit "
439                                 "[-i ip_addr] [-p http_port] "
440                                 "[-t tracefile] [-c] [-f] "
441                                 "[-T Templatedebuglevel] "
442                                 "[-d] [-Z] [-G i18ndumpfile] "
443 #ifdef HAVE_OPENSSL
444                                 "[-s] "
445 #endif
446                                 "[remotehost [remoteport]]\n");
447                         return 1;
448                 }
449
450         if (optind < argc) {
451                 ctdlhost = argv[optind];
452                 if (++optind < argc)
453                         ctdlport = argv[optind];
454         }
455
456         /* daemonize, if we were asked to */
457         if (!DumpTemplateI18NStrings && running_as_daemon) {
458                 start_daemon(pidfile);
459         }
460         else {
461                 signal(SIGHUP, graceful_shutdown);
462         }
463
464         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
465         LoadIconDir(static_icon_dir);
466
467         /* Tell 'em who's in da house */
468         lprintf(1, PACKAGE_STRING "\n");
469         lprintf(1, "Copyright (C) 1996-2009 by the Citadel development team.\n"
470                 "This software is distributed under the terms of the "
471                 "GNU General Public License.\n\n"
472         );
473
474
475         /* initialize the International Bright Young Thing */
476
477         initialise_modules();
478         initialize_viewdefs();
479         initialize_axdefs();
480
481         InitTemplateCache();
482         if (DumpTemplateI18NStrings) {
483                 FILE *fd;
484                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
485                 if (StrLength(I18nDump) < 50) {
486                         lprintf(1, "********************************************************************************\n");
487                         lprintf(1, "*        No strings found in templates! are you shure they're there?           *\n");
488                         lprintf(1, "********************************************************************************\n");
489                         return -1;
490                 }
491                 fd = fopen(I18nDumpFile, "w");
492                 if (fd == NULL) {
493                         lprintf(1, "********************************************************************************\n");
494                         lprintf(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
495                         lprintf(1, "********************************************************************************\n");
496                         return -1;
497                 }
498                 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
499                 fclose(fd);
500                 return 0;
501         }
502
503
504         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
505         icalerror_errors_are_fatal = 0;
506
507         /* Use our own prefix on tzid's generated from system tzdata */
508         icaltimezone_set_tzid_prefix("/citadel.org/");
509
510         /*
511          * Set up a place to put thread-specific data.
512          * We only need a single pointer per thread - it points to the
513          * wcsession struct to which the thread is currently bound.
514          */
515         if (pthread_key_create(&MyConKey, NULL) != 0) {
516                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
517         }
518         InitialiseSemaphores ();
519
520         /*
521          * Set up a place to put thread-specific SSL data.
522          * We don't stick this in the wcsession struct because SSL starts
523          * up before the session is bound, and it gets torn down between
524          * transactions.
525          */
526 #ifdef HAVE_OPENSSL
527         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
528                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
529         }
530 #endif
531
532         /*
533          * Bind the server to our favorite port.
534          * There is no need to check for errors, because ig_tcp_server()
535          * exits if it doesn't succeed.
536          */
537
538         if (!IsEmptyStr(uds_listen_path)) {
539                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
540                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
541         }
542         else {
543                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
544                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
545         }
546
547         lprintf(2, "Listening on socket %d\n", msock);
548         signal(SIGPIPE, SIG_IGN);
549
550         pthread_mutex_init(&SessionListMutex, NULL);
551
552         /*
553          * Start up the housekeeping thread
554          */
555         pthread_attr_init(&attr);
556         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
557         pthread_create(&SessThread, &attr,
558                        (void *(*)(void *)) housekeeping_loop, NULL);
559
560
561         /*
562          * If this is an HTTPS server, fire up SSL
563          */
564 #ifdef HAVE_OPENSSL
565         if (is_https) {
566                 init_ssl();
567         }
568 #endif
569
570         /* Start a few initial worker threads */
571         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
572                 spawn_another_worker_thread();
573         }
574
575         /* now the original thread becomes another worker */
576         worker_entry();
577         ShutDownLibCitadel ();
578         return 0;
579 }
580
581
582 void ShutDownWebcit(void)
583 {
584         free_zone_directory ();
585         icaltimezone_release_zone_tab ();
586         icalmemory_free_ring ();
587         ShutDownLibCitadel ();
588         shutdown_modules ();
589 #ifdef HAVE_OPENSSL
590         if (is_https) {
591                 shutdown_ssl();
592         }
593 #endif
594 }
595
596 /*
597  * Entry point for worker threads
598  */
599 void worker_entry(void)
600 {
601         int ssock;
602         int i = 0;
603         int fail_this_transaction = 0;
604         int ret;
605         struct timeval tv;
606         fd_set readset, tempset;
607         ParsedHttpHdrs Hdr;
608
609         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
610         Hdr.HR.eReqType = eGET;
611         http_new_modules(&Hdr); 
612         tv.tv_sec = 0;
613         tv.tv_usec = 10000;
614         FD_ZERO(&readset);
615         FD_SET(msock, &readset);
616
617         do {
618                 /* Only one thread can accept at a time */
619                 fail_this_transaction = 0;
620                 ssock = -1; 
621                 errno = EAGAIN;
622                 do {
623                         ret = -1; /* just one at once should select... */
624                         begin_critical_section(S_SELECT);
625
626                         FD_ZERO(&tempset);
627                         if (msock > 0) FD_SET(msock, &tempset);
628                         tv.tv_sec = 0;
629                         tv.tv_usec = 10000;
630                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
631                         end_critical_section(S_SELECT);
632                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
633                         {/* EINTR and EAGAIN are thrown but not of interest. */
634                                 lprintf(2, "accept() failed:%d %s\n",
635                                         errno, strerror(errno));
636                         }
637                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
638                         {/* Successfully selected, and still not shutting down? Accept! */
639                                 ssock = accept(msock, NULL, 0);
640                         }
641                         
642                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
643
644                 if ((msock == -1)||(time_to_die))
645                 {/* ok, we're going down. */
646                         int shutdown = 0;
647
648                         /* the first to come here will have to do the cleanup.
649                          * make shure its realy just one.
650                          */
651                         begin_critical_section(S_SHUTDOWN);
652                         if (msock == -1)
653                         {
654                                 msock = -2;
655                                 shutdown = 1;
656                         }
657                         end_critical_section(S_SHUTDOWN);
658                         if (shutdown == 1)
659                         {/* we're the one to cleanup the mess. */
660                                 http_destroy_modules(&Hdr);
661                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
662                                 shutdown_sessions();
663                                 lprintf(2, "master shutdown: waiting for others\n");
664                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
665                                 lprintf(2, "master shutdown: cleaning up sessions\n");
666                                 do_housekeeping();
667                                 lprintf(2, "master shutdown: cleaning up libical\n");
668
669                                 ShutDownWebcit();
670
671                                 lprintf(2, "master shutdown exiting!.\n");                              
672                                 exit(0);
673                         }
674                         break;
675                 }
676                 if (ssock < 0 ) continue;
677
678                 if (msock < 0) {
679                         if (ssock > 0) close (ssock);
680                         lprintf(2, "inbetween.");
681                         pthread_exit(NULL);
682                 } else { /* Got it? do some real work! */
683                         /* Set the SO_REUSEADDR socket option */
684                         i = 1;
685                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
686                                    &i, sizeof(i));
687
688                         /* If we are an HTTPS server, go crypto now. */
689 #ifdef HAVE_OPENSSL
690                         if (is_https) {
691                                 if (starttls(ssock) != 0) {
692                                         fail_this_transaction = 1;
693                                         close(ssock);
694                                 }
695                         }
696                         else 
697                         {
698                                 int fdflags; 
699                                 fdflags = fcntl(ssock, F_GETFL);
700                                 if (fdflags < 0)
701                                         lprintf(1, "unable to get server socket flags! %s \n",
702                                                 strerror(errno));
703                                 fdflags = fdflags | O_NONBLOCK;
704                                 if (fcntl(ssock, F_SETFD, fdflags) < 0)
705                                         lprintf(1, "unable to set server socket nonblocking flags! %s \n",
706                                                 strerror(errno));
707                         }
708 #endif
709
710                         if (fail_this_transaction == 0) {
711                                 Hdr.http_sock = ssock;
712
713                                 /* Perform an HTTP transaction... */
714                                 context_loop(&Hdr);
715
716                                 /* Shut down SSL/TLS if required... */
717 #ifdef HAVE_OPENSSL
718                                 if (is_https) {
719                                         endtls();
720                                 }
721 #endif
722
723                                 /* ...and close the socket. */
724                                 if (Hdr.http_sock > 0)
725                                         lingering_close(ssock);
726                                 http_detach_modules(&Hdr);
727
728                         }
729
730                 }
731
732         } while (!time_to_die);
733
734         http_destroy_modules(&Hdr);
735         lprintf (1, "bye\n");
736         pthread_exit(NULL);
737 }
738
739 /*
740  * print log messages 
741  * logs to stderr if loglevel is lower than the verbosity set at startup
742  *
743  * loglevel     level of the message
744  * format       the printf like format string
745  * ...          the strings to put into format
746  */
747 int lprintf(int loglevel, const char *format, ...)
748 {
749         va_list ap;
750
751         if (loglevel <= verbosity) {
752                 va_start(ap, format);
753                 vfprintf(stderr, format, ap);
754                 va_end(ap);
755                 fflush(stderr);
756         }
757         return 1;
758 }
759
760
761 /*
762  * print the actual stack frame.
763  */
764 void wc_backtrace(void)
765 {
766 #ifdef HAVE_BACKTRACE
767         void *stack_frames[50];
768         size_t size, i;
769         char **strings;
770
771
772         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
773         strings = backtrace_symbols(stack_frames, size);
774         for (i = 0; i < size; i++) {
775                 if (strings != NULL)
776                         lprintf(1, "%s\n", strings[i]);
777                 else
778                         lprintf(1, "%p\n", stack_frames[i]);
779         }
780         free(strings);
781 #endif
782 }
783
784
785
786