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.
11 * Uncomment to dump an HTTP trace to stderr
12 #define HTTP_TRACING 1
25 #include <sys/types.h>
27 #include <sys/socket.h>
28 #ifdef HAVE_SYS_TIME_H
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
44 #include "webserver.h"
47 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
50 int verbosity = 9; /* Logging level */
51 int msock; /* master listening socket */
52 int is_https = 0; /* Nonzero if I am an HTTPS service */
53 extern void *context_loop(int);
54 extern void *housekeeping_loop(void);
55 extern pthread_mutex_t SessionListMutex;
56 extern pthread_key_t MyConKey;
59 char *server_cookie = NULL;
62 char *ctdlhost = DEFAULT_HOST;
63 char *ctdlport = DEFAULT_PORT;
66 * This is a generic function to set up a master socket for listening on
67 * a TCP port. The server shuts down if the bind fails.
69 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
71 struct sockaddr_in sin;
74 memset(&sin, 0, sizeof(sin));
75 sin.sin_family = AF_INET;
76 if (ip_addr == NULL) {
77 sin.sin_addr.s_addr = INADDR_ANY;
80 sin.sin_addr.s_addr = inet_addr(ip_addr);
83 if (sin.sin_addr.s_addr == INADDR_NONE) {
84 sin.sin_addr.s_addr = INADDR_ANY;
87 if (port_number == 0) {
88 lprintf(1, "Cannot start: no port number specified.\n");
91 sin.sin_port = htons((u_short) port_number);
93 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
95 lprintf(1, "Can't create a socket: %s\n",
99 /* Set some socket options that make sense. */
101 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
103 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
104 lprintf(1, "Can't bind: %s\n", strerror(errno));
107 if (listen(s, queue_len) < 0) {
108 lprintf(1, "Can't listen: %s\n", strerror(errno));
116 * Read data from the client socket.
118 * 1 Requested number of bytes has been read.
119 * 0 Request timed out.
120 * -1 Connection is broken, or other error.
122 int client_read_to(int sock, char *buf, int bytes, int timeout)
132 return(client_read_ssl(buf, bytes, timeout));
137 while (len < bytes) {
143 retval = select((sock) + 1,
144 &rfds, NULL, NULL, &tv);
145 if (FD_ISSET(sock, &rfds) == 0) {
149 rlen = read(sock, &buf[len], bytes - len);
152 lprintf(2, "client_read() failed: %s\n",
160 write(2, "\033[32m", 5);
161 write(2, buf, bytes);
162 write(2, "\033[30m", 5);
168 ssize_t client_write(const void *buf, size_t count) {
170 if (WC->burst != NULL) {
171 WC->burst = realloc(WC->burst, (WC->burst_len + count + 2));
172 memcpy(&WC->burst[WC->burst_len], buf, count);
173 WC->burst_len += count;
179 client_write_ssl((char *)buf, count);
184 write(2, "\033[34m", 5);
185 write(2, buf, count);
186 write(2, "\033[30m", 5);
188 return(write(WC->http_sock, buf, count));
192 void begin_burst(void) {
193 if (WC->burst != NULL) {
198 WC->burst = malloc(SIZ);
201 void end_burst(void) {
205 if (WC->burst == NULL) return;
207 the_len = WC->burst_len;
208 the_data = WC->burst;
213 wprintf("Content-length: %d\r\n\r\n", the_len);
214 client_write(the_data, the_len);
221 * Read data from the client socket with default timeout.
222 * (This is implemented in terms of client_read_to() and could be
223 * justifiably moved out of sysdep.c)
225 int client_read(int sock, char *buf, int bytes)
227 return (client_read_to(sock, buf, bytes, SLEEPING));
232 * client_gets() ... Get a LF-terminated line of text from the client.
233 * (This is implemented in terms of client_read() and could be
234 * justifiably moved out of sysdep.c)
236 int client_gets(int sock, char *buf)
240 /* Read one character at a time.
243 retval = client_read(sock, &buf[i], 1);
244 if (retval != 1 || buf[i] == '\n' || i == 255)
248 /* If we got a long line, discard characters until the newline.
251 while (buf[i] != '\n' && retval == 1)
252 retval = client_read(sock, &buf[i], 1);
255 * Strip any trailing non-printable characters.
258 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
259 buf[strlen(buf) - 1] = 0;
266 * Start running as a daemon. Only close stdio if do_close_stdio is set.
268 void start_daemon(int do_close_stdio)
270 if (do_close_stdio) {
275 signal(SIGHUP, SIG_IGN);
276 signal(SIGINT, SIG_IGN);
277 signal(SIGQUIT, SIG_IGN);
282 void spawn_another_worker_thread() {
283 pthread_t SessThread; /* Thread descriptor */
284 pthread_attr_t attr; /* Thread attributes */
287 lprintf(3, "Creating a new thread\n");
289 /* set attributes for the new thread */
290 pthread_attr_init(&attr);
291 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
293 /* Our per-thread stacks need to be bigger than the default size, otherwise
294 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
297 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
298 lprintf(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
299 pthread_attr_destroy(&attr);
302 /* now create the thread */
303 if (pthread_create(&SessThread, &attr,
304 (void *(*)(void *)) worker_entry, NULL)
306 lprintf(1, "Can't create thread: %s\n",
310 /* free up the attributes */
311 pthread_attr_destroy(&attr);
315 * Here's where it all begins.
317 int main(int argc, char **argv)
319 pthread_t SessThread; /* Thread descriptor */
320 pthread_attr_t attr; /* Thread attributes */
321 int a, i; /* General-purpose variables */
322 int port = PORT_NUM; /* Port to listen on */
323 char tracefile[PATH_MAX];
326 /* Parse command line */
328 while ((a = getopt(argc, argv, "hi:p:t:cs")) != EOF)
330 while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
334 strcpy(ip_addr, optarg);
340 strcpy(tracefile, optarg);
341 freopen(tracefile, "w", stdout);
342 freopen(tracefile, "w", stderr);
343 freopen(tracefile, "r", stdin);
346 verbosity = atoi(optarg);
349 server_cookie = malloc(SIZ);
350 if (server_cookie != NULL) {
351 strcpy(server_cookie, "Set-cookie: wcserver=");
353 &server_cookie[strlen(server_cookie)],
355 lprintf(2, "gethostname: %s\n",
365 fprintf(stderr, "usage: webserver "
366 "[-i ip_addr] [-p http_port] "
367 "[-t tracefile] [-c] "
371 "[remotehost [remoteport]]\n");
376 ctdlhost = argv[optind];
378 ctdlport = argv[optind];
380 /* Tell 'em who's in da house */
381 lprintf(1, SERVER "\n"
382 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
383 "This software is distributed under the terms of the GNU General Public\n"
384 "License. If you paid for this software, someone is ripping you off.\n\n");
386 if (chdir(WEBCITDIR) != 0)
390 * Set up a place to put thread-specific data.
391 * We only need a single pointer per thread - it points to the
392 * wcsession struct to which the thread is currently bound.
394 if (pthread_key_create(&MyConKey, NULL) != 0) {
395 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
399 * Set up a place to put thread-specific SSL data.
400 * We don't stick this in the wcsession struct because SSL starts
401 * up before the session is bound, and it gets torn down between
405 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
406 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
411 * Bind the server to our favorite port.
412 * There is no need to check for errors, because ig_tcp_server()
413 * exits if it doesn't succeed.
415 lprintf(2, "Attempting to bind to port %d...\n", port);
416 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
417 lprintf(2, "Listening on socket %d\n", msock);
418 signal(SIGPIPE, SIG_IGN);
420 pthread_mutex_init(&SessionListMutex, NULL);
423 * Start up the housekeeping thread
425 pthread_attr_init(&attr);
426 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
427 pthread_create(&SessThread, &attr,
428 (void *(*)(void *)) housekeeping_loop, NULL);
432 * If this is an HTTPS server, fire up SSL
440 /* Start a few initial worker threads */
441 for (i=0; i<(MIN_WORKER_THREADS); ++i) {
442 spawn_another_worker_thread();
445 /* now the original thread becomes another worker */
452 * Entry point for worker threads
454 void worker_entry(void) {
458 int fail_this_transaction = 0;
461 /* Only one thread can accept at a time */
462 fail_this_transaction = 0;
463 ssock = accept(msock, NULL, 0);
465 lprintf(2, "accept() failed: %s\n", strerror(errno));
467 /* Set the SO_REUSEADDR socket option */
469 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
472 /* If we are an HTTPS server, go crypto now. */
475 if (starttls(ssock) != 0) {
476 fail_this_transaction = 1;
482 if (fail_this_transaction == 0) {
483 /* Perform an HTTP transaction... */
485 /* ...and close the socket. */
486 lingering_close(ssock);
491 } while (!time_to_die);
497 int lprintf(int loglevel, const char *format, ...)
501 if (loglevel <= verbosity) {
502 va_start(ap, format);
503 vfprintf(stderr, format, ap);