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.
12 #include "webserver.h"
15 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
18 int verbosity = 9; /* Logging level */
19 int msock; /* master listening socket */
20 int is_https = 0; /* Nonzero if I am an HTTPS service */
21 extern void *context_loop(int);
22 extern void *housekeeping_loop(void);
23 extern pthread_mutex_t SessionListMutex;
24 extern pthread_key_t MyConKey;
27 char *server_cookie = NULL;
30 char *ctdlhost = DEFAULT_HOST;
31 char *ctdlport = DEFAULT_PORT;
33 char wizard_filename[PATH_MAX];
36 * This is a generic function to set up a master socket for listening on
37 * a TCP port. The server shuts down if the bind fails.
39 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
41 struct sockaddr_in sin;
44 memset(&sin, 0, sizeof(sin));
45 sin.sin_family = AF_INET;
46 if (ip_addr == NULL) {
47 sin.sin_addr.s_addr = INADDR_ANY;
49 sin.sin_addr.s_addr = inet_addr(ip_addr);
52 if (sin.sin_addr.s_addr == INADDR_NONE) {
53 sin.sin_addr.s_addr = INADDR_ANY;
56 if (port_number == 0) {
57 lprintf(1, "Cannot start: no port number specified.\n");
60 sin.sin_port = htons((u_short) port_number);
62 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
64 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
67 /* Set some socket options that make sense. */
69 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
71 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
72 lprintf(1, "Can't bind: %s\n", strerror(errno));
75 if (listen(s, queue_len) < 0) {
76 lprintf(1, "Can't listen: %s\n", strerror(errno));
84 * Read data from the client socket.
86 * 1 Requested number of bytes has been read.
87 * 0 Request timed out.
88 * -1 Connection is broken, or other error.
90 int client_read_to(int sock, char *buf, int bytes, int timeout)
100 return (client_read_ssl(buf, bytes, timeout));
105 while (len < bytes) {
111 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
112 if (FD_ISSET(sock, &rfds) == 0) {
116 rlen = read(sock, &buf[len], bytes - len);
119 lprintf(2, "client_read() failed: %s\n",
127 write(2, "\033[32m", 5);
128 write(2, buf, bytes);
129 write(2, "\033[30m", 5);
135 ssize_t client_write(const void *buf, size_t count)
138 if (WC->burst != NULL) {
140 realloc(WC->burst, (WC->burst_len + count + 2));
141 memcpy(&WC->burst[WC->burst_len], buf, count);
142 WC->burst_len += count;
147 client_write_ssl((char *) buf, count);
152 write(2, "\033[34m", 5);
153 write(2, buf, count);
154 write(2, "\033[30m", 5);
156 return (write(WC->http_sock, buf, count));
160 void begin_burst(void)
162 if (WC->burst != NULL) {
167 WC->burst = malloc(SIZ);
172 * compress_gzip() uses the same calling syntax as compress2(), but it
173 * creates a stream compatible with HTTP "Content-encoding: gzip"
176 #define DEF_MEM_LEVEL 8
177 #define OS_CODE 0x03 /* unix */
178 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
179 const Bytef * source, uLong sourceLen, int level)
181 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
183 /* write gzip header */
184 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
185 gz_magic[0], gz_magic[1], Z_DEFLATED,
186 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
192 stream.next_in = (Bytef *) source;
193 stream.avail_in = (uInt) sourceLen;
194 stream.next_out = dest + 10L; // after header
195 stream.avail_out = (uInt) * destLen;
196 if ((uLong) stream.avail_out != *destLen)
199 stream.zalloc = (alloc_func) 0;
200 stream.zfree = (free_func) 0;
201 stream.opaque = (voidpf) 0;
203 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
204 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
208 err = deflate(&stream, Z_FINISH);
209 if (err != Z_STREAM_END) {
211 return err == Z_OK ? Z_BUF_ERROR : err;
213 *destLen = stream.total_out + 10L;
215 /* write CRC and Length */
216 uLong crc = crc32(0L, source, sourceLen);
218 for (n = 0; n < 4; ++n, ++*destLen) {
219 dest[*destLen] = (int) (crc & 0xff);
222 uLong len = stream.total_in;
223 for (n = 0; n < 4; ++n, ++*destLen) {
224 dest[*destLen] = (int) (len & 0xff);
227 err = deflateEnd(&stream);
237 if (WC->burst == NULL)
240 the_len = WC->burst_len;
241 the_data = WC->burst;
247 /* Handle gzip compression */
249 char *compressed_data = NULL;
250 uLongf compressed_len;
252 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
253 compressed_data = malloc(compressed_len);
255 if (compress_gzip((Bytef *) compressed_data,
258 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
259 wprintf("Content-encoding: gzip\r\n");
261 the_data = compressed_data;
262 the_len = compressed_len;
264 free(compressed_data);
267 #endif /* HAVE_ZLIB */
269 wprintf("Content-length: %d\r\n\r\n", the_len);
270 client_write(the_data, the_len);
278 * Read data from the client socket with default timeout.
279 * (This is implemented in terms of client_read_to() and could be
280 * justifiably moved out of sysdep.c)
282 int client_read(int sock, char *buf, int bytes)
284 return (client_read_to(sock, buf, bytes, SLEEPING));
289 * client_gets() ... Get a LF-terminated line of text from the client.
290 * (This is implemented in terms of client_read() and could be
291 * justifiably moved out of sysdep.c)
293 int client_gets(int sock, char *buf)
297 /* Read one character at a time.
300 retval = client_read(sock, &buf[i], 1);
301 if (retval != 1 || buf[i] == '\n' || i == 255)
305 /* If we got a long line, discard characters until the newline.
308 while (buf[i] != '\n' && retval == 1)
309 retval = client_read(sock, &buf[i], 1);
312 * Strip any trailing non-printable characters.
315 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
316 buf[strlen(buf) - 1] = 0;
323 * Start running as a daemon. Only close stdio if do_close_stdio is set.
325 void start_daemon(int do_close_stdio)
327 if (do_close_stdio) {
332 signal(SIGHUP, SIG_IGN);
333 signal(SIGINT, SIG_IGN);
334 signal(SIGQUIT, SIG_IGN);
339 void spawn_another_worker_thread()
341 pthread_t SessThread; /* Thread descriptor */
342 pthread_attr_t attr; /* Thread attributes */
345 lprintf(3, "Creating a new thread\n");
347 /* set attributes for the new thread */
348 pthread_attr_init(&attr);
349 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
351 /* Our per-thread stacks need to be bigger than the default size, otherwise
352 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
355 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
356 lprintf(1, "pthread_attr_setstacksize: %s\n",
358 pthread_attr_destroy(&attr);
361 /* now create the thread */
362 if (pthread_create(&SessThread, &attr,
363 (void *(*)(void *)) worker_entry, NULL)
365 lprintf(1, "Can't create thread: %s\n", strerror(errno));
368 /* free up the attributes */
369 pthread_attr_destroy(&attr);
373 * Here's where it all begins.
375 int main(int argc, char **argv)
377 pthread_t SessThread; /* Thread descriptor */
378 pthread_attr_t attr; /* Thread attributes */
379 int a, i; /* General-purpose variables */
380 int port = PORT_NUM; /* Port to listen on */
381 char tracefile[PATH_MAX];
383 char *webcitdir = WEBCITDIR;
385 /* Parse command line */
387 while ((a = getopt(argc, argv, "h:i:p:t:x:cs")) != EOF)
389 while ((a = getopt(argc, argv, "h:i:p:t:x:c")) != EOF)
393 webcitdir = strdup(optarg);
396 safestrncpy(ip_addr, optarg, sizeof ip_addr);
402 safestrncpy(tracefile, optarg, sizeof tracefile);
403 freopen(tracefile, "w", stdout);
404 freopen(tracefile, "w", stderr);
405 freopen(tracefile, "r", stdin);
408 verbosity = atoi(optarg);
411 server_cookie = malloc(256);
412 if (server_cookie != NULL) {
413 safestrncpy(server_cookie,
414 "Set-cookie: wcserver=",
417 (&server_cookie[strlen(server_cookie)],
419 lprintf(2, "gethostname: %s\n",
429 fprintf(stderr, "usage: webserver "
430 "[-i ip_addr] [-p http_port] "
431 "[-t tracefile] [-c] "
435 "[remotehost [remoteport]]\n");
440 ctdlhost = argv[optind];
442 ctdlport = argv[optind];
444 /* Tell 'em who's in da house */
445 lprintf(1, SERVER "\n"
446 "Copyright (C) 1996-2005 by the Citadel development team.\n"
447 "This software is distributed under the terms of the "
448 "GNU General Public License.\n\n"
451 lprintf(9, "Changing directory to %s\n", webcitdir);
452 if (chdir(webcitdir) != 0) {
457 * Set up a place to put thread-specific data.
458 * We only need a single pointer per thread - it points to the
459 * wcsession struct to which the thread is currently bound.
461 if (pthread_key_create(&MyConKey, NULL) != 0) {
462 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
466 * Set up a place to put thread-specific SSL data.
467 * We don't stick this in the wcsession struct because SSL starts
468 * up before the session is bound, and it gets torn down between
472 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
473 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
478 * Bind the server to our favorite port.
479 * There is no need to check for errors, because ig_tcp_server()
480 * exits if it doesn't succeed.
482 lprintf(2, "Attempting to bind to port %d...\n", port);
483 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
484 lprintf(2, "Listening on socket %d\n", msock);
485 signal(SIGPIPE, SIG_IGN);
487 pthread_mutex_init(&SessionListMutex, NULL);
490 * Start up the housekeeping thread
492 pthread_attr_init(&attr);
493 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
494 pthread_create(&SessThread, &attr,
495 (void *(*)(void *)) housekeeping_loop, NULL);
499 * If this is an HTTPS server, fire up SSL
507 /* Start a few initial worker threads */
508 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
509 spawn_another_worker_thread();
512 /* now the original thread becomes another worker */
519 * Entry point for worker threads
521 void worker_entry(void)
526 int fail_this_transaction = 0;
529 /* Only one thread can accept at a time */
530 fail_this_transaction = 0;
531 ssock = accept(msock, NULL, 0);
533 lprintf(2, "accept() failed: %s\n",
536 /* Set the SO_REUSEADDR socket option */
538 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
541 /* If we are an HTTPS server, go crypto now. */
544 if (starttls(ssock) != 0) {
545 fail_this_transaction = 1;
551 if (fail_this_transaction == 0) {
552 /* Perform an HTTP transaction... */
554 /* ...and close the socket. */
555 lingering_close(ssock);
560 } while (!time_to_die);
566 int lprintf(int loglevel, const char *format, ...)
570 if (loglevel <= verbosity) {
571 va_start(ap, format);
572 vfprintf(stderr, format, ap);