8488020effca4a1cae9f12ea8aed938d4de86b5a
[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(int*);
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 void
266 webcit_calc_dirs_n_files(int relh, const char *basedir, int home, char *webcitdir, char *relhome)
267 {
268         char dirbuffer[PATH_MAX]="";
269         /* calculate all our path on a central place */
270     /* where to keep our config */
271         
272 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
273         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
274                          (home&!relh)?webcitdir:basedir, \
275              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
276              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
277                          relhome, \
278              (relhome[0]!='\0')?"/":"",\
279                          dirbuffer,\
280                          (dirbuffer[0]!='\0')?"/":"");
281         basedir=RUNDIR;
282         COMPUTE_DIRECTORY(socket_dir);
283         basedir=WWWDIR "/static";
284         COMPUTE_DIRECTORY(static_dir);
285         basedir=WWWDIR "/static/icons";
286         COMPUTE_DIRECTORY(static_icon_dir);
287         basedir=WWWDIR "/static.local";
288         COMPUTE_DIRECTORY(static_local_dir);
289
290         snprintf(file_crpt_file_key,
291                  sizeof file_crpt_file_key, 
292                  "%s/citadel.key",
293                  ctdl_key_dir);
294         snprintf(file_crpt_file_csr,
295                  sizeof file_crpt_file_csr, 
296                  "%s/citadel.csr",
297                  ctdl_key_dir);
298         snprintf(file_crpt_file_cer,
299                  sizeof file_crpt_file_cer, 
300                  "%s/citadel.cer",
301                  ctdl_key_dir);
302
303         /* we should go somewhere we can leave our coredump, if enabled... */
304         lprintf(9, "Changing directory to %s\n", socket_dir);
305         if (chdir(webcitdir) != 0) {
306                 perror("chdir");
307         }
308 }
309 /*
310  * Here's where it all begins.
311  */
312 int main(int argc, char **argv)
313 {
314         pthread_t SessThread;           /* Thread descriptor */
315         pthread_attr_t attr;            /* Thread attributes */
316         int a, i;                       /* General-purpose variables */
317         char tracefile[PATH_MAX];
318         char ip_addr[256]="0.0.0.0";
319         int relh=0;
320         int home=0;
321         int home_specified=0;
322         char relhome[PATH_MAX]="";
323         char webcitdir[PATH_MAX] = DATADIR;
324         char *pidfile = NULL;
325         char *hdir;
326         const char *basedir;
327 #ifdef ENABLE_NLS
328         char *locale = NULL;
329         char *mo = NULL;
330 #endif /* ENABLE_NLS */
331         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
332         const char *I18nDumpFile = NULL;
333
334         WildFireInitBacktrace(argv[0], 2);
335
336         start_modules ();
337
338 #ifdef DBG_PRINNT_HOOKS_AT_START
339 /*      dbg_PrintHash(HandlerHash, nix, NULL);*/
340 #endif
341
342         /* Ensure that we are linked to the correct version of libcitadel */
343         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
344                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
345                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
346                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
347                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
348                 return(1);
349         }
350
351         strcpy(uds_listen_path, "");
352
353         /* Parse command line */
354 #ifdef HAVE_OPENSSL
355         while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:G:cfsZ")) != EOF)
356 #else
357         while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:G:cfZ")) != EOF)
358 #endif
359                 switch (a) {
360                 case 'h':
361                         hdir = strdup(optarg);
362                         relh=hdir[0]!='/';
363                         if (!relh) safestrncpy(webcitdir, hdir,
364                                                                    sizeof webcitdir);
365                         else
366                                 safestrncpy(relhome, relhome,
367                                                         sizeof relhome);
368                         /* free(hdir); TODO: SHOULD WE DO THIS? */
369                         home_specified = 1;
370                         home=1;
371                         break;
372                 case 'd':
373                         running_as_daemon = 1;
374                         break;
375                 case 'D':
376                         pidfile = strdup(optarg);
377                         running_as_daemon = 1;
378                         break;
379                 case 'i':
380                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
381                         break;
382                 case 'p':
383                         http_port = atoi(optarg);
384                         if (http_port == 0) {
385                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
386                         }
387                         break;
388                 case 't':
389                         safestrncpy(tracefile, optarg, sizeof tracefile);
390                         freopen(tracefile, "w", stdout);
391                         freopen(tracefile, "w", stderr);
392                         freopen(tracefile, "r", stdin);
393                         break;
394                 case 'T':
395                         LoadTemplates = atoi(optarg);
396                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
397                         dbg_bactrace_template_errors = (LoadTemplates && (1<<2)) != 0;
398                         break;
399                 case 'Z':
400                         DisableGzip = 1;
401                         break;
402                 case 'x':
403                         verbosity = atoi(optarg);
404                         break;
405                 case 'f':
406                         follow_xff = 1;
407                         break;
408                 case 'c':
409                         server_cookie = malloc(256);
410                         if (server_cookie != NULL) {
411                                 safestrncpy(server_cookie,
412                                        "Set-cookie: wcserver=",
413                                         256);
414                                 if (gethostname
415                                     (&server_cookie[strlen(server_cookie)],
416                                      200) != 0) {
417                                         lprintf(2, "gethostname: %s\n",
418                                                 strerror(errno));
419                                         free(server_cookie);
420                                 }
421                         }
422                         break;
423                 case 's':
424                         is_https = 1;
425                         break;
426                 case 'G':
427                         DumpTemplateI18NStrings = 1;
428                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
429                         I18nDumpFile = optarg;
430                         break;
431                 default:
432                         fprintf(stderr, "usage: webcit "
433                                 "[-i ip_addr] [-p http_port] "
434                                 "[-t tracefile] [-c] [-f] "
435                                 "[-T Templatedebuglevel] "
436                                 "[-d] [-Z] [-G i18ndumpfile] "
437 #ifdef HAVE_OPENSSL
438                                 "[-s] "
439 #endif
440                                 "[remotehost [remoteport]]\n");
441                         return 1;
442                 }
443
444         if (optind < argc) {
445                 ctdlhost = argv[optind];
446                 if (++optind < argc)
447                         ctdlport = argv[optind];
448         }
449
450         /* daemonize, if we were asked to */
451         if (!DumpTemplateI18NStrings && running_as_daemon) {
452                 start_daemon(pidfile);
453         }
454         else {
455                 signal(SIGHUP, graceful_shutdown);
456         }
457
458         webcit_calc_dirs_n_files(relh, basedir, home, webcitdir, relhome);
459         LoadIconDir(static_icon_dir);
460
461         /* Tell 'em who's in da house */
462         lprintf(1, PACKAGE_STRING "\n");
463         lprintf(1, "Copyright (C) 1996-2009 by the Citadel development team.\n"
464                 "This software is distributed under the terms of the "
465                 "GNU General Public License.\n\n"
466         );
467
468
469         /* initialize the International Bright Young Thing */
470 #ifdef ENABLE_NLS
471         initialize_locales();
472
473
474         locale = setlocale(LC_ALL, "");
475
476         mo = malloc(strlen(webcitdir) + 20);
477         lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
478         free(mo);
479         lprintf(9, "Text domain: %s\n", textdomain("webcit"));
480         lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
481 #endif
482
483
484
485
486
487
488
489
490
491
492         initialise_modules();
493         initialize_viewdefs();
494         initialize_axdefs();
495
496         InitTemplateCache();
497         if (DumpTemplateI18NStrings) {
498                 FILE *fd;
499                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
500                 if (StrLength(I18nDump) < 50) {
501                         lprintf(1, "********************************************************************************\n");
502                         lprintf(1, "*        No strings found in templates! are you shure they're there?           *\n");
503                         lprintf(1, "********************************************************************************\n");
504                         return -1;
505                 }
506                 fd = fopen(I18nDumpFile, "w");
507                 if (fd == NULL) {
508                         lprintf(1, "********************************************************************************\n");
509                         lprintf(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
510                         lprintf(1, "********************************************************************************\n");
511                         return -1;
512                 }
513                 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
514                 fclose(fd);
515                 return 0;
516         }
517
518
519         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
520         icalerror_errors_are_fatal = 0;
521
522         /* Use our own prefix on tzid's generated from system tzdata */
523         icaltimezone_set_tzid_prefix("/citadel.org/");
524
525         /*
526          * Set up a place to put thread-specific data.
527          * We only need a single pointer per thread - it points to the
528          * wcsession struct to which the thread is currently bound.
529          */
530         if (pthread_key_create(&MyConKey, NULL) != 0) {
531                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
532         }
533         InitialiseSemaphores ();
534
535         /*
536          * Set up a place to put thread-specific SSL data.
537          * We don't stick this in the wcsession struct because SSL starts
538          * up before the session is bound, and it gets torn down between
539          * transactions.
540          */
541 #ifdef HAVE_OPENSSL
542         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
543                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
544         }
545 #endif
546
547         /*
548          * Bind the server to our favorite port.
549          * There is no need to check for errors, because ig_tcp_server()
550          * exits if it doesn't succeed.
551          */
552
553         if (!IsEmptyStr(uds_listen_path)) {
554                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
555                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
556         }
557         else {
558                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
559                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
560         }
561
562         lprintf(2, "Listening on socket %d\n", msock);
563         signal(SIGPIPE, SIG_IGN);
564
565         pthread_mutex_init(&SessionListMutex, NULL);
566
567         /*
568          * Start up the housekeeping thread
569          */
570         pthread_attr_init(&attr);
571         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
572         pthread_create(&SessThread, &attr,
573                        (void *(*)(void *)) housekeeping_loop, NULL);
574
575
576         /*
577          * If this is an HTTPS server, fire up SSL
578          */
579 #ifdef HAVE_OPENSSL
580         if (is_https) {
581                 init_ssl();
582         }
583 #endif
584
585         /* Start a few initial worker threads */
586         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
587                 spawn_another_worker_thread();
588         }
589
590         /* now the original thread becomes another worker */
591         worker_entry();
592         ShutDownLibCitadel ();
593         return 0;
594 }
595
596
597 void ShutDownWebcit(void)
598 {
599         free_zone_directory ();
600         icaltimezone_release_zone_tab ();
601         icalmemory_free_ring ();
602         ShutDownLibCitadel ();
603         shutdown_modules ();
604 #ifdef ENABLE_NLS
605         ShutdownLocale();
606 #endif
607 #ifdef HAVE_OPENSSL
608         if (is_https) {
609                 shutdown_ssl();
610         }
611 #endif
612 }
613
614 /*
615  * Entry point for worker threads
616  */
617 void worker_entry(void)
618 {
619         int ssock;
620         int i = 0;
621         int fail_this_transaction = 0;
622         int ret;
623         struct timeval tv;
624         fd_set readset, tempset;
625
626         tv.tv_sec = 0;
627         tv.tv_usec = 10000;
628         FD_ZERO(&readset);
629         FD_SET(msock, &readset);
630
631         do {
632                 /* Only one thread can accept at a time */
633                 fail_this_transaction = 0;
634                 ssock = -1; 
635                 errno = EAGAIN;
636                 do {
637                         ret = -1; /* just one at once should select... */
638                         begin_critical_section(S_SELECT);
639
640                         FD_ZERO(&tempset);
641                         if (msock > 0) FD_SET(msock, &tempset);
642                         tv.tv_sec = 0;
643                         tv.tv_usec = 10000;
644                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
645                         end_critical_section(S_SELECT);
646                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
647                         {/* EINTR and EAGAIN are thrown but not of interest. */
648                                 lprintf(2, "accept() failed:%d %s\n",
649                                         errno, strerror(errno));
650                         }
651                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
652                         {/* Successfully selected, and still not shutting down? Accept! */
653                                 ssock = accept(msock, NULL, 0);
654                         }
655                         
656                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
657
658                 if ((msock == -1)||(time_to_die))
659                 {/* ok, we're going down. */
660                         int shutdown = 0;
661
662                         /* the first to come here will have to do the cleanup.
663                          * make shure its realy just one.
664                          */
665                         begin_critical_section(S_SHUTDOWN);
666                         if (msock == -1)
667                         {
668                                 msock = -2;
669                                 shutdown = 1;
670                         }
671                         end_critical_section(S_SHUTDOWN);
672                         if (shutdown == 1)
673                         {/* we're the one to cleanup the mess. */
674                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
675                                 shutdown_sessions();
676                                 lprintf(2, "master shutdown: waiting for others\n");
677                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
678                                 lprintf(2, "master shutdown: cleaning up sessions\n");
679                                 do_housekeeping();
680                                 lprintf(2, "master shutdown: cleaning up libical\n");
681
682                                 ShutDownWebcit();
683
684                                 lprintf(2, "master shutdown exiting!.\n");                              
685                                 exit(0);
686                         }
687                         break;
688                 }
689                 if (ssock < 0 ) continue;
690
691                 if (msock < 0) {
692                         if (ssock > 0) close (ssock);
693                         lprintf(2, "inbetween.");
694                         pthread_exit(NULL);
695                 } else { /* Got it? do some real work! */
696                         /* Set the SO_REUSEADDR socket option */
697                         i = 1;
698                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
699                                    &i, sizeof(i));
700
701                         /* If we are an HTTPS server, go crypto now. */
702 #ifdef HAVE_OPENSSL
703                         if (is_https) {
704                                 if (starttls(ssock) != 0) {
705                                         fail_this_transaction = 1;
706                                         close(ssock);
707                                 }
708                         }
709                         else 
710                         {
711                                 int fdflags; 
712                                 fdflags = fcntl(ssock, F_GETFL);
713                                 if (fdflags < 0)
714                                         lprintf(1, "unable to get server socket flags! %s \n",
715                                                 strerror(errno));
716                                 fdflags = fdflags | O_NONBLOCK;
717                                 if (fcntl(ssock, F_SETFD, fdflags) < 0)
718                                         lprintf(1, "unable to set server socket nonblocking flags! %s \n",
719                                                 strerror(errno));
720                         }
721 #endif
722
723                         if (fail_this_transaction == 0) {
724
725                                 /* Perform an HTTP transaction... */
726                                 context_loop(&ssock);
727
728                                 /* Shut down SSL/TLS if required... */
729 #ifdef HAVE_OPENSSL
730                                 if (is_https) {
731                                         endtls();
732                                 }
733 #endif
734
735                                 /* ...and close the socket. */
736                                 if (ssock > 0)
737                                         lingering_close(ssock);
738                         }
739
740                 }
741
742         } while (!time_to_die);
743
744         lprintf (1, "bye\n");
745         pthread_exit(NULL);
746 }
747
748 /*
749  * print log messages 
750  * logs to stderr if loglevel is lower than the verbosity set at startup
751  *
752  * loglevel     level of the message
753  * format       the printf like format string
754  * ...          the strings to put into format
755  */
756 int lprintf(int loglevel, const char *format, ...)
757 {
758         va_list ap;
759
760         if (loglevel <= verbosity) {
761                 va_start(ap, format);
762                 vfprintf(stderr, format, ap);
763                 va_end(ap);
764                 fflush(stderr);
765         }
766         return 1;
767 }
768
769
770 /*
771  * print the actual stack frame.
772  */
773 void wc_backtrace(void)
774 {
775 #ifdef HAVE_BACKTRACE
776         void *stack_frames[50];
777         size_t size, i;
778         char **strings;
779
780
781         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
782         strings = backtrace_symbols(stack_frames, size);
783         for (i = 0; i < size; i++) {
784                 if (strings != NULL)
785                         lprintf(1, "%s\n", strings[i]);
786                 else
787                         lprintf(1, "%p\n", stack_frames[i]);
788         }
789         free(strings);
790 #endif
791 }
792
793
794
795