webcit_before_automake is now the trunk
[citadel.git] / webcit / webserver.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup Webserver This contains a simple multithreaded TCP server manager.  It sits around
6  * waiting on the specified port for incoming HTTP connections.  When a
7  * connection is established, it calls context_loop() from context_loop.c.
8  * \ingroup WebcitHttpServer
9  */
10
11 /*@{*/
12 #include "webcit.h"
13 #include "webserver.h"
14
15 #if HAVE_BACKTRACE
16 #include <execinfo.h>
17 #endif
18
19 #ifndef HAVE_SNPRINTF
20 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
21 #endif
22
23 int verbosity = 9;              /**< Logging level */
24 int msock;                          /**< master listening socket */
25 int is_https = 0;               /**< Nonzero if I am an HTTPS service */
26 int follow_xff = 0;             /**< Follow X-Forwarded-For: header */
27 int home_specified = 0; /**< did the user specify a homedir? */
28 extern void *context_loop(int);
29 extern void *housekeeping_loop(void);
30 extern pthread_mutex_t SessionListMutex;
31 extern pthread_key_t MyConKey;
32
33 char socket_dir[PATH_MAX];      /**< where to talk to our citadel server */
34 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /**< nailed to what configure gives us. */
35 static char static_dir[PATH_MAX]; /**< calculated on startup */
36 char  *static_dirs[]={ /**< needs same sort order as the web mapping */
37         (char*)static_dir,                  /** our templates on disk */
38         (char*)editor_absolut_dir           /** the editor on disk */
39 };
40 int ndirs=2; //sizeof(static_content_dirs);//sizeof(char *);
41
42 /**
43  * Subdirectories from which the client may request static content
44  */
45 char *static_content_dirs[] = {
46         "static",                     /** static templates */
47         "tiny_mce"                    /** the JS editor */
48 };
49
50
51
52 char *server_cookie = NULL; /**< our Cookie connection to the client */
53
54 int http_port = PORT_NUM;       /**< Port to listen on */
55
56 char *ctdlhost = DEFAULT_HOST; /**< our name */
57 char *ctdlport = DEFAULT_PORT; /**< our Port */
58 int setup_wizard = 0;          /**< should we run the setup wizard? \todo */
59 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
60
61 /** 
62  * \brief This is a generic function to set up a master socket for listening on
63  * a TCP port.  The server shuts down if the bind fails.
64  * \param ip_addr ip to bind to
65  * \param port_number the port to bind to 
66  * \param queue_len the size of the input queue ????
67  */
68 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
69 {
70         struct sockaddr_in sin;
71         int s, i;
72
73         memset(&sin, 0, sizeof(sin));
74         sin.sin_family = AF_INET;
75         if (ip_addr == NULL) {
76                 sin.sin_addr.s_addr = INADDR_ANY;
77         } else {
78                 sin.sin_addr.s_addr = inet_addr(ip_addr);
79         }
80
81         if (sin.sin_addr.s_addr == INADDR_NONE) {
82                 sin.sin_addr.s_addr = INADDR_ANY;
83         }
84
85         if (port_number == 0) {
86                 lprintf(1, "Cannot start: no port number specified.\n");
87                 exit(1);
88         }
89         sin.sin_port = htons((u_short) port_number);
90
91         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
92         if (s < 0) {
93                 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
94                 exit(errno);
95         }
96         /** Set some socket options that make sense. */
97         i = 1;
98         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
99
100         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
101                 lprintf(1, "Can't bind: %s\n", strerror(errno));
102                 exit(errno);
103         }
104         if (listen(s, queue_len) < 0) {
105                 lprintf(1, "Can't listen: %s\n", strerror(errno));
106                 exit(errno);
107         }
108         return (s);
109 }
110
111
112
113 /**
114  * \brief Create a Unix domain socket and listen on it
115  * \param sockpath file name of the unix domain socket
116  * \param queue_len queue size of the kernel fifo????
117  */
118 int ig_uds_server(char *sockpath, int queue_len)
119 {
120         struct sockaddr_un addr;
121         int s;
122         int i;
123         int actual_queue_len;
124
125         actual_queue_len = queue_len;
126         if (actual_queue_len < 5) actual_queue_len = 5;
127
128         i = unlink(sockpath);
129         if (i != 0) if (errno != ENOENT) {
130                 lprintf(1, "citserver: can't unlink %s: %s\n",
131                         sockpath, strerror(errno));
132                 exit(errno);
133         }
134
135         memset(&addr, 0, sizeof(addr));
136         addr.sun_family = AF_UNIX;
137         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
138
139         s = socket(AF_UNIX, SOCK_STREAM, 0);
140         if (s < 0) {
141                 lprintf(1, "citserver: Can't create a socket: %s\n",
142                         strerror(errno));
143                 exit(errno);
144         }
145
146         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
147                 lprintf(1, "citserver: Can't bind: %s\n",
148                         strerror(errno));
149                 exit(errno);
150         }
151
152         if (listen(s, actual_queue_len) < 0) {
153                 lprintf(1, "citserver: Can't listen: %s\n",
154                         strerror(errno));
155                 exit(errno);
156         }
157
158         chmod(sockpath, 0777);
159         return(s);
160 }
161
162
163
164
165 /**
166  * \brief Read data from the client socket.
167  * \param sock socket fd to read from ???
168  * \param buf buffer to read into 
169  * \param bytes how large is the read buffer?
170  * \param timeout how long should we wait for input?
171  * \return values are\
172  *      1       Requested number of bytes has been read.\
173  *      0       Request timed out.\
174  *         -1           Connection is broken, or other error.
175  */
176 int client_read_to(int sock, char *buf, int bytes, int timeout)
177 {
178         int len, rlen;
179         fd_set rfds;
180         struct timeval tv;
181         int retval;
182
183
184 #ifdef HAVE_OPENSSL
185         if (is_https) {
186                 return (client_read_ssl(buf, bytes, timeout));
187         }
188 #endif
189
190         len = 0;
191         while (len < bytes) {
192                 FD_ZERO(&rfds);
193                 FD_SET(sock, &rfds);
194                 tv.tv_sec = timeout;
195                 tv.tv_usec = 0;
196
197                 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
198                 if (FD_ISSET(sock, &rfds) == 0) {
199                         return (0);
200                 }
201
202                 rlen = read(sock, &buf[len], bytes - len);
203
204                 if (rlen < 1) {
205                         lprintf(2, "client_read() failed: %s\n",
206                                 strerror(errno));
207                         return (-1);
208                 }
209                 len = len + rlen;
210         }
211
212 #ifdef HTTP_TRACING
213         write(2, "\033[32m", 5);
214         write(2, buf, bytes);
215         write(2, "\033[30m", 5);
216 #endif
217         return (1);
218 }
219
220 /**
221  * \brief write data to the client
222  * \param buf data to write to the client
223  * \param count size of buffer
224  */
225 ssize_t client_write(const void *buf, size_t count)
226 {
227         char *newptr;
228         size_t newalloc;
229
230         if (WC->burst != NULL) {
231                 if ((WC->burst_len + count) >= WC->burst_alloc) {
232                         newalloc = (WC->burst_alloc * 2);
233                         if ((WC->burst_len + count) >= newalloc) {
234                                 newalloc += count;
235                         }
236                         newptr = realloc(WC->burst, newalloc);
237                         if (newptr != NULL) {
238                                 WC->burst = newptr;
239                                 WC->burst_alloc = newalloc;
240                         }
241                 }
242                 if ((WC->burst_len + count) < WC->burst_alloc) {
243                         memcpy(&WC->burst[WC->burst_len], buf, count);
244                         WC->burst_len += count;
245                         return (count);
246                 }
247                 else {
248                         return(-1);
249                 }
250         }
251 #ifdef HAVE_OPENSSL
252         if (is_https) {
253                 client_write_ssl((char *) buf, count);
254                 return (count);
255         }
256 #endif
257 #ifdef HTTP_TRACING
258         write(2, "\033[34m", 5);
259         write(2, buf, count);
260         write(2, "\033[30m", 5);
261 #endif
262         return (write(WC->http_sock, buf, count));
263 }
264
265 /**
266  * \brief what burst???
267  */
268 void begin_burst(void)
269 {
270         if (WC->burst != NULL) {
271                 free(WC->burst);
272                 WC->burst = NULL;
273         }
274         WC->burst_len = 0;
275         WC->burst_alloc = 32768;
276         WC->burst = malloc(WC->burst_alloc);
277 }
278
279
280 /**
281  * \brief uses the same calling syntax as compress2(), but it
282  * creates a stream compatible with HTTP "Content-encoding: gzip"
283  */
284 #ifdef HAVE_ZLIB
285 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
286 #define OS_CODE 0x03    /**< unix */
287 int ZEXPORT compress_gzip(Bytef * dest,         /**< compressed buffer*/
288                                                   uLongf * destLen,     /**< length of the compresed data */
289                                                   const Bytef * source, /**< source to encode */
290                                                   uLong sourceLen,      /**< length of the source to encode */
291                                                   int level)            /**< what level??? */
292 {
293         const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
294
295         /** write gzip header */
296         sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
297                 gz_magic[0], gz_magic[1], Z_DEFLATED,
298                 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
299                 OS_CODE);
300
301         /* normal deflate */
302         z_stream stream;
303         int err;
304         stream.next_in = (Bytef *) source;
305         stream.avail_in = (uInt) sourceLen;
306         stream.next_out = dest + 10L;   // after header
307         stream.avail_out = (uInt) * destLen;
308         if ((uLong) stream.avail_out != *destLen)
309                 return Z_BUF_ERROR;
310
311         stream.zalloc = (alloc_func) 0;
312         stream.zfree = (free_func) 0;
313         stream.opaque = (voidpf) 0;
314
315         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
316                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
317         if (err != Z_OK)
318                 return err;
319
320         err = deflate(&stream, Z_FINISH);
321         if (err != Z_STREAM_END) {
322                 deflateEnd(&stream);
323                 return err == Z_OK ? Z_BUF_ERROR : err;
324         }
325         *destLen = stream.total_out + 10L;
326
327         /* write CRC and Length */
328         uLong crc = crc32(0L, source, sourceLen);
329         int n;
330         for (n = 0; n < 4; ++n, ++*destLen) {
331                 dest[*destLen] = (int) (crc & 0xff);
332                 crc >>= 8;
333         }
334         uLong len = stream.total_in;
335         for (n = 0; n < 4; ++n, ++*destLen) {
336                 dest[*destLen] = (int) (len & 0xff);
337                 len >>= 8;
338         }
339         err = deflateEnd(&stream);
340         return err;
341 }
342 #endif
343
344 /**
345  * \brief what burst???
346  */
347 void end_burst(void)
348 {
349         size_t the_len;
350         char *the_data;
351
352         if (WC->burst == NULL)
353                 return;
354
355         the_len = WC->burst_len;
356         the_data = WC->burst;
357
358         WC->burst_len = 0;
359         WC->burst_alloc = 0;
360         WC->burst = NULL;
361
362 #ifdef HAVE_ZLIB
363         /* Handle gzip compression */
364         if (WC->gzip_ok) {
365                 char *compressed_data = NULL;
366                 uLongf compressed_len;
367
368                 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
369                 compressed_data = malloc(compressed_len);
370
371                 if (compress_gzip((Bytef *) compressed_data,
372                                   &compressed_len,
373                                   (Bytef *) the_data,
374                                   (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
375                         wprintf("Content-encoding: gzip\r\n");
376                         free(the_data);
377                         the_data = compressed_data;
378                         the_len = compressed_len;
379                 } else {
380                         free(compressed_data);
381                 }
382         }
383 #endif                          /* HAVE_ZLIB */
384
385         wprintf("Content-length: %d\r\n\r\n", the_len);
386         client_write(the_data, the_len);
387         free(the_data);
388         return;
389 }
390
391
392
393 /**
394  * \brief Read data from the client socket with default timeout.
395  * (This is implemented in terms of client_read_to() and could be
396  * justifiably moved out of sysdep.c)
397  * \param sock the socket fd to read from???
398  * \param buf the buffer to write to
399  * \param bytes how large is the buffer
400  */
401 int client_read(int sock, char *buf, int bytes)
402 {
403         return (client_read_to(sock, buf, bytes, SLEEPING));
404 }
405
406
407 /**
408  * \brief Get a LF-terminated line of text from the client.
409  * (This is implemented in terms of client_read() and could be
410  * justifiably moved out of sysdep.c)
411  * \param sock socket fd to get client line from???
412  * \param buf buffer to write read data to
413  * \param bufsiz how many bytes to read
414  * \return  numer of bytes read???
415  */
416 int client_getln(int sock, char *buf, int bufsiz)
417 {
418         int i, retval;
419
420         /** Read one character at a time.*/
421         for (i = 0;; i++) {
422                 retval = client_read(sock, &buf[i], 1);
423                 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
424                         break;
425                 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
426                         /** Non printable character recieved from client */
427                         return(-1);
428                 }
429         }
430
431         /** If we got a long line, discard characters until the newline. */
432         if (i == (bufsiz-1))
433                 while (buf[i] != '\n' && retval == 1)
434                         retval = client_read(sock, &buf[i], 1);
435
436         /**
437          * Strip any trailing non-printable characters.
438          */
439         buf[i] = 0;
440         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
441                 buf[strlen(buf) - 1] = 0;
442         }
443         return (retval);
444 }
445
446
447 /**
448  * \brief       Start running as a daemon.  
449  *
450  * param        do_close_stdio          Only close stdio if set.
451  */
452 void start_daemon(int do_close_stdio)
453 {
454         if (do_close_stdio) {
455                 /* close(0); */
456                 close(1);
457                 close(2);
458         }
459         signal(SIGHUP, SIG_IGN);
460         signal(SIGINT, SIG_IGN);
461         signal(SIGQUIT, SIG_IGN);
462         if (fork() != 0) {
463                 exit(0);
464         }
465 }
466
467 /**
468  * \brief       Spawn an additional worker thread into the pool.
469  */
470 void spawn_another_worker_thread()
471 {
472         pthread_t SessThread;   /**< Thread descriptor */
473         pthread_attr_t attr;    /**< Thread attributes */
474         int ret;
475
476         lprintf(3, "Creating a new thread\n");
477
478         /** set attributes for the new thread */
479         pthread_attr_init(&attr);
480         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
481
482         /**
483          * Our per-thread stacks need to be bigger than the default size, otherwise
484          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
485          * 64-bit Linux.
486          */
487         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
488                 lprintf(1, "pthread_attr_setstacksize: %s\n",
489                         strerror(ret));
490                 pthread_attr_destroy(&attr);
491         }
492
493         /** now create the thread */
494         if (pthread_create(&SessThread, &attr,
495                            (void *(*)(void *)) worker_entry, NULL)
496             != 0) {
497                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
498         }
499
500         /** free up the attributes */
501         pthread_attr_destroy(&attr);
502 }
503
504 /**
505  * \brief Here's where it all begins.
506  * \param argc number of commandline args
507  * \param argv the commandline arguments
508  */
509 int main(int argc, char **argv)
510 {
511         pthread_t SessThread;   /**< Thread descriptor */
512         pthread_attr_t attr;    /**< Thread attributes */
513         int a, i;                       /**< General-purpose variables */
514         char tracefile[PATH_MAX];
515         char ip_addr[256];
516         char dirbuffer[PATH_MAX]="";
517         int relh=0;
518         int home=0;
519         int home_specified=0;
520         char relhome[PATH_MAX]="";
521         char webcitdir[PATH_MAX] = DATADIR;
522         char *hdir;
523         const char *basedir;
524 #ifdef ENABLE_NLS
525         char *locale = NULL;
526         char *mo = NULL;
527 #endif /* ENABLE_NLS */
528         char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
529
530         strcpy(uds_listen_path, "");
531
532         /** Parse command line */
533 #ifdef HAVE_OPENSSL
534         while ((a = getopt(argc, argv, "h:i:p:t:x:cfs")) != EOF)
535 #else
536         while ((a = getopt(argc, argv, "h:i:p:t:x:cf")) != EOF)
537 #endif
538                 switch (a) {
539                 case 'h':
540                         hdir = strdup(optarg);
541                         relh=hdir[0]!='/';
542                         if (!relh) safestrncpy(webcitdir, hdir,
543                                                                    sizeof webcitdir);
544                         else
545                                 safestrncpy(relhome, relhome,
546                                                         sizeof relhome);
547                         /* free(hdir); TODO: SHOULD WE DO THIS? */
548                         home_specified = 1;
549                         home=1;
550                         break;
551                 case 'i':
552                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
553                         break;
554                 case 'p':
555                         http_port = atoi(optarg);
556                         if (http_port == 0) {
557                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
558                         }
559                         break;
560                 case 't':
561                         safestrncpy(tracefile, optarg, sizeof tracefile);
562                         freopen(tracefile, "w", stdout);
563                         freopen(tracefile, "w", stderr);
564                         freopen(tracefile, "r", stdin);
565                         break;
566                 case 'x':
567                         verbosity = atoi(optarg);
568                         break;
569                 case 'f':
570                         follow_xff = 1;
571                         break;
572                 case 'c':
573                         server_cookie = malloc(256);
574                         if (server_cookie != NULL) {
575                                 safestrncpy(server_cookie,
576                                        "Set-cookie: wcserver=",
577                                         256);
578                                 if (gethostname
579                                     (&server_cookie[strlen(server_cookie)],
580                                      200) != 0) {
581                                         lprintf(2, "gethostname: %s\n",
582                                                 strerror(errno));
583                                         free(server_cookie);
584                                 }
585                         }
586                         break;
587                 case 's':
588                         is_https = 1;
589                         break;
590                 default:
591                         fprintf(stderr, "usage: webserver "
592                                 "[-i ip_addr] [-p http_port] "
593                                 "[-t tracefile] [-c] [-f] "
594 #ifdef HAVE_OPENSSL
595                                 "[-s] "
596 #endif
597                                 "[remotehost [remoteport]]\n");
598                         return 1;
599                 }
600
601         if (optind < argc) {
602                 ctdlhost = argv[optind];
603                 if (++optind < argc)
604                         ctdlport = argv[optind];
605         }
606         /** Tell 'em who's in da house */
607         lprintf(1, SERVER "\n");
608         lprintf(1, "Copyright (C) 1996-2006 by the Citadel development team.\n"
609                 "This software is distributed under the terms of the "
610                 "GNU General Public License.\n\n"
611         );
612
613
614         /** initialize the International Bright Young Thing */
615 #ifdef ENABLE_NLS
616         initialize_locales();
617         locale = setlocale(LC_ALL, "");
618         mo = malloc(strlen(webcitdir) + 20);
619         lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR));
620         free(mo);
621         lprintf(9, "Text domain: %s\n", textdomain("webcit"));
622         lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
623 #endif
624
625
626         /* calculate all our path on a central place */
627     /* where to keep our config */
628         
629 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
630         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
631                          (home&!relh)?webcitdir:basedir, \
632              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
633              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
634                          relhome, \
635              (relhome[0]!='\0')?"/":"",\
636                          dirbuffer,\
637                          (dirbuffer[0]!='\0')?"/":"");
638         basedir=RUNDIR;
639         COMPUTE_DIRECTORY(socket_dir);
640         basedir=DATADIR;
641         COMPUTE_DIRECTORY(static_dir);
642         /** we should go somewhere we can leave our coredump, if enabled... */
643         lprintf(9, "Changing directory to %s\n", socket_dir);
644         if (chdir(webcitdir) != 0) {
645                 perror("chdir");
646         }
647         initialize_viewdefs();
648         initialize_axdefs();
649
650         /**
651          * Set up a place to put thread-specific data.
652          * We only need a single pointer per thread - it points to the
653          * wcsession struct to which the thread is currently bound.
654          */
655         if (pthread_key_create(&MyConKey, NULL) != 0) {
656                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
657         }
658
659         /**
660          * Set up a place to put thread-specific SSL data.
661          * We don't stick this in the wcsession struct because SSL starts
662          * up before the session is bound, and it gets torn down between
663          * transactions.
664          */
665 #ifdef HAVE_OPENSSL
666         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
667                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
668         }
669 #endif
670
671         /**
672          * Bind the server to our favorite port.
673          * There is no need to check for errors, because ig_tcp_server()
674          * exits if it doesn't succeed.
675          */
676
677         if (strlen(uds_listen_path) > 0) {
678                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
679                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
680         }
681         else {
682                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
683                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
684         }
685
686         lprintf(2, "Listening on socket %d\n", msock);
687         signal(SIGPIPE, SIG_IGN);
688
689         pthread_mutex_init(&SessionListMutex, NULL);
690
691         /**
692          * Start up the housekeeping thread
693          */
694         pthread_attr_init(&attr);
695         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
696         pthread_create(&SessThread, &attr,
697                        (void *(*)(void *)) housekeeping_loop, NULL);
698
699
700         /**
701          * If this is an HTTPS server, fire up SSL
702          */
703 #ifdef HAVE_OPENSSL
704         if (is_https) {
705                 init_ssl();
706         }
707 #endif
708
709         /** Start a few initial worker threads */
710         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
711                 spawn_another_worker_thread();
712         }
713
714         /* now the original thread becomes another worker */
715         worker_entry();
716         return 0;
717 }
718
719
720 /**
721  * Entry point for worker threads
722  */
723 void worker_entry(void)
724 {
725         int ssock;
726         int i = 0;
727         int time_to_die = 0;
728         int fail_this_transaction = 0;
729
730         do {
731                 /** Only one thread can accept at a time */
732                 fail_this_transaction = 0;
733                 ssock = accept(msock, NULL, 0);
734                 if (ssock < 0) {
735                         lprintf(2, "accept() failed: %s\n",
736                                 strerror(errno));
737                 } else {
738                         /** Set the SO_REUSEADDR socket option */
739                         i = 1;
740                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
741                                    &i, sizeof(i));
742
743                         /** If we are an HTTPS server, go crypto now. */
744 #ifdef HAVE_OPENSSL
745                         if (is_https) {
746                                 if (starttls(ssock) != 0) {
747                                         fail_this_transaction = 1;
748                                         close(ssock);
749                                 }
750                         }
751 #endif
752
753                         if (fail_this_transaction == 0) {
754                                 /** Perform an HTTP transaction... */
755                                 context_loop(ssock);
756                                 /** ...and close the socket. */
757                                 lingering_close(ssock);
758                         }
759
760                 }
761
762         } while (!time_to_die);
763
764         pthread_exit(NULL);
765 }
766
767 /**
768  * \brief logprintf. log messages 
769  * logs to stderr if loglevel is lower than the verbosity set at startup
770  * \param loglevel level of the message
771  * \param format the printf like format string
772  * \param ... the strings to put into format
773  */
774 int lprintf(int loglevel, const char *format, ...)
775 {
776         va_list ap;
777
778         if (loglevel <= verbosity) {
779                 va_start(ap, format);
780                 vfprintf(stderr, format, ap);
781                 va_end(ap);
782                 fflush(stderr);
783         }
784         return 1;
785 }
786
787
788 /**
789  * \brief print the actual stack frame.
790  */
791 void wc_backtrace(void)
792 {
793 #ifdef HAVE_BACKTRACE
794         void *stack_frames[50];
795         size_t size, i;
796         char **strings;
797
798
799         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
800         strings = backtrace_symbols(stack_frames, size);
801         for (i = 0; i < size; i++) {
802                 if (strings != NULL)
803                         lprintf(1, "%s\n", strings[i]);
804                 else
805                         lprintf(1, "%p\n", stack_frames[i]);
806         }
807         free(strings);
808 #endif
809 }
810
811 /*@}*/