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>
39 #include "webserver.h"
42 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
45 int verbosity = 9; /* Logging level */
46 int msock; /* master listening socket */
47 extern void *context_loop(int);
48 extern void *housekeeping_loop(void);
49 extern pthread_mutex_t SessionListMutex;
50 extern pthread_key_t MyConKey;
53 char *server_cookie = NULL;
56 char *defaulthost = DEFAULT_HOST;
57 char *defaultport = DEFAULT_PORT;
59 pthread_mutex_t AcceptQueue;
62 * 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.
65 int ig_tcp_server(int port_number, int queue_len)
67 struct sockaddr_in sin;
70 memset(&sin, 0, sizeof(sin));
71 sin.sin_family = AF_INET;
72 sin.sin_addr.s_addr = INADDR_ANY;
74 if (port_number == 0) {
75 lprintf(1, "Cannot start: no port number specified.\n");
78 sin.sin_port = htons((u_short) port_number);
80 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
82 lprintf(1, "Can't create a socket: %s\n",
86 /* Set some socket options that make sense. */
88 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
90 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
91 lprintf(1, "Can't bind: %s\n", strerror(errno));
94 if (listen(s, queue_len) < 0) {
95 lprintf(1, "Can't listen: %s\n", strerror(errno));
103 * Read data from the client socket.
105 * 1 Requested number of bytes has been read.
106 * 0 Request timed out.
107 * -1 Connection is broken, or other error.
109 int client_read_to(int sock, char *buf, int bytes, int timeout)
117 while (len < bytes) {
123 retval = select((sock) + 1,
124 &rfds, NULL, NULL, &tv);
125 if (FD_ISSET(sock, &rfds) == 0) {
128 rlen = read(sock, &buf[len], bytes - len);
130 lprintf(2, "client_read() failed: %s\n",
140 * Read data from the client socket with default timeout.
141 * (This is implemented in terms of client_read_to() and could be
142 * justifiably moved out of sysdep.c)
144 int client_read(int sock, char *buf, int bytes)
146 return (client_read_to(sock, buf, bytes, SLEEPING));
151 * client_gets() ... Get a LF-terminated line of text from the client.
152 * (This is implemented in terms of client_read() and could be
153 * justifiably moved out of sysdep.c)
155 int client_gets(int sock, char *buf)
159 /* Read one character at a time.
162 retval = client_read(sock, &buf[i], 1);
163 if (retval != 1 || buf[i] == '\n' || i == 255)
167 /* If we got a long line, discard characters until the newline.
170 while (buf[i] != '\n' && retval == 1)
171 retval = client_read(sock, &buf[i], 1);
174 * Strip any trailing non-printable characters.
177 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
178 buf[strlen(buf) - 1] = 0;
185 * Start running as a daemon. Only close stdio if do_close_stdio is set.
187 void start_daemon(int do_close_stdio)
189 if (do_close_stdio) {
194 signal(SIGHUP, SIG_IGN);
195 signal(SIGINT, SIG_IGN);
196 signal(SIGQUIT, SIG_IGN);
201 void spawn_another_worker_thread() {
202 pthread_t SessThread; /* Thread descriptor */
203 pthread_attr_t attr; /* Thread attributes */
205 lprintf(3, "Creating a new thread\n");
207 /* set attributes for the new thread */
208 pthread_attr_init(&attr);
209 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
211 /* now create the thread */
212 if (pthread_create(&SessThread, &attr,
213 (void *(*)(void *)) worker_entry, NULL)
215 lprintf(1, "Can't create thread: %s\n",
221 * Here's where it all begins.
223 int main(int argc, char **argv)
225 pthread_t SessThread; /* Thread descriptor */
226 pthread_attr_t attr; /* Thread attributes */
227 int a, i; /* General-purpose variables */
228 int port = PORT_NUM; /* Port to listen on */
229 char tracefile[PATH_MAX];
231 /* Parse command line */
232 while ((a = getopt(argc, argv, "hp:t:c")) != EOF)
238 strcpy(tracefile, optarg);
239 freopen(tracefile, "w", stdout);
240 freopen(tracefile, "w", stderr);
241 freopen(tracefile, "r", stdin);
244 verbosity = atoi(optarg);
247 server_cookie = malloc(SIZ);
248 if (server_cookie != NULL) {
249 strcpy(server_cookie, "Set-cookie: wcserver=");
251 &server_cookie[strlen(server_cookie)],
253 lprintf(2, "gethostname: %s\n",
260 fprintf(stderr, "usage: webserver [-p localport] "
261 "[-t tracefile] [-c] "
262 "[remotehost [remoteport]]\n");
267 defaulthost = argv[optind];
269 defaultport = argv[optind];
271 /* Tell 'em who's in da house */
272 lprintf(1, SERVER "\n"
273 "Copyright (C) 1996-2001 by the Citadel/UX development team.\n"
274 "This software is distributed under the terms of the GNU General Public\n"
275 "License. If you paid for this software, someone is ripping you off.\n\n");
277 if (chdir(WEBCITDIR) != 0)
281 * Set up a place to put thread-specific data.
282 * We only need a single pointer per thread - it points to the
283 * wcsession struct to which the thread is currently bound.
285 if (pthread_key_create(&MyConKey, NULL) != 0) {
286 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
290 * Bind the server to our favorite port.
291 * There is no need to check for errors, because ig_tcp_server()
292 * exits if it doesn't succeed.
294 lprintf(2, "Attempting to bind to port %d...\n", port);
295 msock = ig_tcp_server(port, LISTEN_QUEUE_LENGTH);
296 lprintf(2, "Listening on socket %d\n", msock);
297 signal(SIGPIPE, SIG_IGN);
299 pthread_mutex_init(&SessionListMutex, NULL);
300 pthread_mutex_init(&AcceptQueue, NULL);
303 * Start up the housekeeping thread
305 pthread_attr_init(&attr);
306 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
307 pthread_create(&SessThread, &attr,
308 (void *(*)(void *)) housekeeping_loop, NULL);
311 /* Start a few initial worker threads */
312 for (i=0; i<(INITIAL_WORKER_THREADS); ++i) {
313 spawn_another_worker_thread();
316 /* now the original thread can go away. */
323 * Entry point for worker threads
325 void worker_entry(void) {
327 struct sockaddr_in fsin;
331 time_t start_time, stop_time;
334 /* Only one thread can accept at a time */
335 start_time = time(NULL);
336 pthread_mutex_lock(&AcceptQueue);
337 ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
338 pthread_mutex_unlock(&AcceptQueue);
339 stop_time = time(NULL);
341 /* Augment the thread pool if we're not blocking at all */
342 if ( (stop_time - start_time) == 0L) {
343 spawn_another_worker_thread();
347 lprintf(2, "accept() failed: %s\n", strerror(errno));
349 /* Set the SO_REUSEADDR socket option */
351 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
354 /* Perform an HTTP transaction... */
357 /* ...and close the socket. */
358 lingering_close(ssock);
361 } while (!time_to_die);
367 int lprintf(int loglevel, const char *format, ...)
372 va_start(ap, format);
373 vsprintf(buf, format, ap);
376 if (loglevel <= verbosity) {
380 gettimeofday(&tv, NULL);
381 tim = localtime(&(tv.tv_sec));
383 if (WC && WC->wc_session) {
385 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld:%d] %s",
386 tim->tm_year + 1900, tim->tm_mon + 1,
387 tim->tm_mday, tim->tm_hour, tim->tm_min,
388 tim->tm_sec, (long)tv.tv_usec / 1000,
389 pthread_self(), WC->wc_session, buf);
392 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld] %s",
393 tim->tm_year + 1900, tim->tm_mon + 1,
394 tim->tm_mday, tim->tm_hour, tim->tm_min,
395 tim->tm_sec, (long)tv.tv_usec / 1000,
396 pthread_self(), buf);