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 the_len = WC->burst_len;
206 the_data = WC->burst;
211 wprintf("Content-length: %d\r\n\r\n", the_len);
212 client_write(the_data, the_len);
219 * Read data from the client socket with default timeout.
220 * (This is implemented in terms of client_read_to() and could be
221 * justifiably moved out of sysdep.c)
223 int client_read(int sock, char *buf, int bytes)
225 return (client_read_to(sock, buf, bytes, SLEEPING));
230 * client_gets() ... Get a LF-terminated line of text from the client.
231 * (This is implemented in terms of client_read() and could be
232 * justifiably moved out of sysdep.c)
234 int client_gets(int sock, char *buf)
238 /* Read one character at a time.
241 retval = client_read(sock, &buf[i], 1);
242 if (retval != 1 || buf[i] == '\n' || i == 255)
246 /* If we got a long line, discard characters until the newline.
249 while (buf[i] != '\n' && retval == 1)
250 retval = client_read(sock, &buf[i], 1);
253 * Strip any trailing non-printable characters.
256 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
257 buf[strlen(buf) - 1] = 0;
264 * Start running as a daemon. Only close stdio if do_close_stdio is set.
266 void start_daemon(int do_close_stdio)
268 if (do_close_stdio) {
273 signal(SIGHUP, SIG_IGN);
274 signal(SIGINT, SIG_IGN);
275 signal(SIGQUIT, SIG_IGN);
280 void spawn_another_worker_thread() {
281 pthread_t SessThread; /* Thread descriptor */
282 pthread_attr_t attr; /* Thread attributes */
285 lprintf(3, "Creating a new thread\n");
287 /* set attributes for the new thread */
288 pthread_attr_init(&attr);
289 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
291 /* Our per-thread stacks need to be bigger than the default size, otherwise
292 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
295 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
296 lprintf(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
297 pthread_attr_destroy(&attr);
300 /* now create the thread */
301 if (pthread_create(&SessThread, &attr,
302 (void *(*)(void *)) worker_entry, NULL)
304 lprintf(1, "Can't create thread: %s\n",
308 /* free up the attributes */
309 pthread_attr_destroy(&attr);
313 * Here's where it all begins.
315 int main(int argc, char **argv)
317 pthread_t SessThread; /* Thread descriptor */
318 pthread_attr_t attr; /* Thread attributes */
319 int a, i; /* General-purpose variables */
320 int port = PORT_NUM; /* Port to listen on */
321 char tracefile[PATH_MAX];
324 /* Parse command line */
326 while ((a = getopt(argc, argv, "hi:p:t:cs")) != EOF)
328 while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
332 strcpy(ip_addr, optarg);
338 strcpy(tracefile, optarg);
339 freopen(tracefile, "w", stdout);
340 freopen(tracefile, "w", stderr);
341 freopen(tracefile, "r", stdin);
344 verbosity = atoi(optarg);
347 server_cookie = malloc(SIZ);
348 if (server_cookie != NULL) {
349 strcpy(server_cookie, "Set-cookie: wcserver=");
351 &server_cookie[strlen(server_cookie)],
353 lprintf(2, "gethostname: %s\n",
363 fprintf(stderr, "usage: webserver "
364 "[-i ip_addr] [-p http_port] "
365 "[-t tracefile] [-c] "
369 "[remotehost [remoteport]]\n");
374 ctdlhost = argv[optind];
376 ctdlport = argv[optind];
378 /* Tell 'em who's in da house */
379 lprintf(1, SERVER "\n"
380 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
381 "This software is distributed under the terms of the GNU General Public\n"
382 "License. If you paid for this software, someone is ripping you off.\n\n");
384 if (chdir(WEBCITDIR) != 0)
388 * Set up a place to put thread-specific data.
389 * We only need a single pointer per thread - it points to the
390 * wcsession struct to which the thread is currently bound.
392 if (pthread_key_create(&MyConKey, NULL) != 0) {
393 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
397 * Set up a place to put thread-specific SSL data.
398 * We don't stick this in the wcsession struct because SSL starts
399 * up before the session is bound, and it gets torn down between
403 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
404 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
409 * Bind the server to our favorite port.
410 * There is no need to check for errors, because ig_tcp_server()
411 * exits if it doesn't succeed.
413 lprintf(2, "Attempting to bind to port %d...\n", port);
414 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
415 lprintf(2, "Listening on socket %d\n", msock);
416 signal(SIGPIPE, SIG_IGN);
418 pthread_mutex_init(&SessionListMutex, NULL);
421 * Start up the housekeeping thread
423 pthread_attr_init(&attr);
424 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
425 pthread_create(&SessThread, &attr,
426 (void *(*)(void *)) housekeeping_loop, NULL);
430 * If this is an HTTPS server, fire up SSL
438 /* Start a few initial worker threads */
439 for (i=0; i<(MIN_WORKER_THREADS); ++i) {
440 spawn_another_worker_thread();
443 /* now the original thread becomes another worker */
450 * Entry point for worker threads
452 void worker_entry(void) {
456 int fail_this_transaction = 0;
459 /* Only one thread can accept at a time */
460 fail_this_transaction = 0;
461 ssock = accept(msock, NULL, 0);
463 lprintf(2, "accept() failed: %s\n", strerror(errno));
465 /* Set the SO_REUSEADDR socket option */
467 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
470 /* If we are an HTTPS server, go crypto now. */
473 if (starttls(ssock) != 0) {
474 fail_this_transaction = 1;
480 if (fail_this_transaction == 0) {
481 /* Perform an HTTP transaction... */
483 /* ...and close the socket. */
484 lingering_close(ssock);
489 } while (!time_to_die);
495 int lprintf(int loglevel, const char *format, ...)
499 if (loglevel <= verbosity) {
500 va_start(ap, format);
501 vfprintf(stderr, format, ap);