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.
21 #include <sys/types.h>
23 #include <sys/socket.h>
24 #ifdef HAVE_SYS_TIME_H
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
40 #include "webserver.h"
43 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
46 int verbosity = 9; /* Logging level */
47 int msock; /* master listening socket */
48 int is_https = 0; /* Nonzero if I am an HTTPS service */
49 extern void *context_loop(int);
50 extern void *housekeeping_loop(void);
51 extern pthread_mutex_t SessionListMutex;
52 extern pthread_key_t MyConKey;
55 char *server_cookie = NULL;
58 char *ctdlhost = DEFAULT_HOST;
59 char *ctdlport = DEFAULT_PORT;
61 char wizard_filename[PATH_MAX];
64 * This is a generic function to set up a master socket for listening on
65 * a TCP port. The server shuts down if the bind fails.
67 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
69 struct sockaddr_in sin;
72 memset(&sin, 0, sizeof(sin));
73 sin.sin_family = AF_INET;
74 if (ip_addr == NULL) {
75 sin.sin_addr.s_addr = INADDR_ANY;
77 sin.sin_addr.s_addr = inet_addr(ip_addr);
80 if (sin.sin_addr.s_addr == INADDR_NONE) {
81 sin.sin_addr.s_addr = INADDR_ANY;
84 if (port_number == 0) {
85 lprintf(1, "Cannot start: no port number specified.\n");
88 sin.sin_port = htons((u_short) port_number);
90 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
92 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
95 /* Set some socket options that make sense. */
97 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
99 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
100 lprintf(1, "Can't bind: %s\n", strerror(errno));
103 if (listen(s, queue_len) < 0) {
104 lprintf(1, "Can't listen: %s\n", strerror(errno));
112 * Read data from the client socket.
114 * 1 Requested number of bytes has been read.
115 * 0 Request timed out.
116 * -1 Connection is broken, or other error.
118 int client_read_to(int sock, char *buf, int bytes, int timeout)
128 return (client_read_ssl(buf, bytes, timeout));
133 while (len < bytes) {
139 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
140 if (FD_ISSET(sock, &rfds) == 0) {
144 rlen = read(sock, &buf[len], bytes - len);
147 lprintf(2, "client_read() failed: %s\n",
155 write(2, "\033[32m", 5);
156 write(2, buf, bytes);
157 write(2, "\033[30m", 5);
163 ssize_t client_write(const void *buf, size_t count)
166 if (WC->burst != NULL) {
168 realloc(WC->burst, (WC->burst_len + count + 2));
169 memcpy(&WC->burst[WC->burst_len], buf, count);
170 WC->burst_len += count;
175 client_write_ssl((char *) buf, count);
180 write(2, "\033[34m", 5);
181 write(2, buf, count);
182 write(2, "\033[30m", 5);
184 return (write(WC->http_sock, buf, count));
188 void begin_burst(void)
190 if (WC->burst != NULL) {
195 WC->burst = malloc(SIZ);
200 * compress_gzip() uses the same calling syntax as compress2(), but it
201 * creates a stream compatible with HTTP "Content-encoding: gzip"
204 #define DEF_MEM_LEVEL 8
205 #define OS_CODE 0x03 /* unix */
206 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
207 const Bytef * source, uLong sourceLen, int level)
209 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
211 /* write gzip header */
212 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
213 gz_magic[0], gz_magic[1], Z_DEFLATED,
214 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
220 stream.next_in = (Bytef *) source;
221 stream.avail_in = (uInt) sourceLen;
222 stream.next_out = dest + 10L; // after header
223 stream.avail_out = (uInt) * destLen;
224 if ((uLong) stream.avail_out != *destLen)
227 stream.zalloc = (alloc_func) 0;
228 stream.zfree = (free_func) 0;
229 stream.opaque = (voidpf) 0;
231 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
232 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
236 err = deflate(&stream, Z_FINISH);
237 if (err != Z_STREAM_END) {
239 return err == Z_OK ? Z_BUF_ERROR : err;
241 *destLen = stream.total_out + 10L;
243 /* write CRC and Length */
244 uLong crc = crc32(0L, source, sourceLen);
246 for (n = 0; n < 4; ++n, ++*destLen) {
247 dest[*destLen] = (int) (crc & 0xff);
250 uLong len = stream.total_in;
251 for (n = 0; n < 4; ++n, ++*destLen) {
252 dest[*destLen] = (int) (len & 0xff);
255 err = deflateEnd(&stream);
265 if (WC->burst == NULL)
268 the_len = WC->burst_len;
269 the_data = WC->burst;
275 /* Handle gzip compression */
277 char *compressed_data = NULL;
278 uLongf compressed_len;
280 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
281 compressed_data = malloc(compressed_len);
283 if (compress_gzip((Bytef *) compressed_data,
286 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
287 wprintf("Content-encoding: gzip\r\n");
289 the_data = compressed_data;
290 the_len = compressed_len;
292 free(compressed_data);
295 #endif /* HAVE_ZLIB */
297 wprintf("Content-length: %d\r\n\r\n", the_len);
298 client_write(the_data, the_len);
306 * Read data from the client socket with default timeout.
307 * (This is implemented in terms of client_read_to() and could be
308 * justifiably moved out of sysdep.c)
310 int client_read(int sock, char *buf, int bytes)
312 return (client_read_to(sock, buf, bytes, SLEEPING));
317 * client_gets() ... Get a LF-terminated line of text from the client.
318 * (This is implemented in terms of client_read() and could be
319 * justifiably moved out of sysdep.c)
321 int client_gets(int sock, char *buf)
325 /* Read one character at a time.
328 retval = client_read(sock, &buf[i], 1);
329 if (retval != 1 || buf[i] == '\n' || i == 255)
333 /* If we got a long line, discard characters until the newline.
336 while (buf[i] != '\n' && retval == 1)
337 retval = client_read(sock, &buf[i], 1);
340 * Strip any trailing non-printable characters.
343 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
344 buf[strlen(buf) - 1] = 0;
351 * Start running as a daemon. Only close stdio if do_close_stdio is set.
353 void start_daemon(int do_close_stdio)
355 if (do_close_stdio) {
360 signal(SIGHUP, SIG_IGN);
361 signal(SIGINT, SIG_IGN);
362 signal(SIGQUIT, SIG_IGN);
367 void spawn_another_worker_thread()
369 pthread_t SessThread; /* Thread descriptor */
370 pthread_attr_t attr; /* Thread attributes */
373 lprintf(3, "Creating a new thread\n");
375 /* set attributes for the new thread */
376 pthread_attr_init(&attr);
377 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
379 /* Our per-thread stacks need to be bigger than the default size, otherwise
380 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
383 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
384 lprintf(1, "pthread_attr_setstacksize: %s\n",
386 pthread_attr_destroy(&attr);
389 /* now create the thread */
390 if (pthread_create(&SessThread, &attr,
391 (void *(*)(void *)) worker_entry, NULL)
393 lprintf(1, "Can't create thread: %s\n", strerror(errno));
396 /* free up the attributes */
397 pthread_attr_destroy(&attr);
401 * Here's where it all begins.
403 int main(int argc, char **argv)
405 pthread_t SessThread; /* Thread descriptor */
406 pthread_attr_t attr; /* Thread attributes */
407 int a, i; /* General-purpose variables */
408 int port = PORT_NUM; /* Port to listen on */
409 char tracefile[PATH_MAX];
412 /* Parse command line */
414 while ((a = getopt(argc, argv, "hi:p:t:x:cs")) != EOF)
416 while ((a = getopt(argc, argv, "hi:p:t:x:c")) != EOF)
420 safestrncpy(ip_addr, optarg, sizeof ip_addr);
426 safestrncpy(tracefile, optarg, sizeof tracefile);
427 freopen(tracefile, "w", stdout);
428 freopen(tracefile, "w", stderr);
429 freopen(tracefile, "r", stdin);
432 verbosity = atoi(optarg);
435 server_cookie = malloc(256);
436 if (server_cookie != NULL) {
437 safestrncpy(server_cookie,
438 "Set-cookie: wcserver=",
441 (&server_cookie[strlen(server_cookie)],
443 lprintf(2, "gethostname: %s\n",
453 fprintf(stderr, "usage: webserver "
454 "[-i ip_addr] [-p http_port] "
455 "[-t tracefile] [-c] "
459 "[remotehost [remoteport]]\n");
464 ctdlhost = argv[optind];
466 ctdlport = argv[optind];
468 /* Tell 'em who's in da house */
469 lprintf(1, SERVER "\n"
470 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
471 "This software is distributed under the terms of the GNU General Public\n"
472 "License. If you paid for this software, someone is ripping you off.\n\n");
474 if (chdir(WEBCITDIR) != 0)
478 * Set up a place to put thread-specific data.
479 * We only need a single pointer per thread - it points to the
480 * wcsession struct to which the thread is currently bound.
482 if (pthread_key_create(&MyConKey, NULL) != 0) {
483 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
487 * Set up a place to put thread-specific SSL data.
488 * We don't stick this in the wcsession struct because SSL starts
489 * up before the session is bound, and it gets torn down between
493 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
494 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
499 * Bind the server to our favorite port.
500 * There is no need to check for errors, because ig_tcp_server()
501 * exits if it doesn't succeed.
503 lprintf(2, "Attempting to bind to port %d...\n", port);
504 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
505 lprintf(2, "Listening on socket %d\n", msock);
506 signal(SIGPIPE, SIG_IGN);
508 pthread_mutex_init(&SessionListMutex, NULL);
511 * Start up the housekeeping thread
513 pthread_attr_init(&attr);
514 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
515 pthread_create(&SessThread, &attr,
516 (void *(*)(void *)) housekeeping_loop, NULL);
520 * If this is an HTTPS server, fire up SSL
528 /* Start a few initial worker threads */
529 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
530 spawn_another_worker_thread();
533 /* now the original thread becomes another worker */
540 * Entry point for worker threads
542 void worker_entry(void)
547 int fail_this_transaction = 0;
550 /* Only one thread can accept at a time */
551 fail_this_transaction = 0;
552 ssock = accept(msock, NULL, 0);
554 lprintf(2, "accept() failed: %s\n",
557 /* Set the SO_REUSEADDR socket option */
559 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
562 /* If we are an HTTPS server, go crypto now. */
565 if (starttls(ssock) != 0) {
566 fail_this_transaction = 1;
572 if (fail_this_transaction == 0) {
573 /* Perform an HTTP transaction... */
575 /* ...and close the socket. */
576 lingering_close(ssock);
581 } while (!time_to_die);
587 int lprintf(int loglevel, const char *format, ...)
591 if (loglevel <= verbosity) {
592 va_start(ap, format);
593 vfprintf(stderr, format, ap);