]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
did a minimal amount of ANSIfication without changing anything that would
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel/UX "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14
15 #ifdef DLL_EXPORT
16 #define IN_LIBCIT
17 #endif
18
19 #include "sysdep.h"
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <fcntl.h>
24 #include <ctype.h>
25 #include <signal.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <sys/socket.h>
30
31 #if TIME_WITH_SYS_TIME
32 # include <sys/time.h>
33 # include <time.h>
34 #else
35 # if HAVE_SYS_TIME_H
36 #  include <sys/time.h>
37 # else
38 #  include <time.h>
39 # endif
40 #endif
41
42 #include <limits.h>
43 #include <netinet/in.h>
44 #include <netdb.h>
45 #include <sys/un.h>
46 #include <string.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <stdarg.h>
50 #include <syslog.h>
51 #include <grp.h>
52 #ifdef HAVE_PTHREAD_H
53 #include <pthread.h>
54 #endif
55 #include "citadel.h"
56 #include "server.h"
57 #include "serv_extensions.h"
58 #include "sysdep_decls.h"
59 #include "citserver.h"
60 #include "support.h"
61 #include "config.h"
62 #include "database.h"
63 #include "housekeeping.h"
64 #include "tools.h"
65 #include "serv_crypto.h"
66
67 #ifdef HAVE_SYS_SELECT_H
68 #include <sys/select.h>
69 #endif
70
71 #ifndef HAVE_SNPRINTF
72 #include "snprintf.h"
73 #endif
74
75 #ifdef DEBUG_MEMORY_LEAKS
76 struct TheHeap *heap = NULL;
77 #endif
78
79 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
80 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
81
82 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
83
84 struct CitContext masterCC;
85 int rescan[2];                                  /* The Rescan Pipe */
86 time_t last_purge = 0;                          /* Last dead session purge */
87 static int num_threads = 0;                     /* Current number of threads */
88 int num_sessions = 0;                           /* Current number of sessions */
89
90 fd_set masterfds;                               /* Master sockets etc. */
91 int masterhighest;
92
93 pthread_t initial_thread;               /* tid for main() thread */
94
95
96 /*
97  * lprintf()  ...   Write logging information
98  * 
99  * Note: the variable "buf" below needs to be large enough to handle any
100  * log data sent through this function.  BE CAREFUL!
101  */
102 void lprintf(int loglevel, const char *format, ...) {   
103         va_list arg_ptr;
104         char buf[SIZ];
105   
106         va_start(arg_ptr, format);   
107         vsnprintf(buf, sizeof(buf), format, arg_ptr);   
108         va_end(arg_ptr);   
109
110         if (loglevel <= verbosity) { 
111                 struct timeval tv;
112                 struct tm *tim;
113                 time_t unixtime;
114
115                 gettimeofday(&tv, NULL);
116                 /* Promote to time_t; types differ on some OSes (like darwin) */
117                 unixtime = tv.tv_sec;
118                 tim = localtime(&unixtime);
119                 /*
120                  * Log provides millisecond accuracy.  If you need
121                  * microsecond accuracy and your OS supports it, change
122                  * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
123                  */
124                 if (CC && CC->cs_pid) {
125                         fprintf(stderr,
126                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%3d] %s",
127                                 tim->tm_year + 1900, tim->tm_mon + 1,
128                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
129                                 tim->tm_sec, (long)tv.tv_usec / 1000,
130                                 CC->cs_pid, buf);
131                 } else {
132                         fprintf(stderr,
133                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld %s",
134                                 tim->tm_year + 1900, tim->tm_mon + 1,
135                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
136                                 tim->tm_sec, (long)tv.tv_usec / 1000, buf);
137                 }
138                 fflush(stderr);
139         }
140
141         PerformLogHooks(loglevel, buf);
142 }   
143
144
145
146 #ifdef DEBUG_MEMORY_LEAKS
147 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
148         void *ptr;
149         struct TheHeap *hptr;
150
151         ptr = malloc(tsize);
152         if (ptr == NULL) {
153                 lprintf(3, "DANGER!  mallok(%d) at %s:%d failed!\n",
154                         tsize, tfile, tline);
155                 return(NULL);
156         }
157
158         hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
159         strcpy(hptr->h_file, tfile);
160         hptr->h_line = tline;
161         hptr->next = heap;
162         hptr->h_ptr = ptr;
163         heap = hptr;
164         return ptr;
165 }
166
167 char *tracked_strdup(const char *orig, char *tfile, int tline) {
168         char *s;
169
170         s = tracked_malloc( (strlen(orig)+1), tfile, tline);
171         if (s == NULL) return NULL;
172
173         strcpy(s, orig);
174         return s;
175 }
176
177 void tracked_free(void *ptr) {
178         struct TheHeap *hptr, *freeme;
179
180         if (heap->h_ptr == ptr) {
181                 hptr = heap->next;
182                 free(heap);
183                 heap = hptr;
184         }
185         else {
186                 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
187                         if (hptr->next->h_ptr == ptr) {
188                                 freeme = hptr->next;
189                                 hptr->next = hptr->next->next;
190                                 free(freeme);
191                         }
192                 }
193         }
194
195         free(ptr);
196 }
197
198 void *tracked_realloc(void *ptr, size_t size) {
199         void *newptr;
200         struct TheHeap *hptr;
201         
202         newptr = realloc(ptr, size);
203
204         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
205                 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
206         }
207
208         return newptr;
209 }
210
211
212 void dump_tracked() {
213         struct TheHeap *hptr;
214
215         cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);    
216         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
217                 cprintf("%20s %5d\n",
218                         hptr->h_file, hptr->h_line);
219         }
220 #ifdef __GNUC__
221         malloc_stats();
222 #endif
223
224         cprintf("000\n");
225 }
226 #endif
227
228
229 /*
230  * We used to use master_cleanup() as a signal handler to shut down the server.
231  * however, master_cleanup() and the functions it calls do some things that
232  * aren't such a good idea to do from a signal handler: acquiring mutexes,
233  * playing with signal masks on BSDI systems, etc. so instead we install the
234  * following signal handler to set a global variable to inform the main loop
235  * that it's time to call master_cleanup() and exit.
236  */
237
238 volatile int time_to_die = 0;
239
240 static RETSIGTYPE signal_cleanup(int signum) {
241         time_to_die = 1;
242 }
243
244
245 /*
246  * Some initialization stuff...
247  */
248 void init_sysdep(void) {
249         int a;
250
251 #ifdef HAVE_OPENSSL
252         init_ssl();
253 #endif
254
255         /* Set up a bunch of semaphores to be used for critical sections */
256         for (a=0; a<MAX_SEMAPHORES; ++a) {
257                 pthread_mutex_init(&Critters[a], NULL);
258         }
259
260         /*
261          * Set up a place to put thread-specific data.
262          * We only need a single pointer per thread - it points to the
263          * CitContext structure (in the ContextList linked list) of the
264          * session to which the calling thread is currently bound.
265          */
266         if (pthread_key_create(&MyConKey, NULL) != 0) {
267                 lprintf(1, "Can't create TSD key!!  %s\n", strerror(errno));
268         }
269
270         /*
271          * The action for unexpected signals and exceptions should be to
272          * call signal_cleanup() to gracefully shut down the server.
273          */
274         signal(SIGINT, signal_cleanup);
275         signal(SIGQUIT, signal_cleanup);
276         signal(SIGHUP, signal_cleanup);
277         signal(SIGTERM, signal_cleanup);
278
279         /*
280          * Do not shut down the server on broken pipe signals, otherwise the
281          * whole Citadel service would come down whenever a single client
282          * socket breaks.
283          */
284         signal(SIGPIPE, SIG_IGN);
285 }
286
287
288 /*
289  * Obtain a semaphore lock to begin a critical section.
290  */
291 void begin_critical_section(int which_one)
292 {
293         /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
294         /* ensure nobody ever tries to do a critical section within a
295            transaction; this could lead to deadlock. */
296         cdb_check_handles();
297         pthread_mutex_lock(&Critters[which_one]);
298 }
299
300 /*
301  * Release a semaphore lock to end a critical section.
302  */
303 void end_critical_section(int which_one)
304 {
305         /* lprintf(9, "end_critical_section(%d)\n", which_one); */
306         pthread_mutex_unlock(&Critters[which_one]);
307 }
308
309
310
311 /*
312  * This is a generic function to set up a master socket for listening on
313  * a TCP port.  The server shuts down if the bind fails.
314  *
315  */
316 int ig_tcp_server(int port_number, int queue_len)
317 {
318         struct sockaddr_in sin;
319         int s, i;
320         int actual_queue_len;
321
322         actual_queue_len = queue_len;
323         if (actual_queue_len < 5) actual_queue_len = 5;
324
325         memset(&sin, 0, sizeof(sin));
326         sin.sin_family = AF_INET;
327         sin.sin_addr.s_addr = INADDR_ANY;
328         sin.sin_port = htons((u_short)port_number);
329
330         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
331
332         if (s < 0) {
333                 lprintf(1, "citserver: Can't create a socket: %s\n",
334                         strerror(errno));
335                 return(-1);
336         }
337
338         i = 1;
339         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
340
341         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
342                 lprintf(1, "citserver: Can't bind: %s\n",
343                         strerror(errno));
344                 close(s);
345                 return(-1);
346         }
347
348         if (listen(s, actual_queue_len) < 0) {
349                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
350                 close(s);
351                 return(-1);
352         }
353
354         return(s);
355 }
356
357
358
359 /*
360  * Create a Unix domain socket and listen on it
361  */
362 int ig_uds_server(char *sockpath, int queue_len)
363 {
364         struct sockaddr_un addr;
365         int s;
366         int i;
367         int actual_queue_len;
368
369         actual_queue_len = queue_len;
370         if (actual_queue_len < 5) actual_queue_len = 5;
371
372         i = unlink(sockpath);
373         if (i != 0) if (errno != ENOENT) {
374                 lprintf(1, "citserver: can't unlink %s: %s\n",
375                         sockpath, strerror(errno));
376                 return(-1);
377         }
378
379         memset(&addr, 0, sizeof(addr));
380         addr.sun_family = AF_UNIX;
381         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
382
383         s = socket(AF_UNIX, SOCK_STREAM, 0);
384         if (s < 0) {
385                 lprintf(1, "citserver: Can't create a socket: %s\n",
386                         strerror(errno));
387                 return(-1);
388         }
389
390         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
391                 lprintf(1, "citserver: Can't bind: %s\n",
392                         strerror(errno));
393                 return(-1);
394         }
395
396         if (listen(s, actual_queue_len) < 0) {
397                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
398                 return(-1);
399         }
400
401         chmod(sockpath, 0777);
402         return(s);
403 }
404
405
406
407 /*
408  * Return a pointer to the CitContext structure bound to the thread which
409  * called this function.  If there's no such binding (for example, if it's
410  * called by the housekeeper thread) then a generic 'master' CC is returned.
411  *
412  * It's inlined because it's used *VERY* frequently.
413  */
414 INLINE struct CitContext *MyContext(void) {
415         return ((pthread_getspecific(MyConKey) == NULL)
416                 ? &masterCC
417                 : (struct CitContext *) pthread_getspecific(MyConKey)
418         );
419 }
420
421
422 /*
423  * Initialize a new context and place it in the list.  The session number
424  * used to be the PID (which is why it's called cs_pid), but that was when we
425  * had one process per session.  Now we just assign them sequentially, starting
426  * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
427  * sessions terminate.
428  */
429 struct CitContext *CreateNewContext(void) {
430         struct CitContext *me, *ptr;
431
432         me = (struct CitContext *) mallok(sizeof(struct CitContext));
433         if (me == NULL) {
434                 lprintf(1, "citserver: can't allocate memory!!\n");
435                 return NULL;
436         }
437         memset(me, 0, sizeof(struct CitContext));
438
439         /* The new context will be created already in the CON_EXECUTING state
440          * in order to prevent another thread from grabbing it while it's
441          * being set up.
442          */
443         me->state = CON_EXECUTING;
444
445
446         /*
447          * Generate a unique session number and insert this context into
448          * the list.
449          */
450         begin_critical_section(S_SESSION_TABLE);
451
452         if (ContextList == NULL) {
453                 ContextList = me;
454                 me->cs_pid = 1;
455                 me->next = NULL;
456         }
457
458         else if (ContextList->cs_pid > 1) {
459                 me->next = ContextList;
460                 ContextList = me;
461                 me->cs_pid = 1;
462         }
463
464         else {
465                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
466                         if (ptr->next == NULL) {
467                                 ptr->next = me;
468                                 me->cs_pid = ptr->cs_pid + 1;
469                                 me->next = NULL;
470                                 goto DONE;
471                         }
472                         else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
473                                 me->next = ptr->next;
474                                 ptr->next = me;
475                                 me->cs_pid = ptr->cs_pid + 1;
476                                 goto DONE;
477                         }
478                 }
479         }
480
481 DONE:   ++num_sessions;
482         end_critical_section(S_SESSION_TABLE);
483         return(me);
484 }
485
486
487 /*
488  * buffer_output() ... tell client_write to buffer all output until
489  *                     instructed to dump it all out later
490  */
491 void buffer_output(void) {
492         if (CC->buffering == 0) {
493                 CC->buffering = 1;
494                 CC->buffer_len = 0;
495                 CC->output_buffer = mallok(SIZ);
496         }
497 }
498
499 /*
500  * unbuffer_output()  ...  dump out all that output we've been buffering.
501  */
502 void unbuffer_output(void) {
503         if (CC->buffering == 1) {
504                 CC->buffering = 0;
505                 client_write(CC->output_buffer, CC->buffer_len);
506                 phree(CC->output_buffer);
507                 CC->output_buffer = NULL;
508                 CC->buffer_len = 0;
509         }
510 }
511
512
513
514 /*
515  * client_write()   ...    Send binary data to the client.
516  */
517 void client_write(char *buf, int nbytes)
518 {
519         int bytes_written = 0;
520         int retval;
521         int sock;
522         int old_buffer_len = 0;
523
524         if (CC->redirect_fp != NULL) {
525                 fwrite(buf, nbytes, 1, CC->redirect_fp);
526                 return;
527         }
528
529         if (CC->redirect_sock > 0) {
530                 sock = CC->redirect_sock;       /* and continue below... */
531         }
532         else {
533                 sock = CC->client_socket;
534         }
535
536         /* If we're buffering for later, do that now. */
537         if (CC->buffering) {
538                 old_buffer_len = CC->buffer_len;
539                 CC->buffer_len += nbytes;
540                 CC->output_buffer = reallok(CC->output_buffer, CC->buffer_len);
541                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
542                 return;
543         }
544
545         /* Ok, at this point we're not buffering.  Go ahead and write. */
546
547 #ifdef HAVE_OPENSSL
548         if (CC->redirect_ssl) {
549                 client_write_ssl(buf, nbytes);
550                 return;
551         }
552 #endif
553
554         while (bytes_written < nbytes) {
555                 retval = write(sock, &buf[bytes_written],
556                         nbytes - bytes_written);
557                 if (retval < 1) {
558                         lprintf(2, "client_write() failed: %s\n",
559                                 strerror(errno));
560                         if (sock == CC->client_socket) CC->kill_me = 1;
561                         return;
562                 }
563                 bytes_written = bytes_written + retval;
564         }
565 }
566
567
568 /*
569  * cprintf()  ...   Send formatted printable data to the client.   It is
570  *                  implemented in terms of client_write() but remains in
571  *                  sysdep.c in case we port to somewhere without va_args...
572  */
573 void cprintf(const char *format, ...) {   
574         va_list arg_ptr;   
575         char buf[SIZ];   
576    
577         va_start(arg_ptr, format);   
578         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
579                 buf[sizeof buf - 2] = '\n';
580         client_write(buf, strlen(buf)); 
581         va_end(arg_ptr);
582 }   
583
584
585 /*
586  * Read data from the client socket.
587  * Return values are:
588  *      1       Requested number of bytes has been read.
589  *      0       Request timed out.
590  *      -1      The socket is broken.
591  * If the socket breaks, the session will be terminated.
592  */
593 int client_read_to(char *buf, int bytes, int timeout)
594 {
595         int len,rlen;
596         fd_set rfds;
597         struct timeval tv;
598         int retval;
599
600 #ifdef HAVE_OPENSSL
601         if (CC->redirect_ssl) {
602                 return (client_read_ssl(buf, bytes, timeout));
603         }
604 #endif
605         len = 0;
606         while(len<bytes) {
607                 FD_ZERO(&rfds);
608                 FD_SET(CC->client_socket, &rfds);
609                 tv.tv_sec = timeout;
610                 tv.tv_usec = 0;
611
612                 retval = select( (CC->client_socket)+1, 
613                                         &rfds, NULL, NULL, &tv);
614
615                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
616                         return(0);
617                 }
618
619                 rlen = read(CC->client_socket, &buf[len], bytes-len);
620                 if (rlen<1) {
621                         lprintf(2, "client_read() failed: %s\n",
622                                 strerror(errno));
623                         CC->kill_me = 1;
624                         return(-1);
625                 }
626                 len = len + rlen;
627         }
628         return(1);
629 }
630
631 /*
632  * Read data from the client socket with default timeout.
633  * (This is implemented in terms of client_read_to() and could be
634  * justifiably moved out of sysdep.c)
635  */
636 INLINE int client_read(char *buf, int bytes)
637 {
638         return(client_read_to(buf, bytes, config.c_sleeping));
639 }
640
641
642 /*
643  * client_gets()   ...   Get a LF-terminated line of text from the client.
644  * (This is implemented in terms of client_read() and could be
645  * justifiably moved out of sysdep.c)
646  */
647 int client_gets(char *buf)
648 {
649         int i, retval;
650
651         /* Read one character at a time.
652          */
653         for (i = 0;;i++) {
654                 retval = client_read(&buf[i], 1);
655                 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
656                         break;
657         }
658
659         /* If we got a long line, discard characters until the newline.
660          */
661         if (i == (SIZ-1))
662                 while (buf[i] != '\n' && retval == 1)
663                         retval = client_read(&buf[i], 1);
664
665         /* Strip the trailing newline and any trailing nonprintables (cr's)
666          */
667         buf[i] = 0;
668         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
669                 buf[strlen(buf)-1] = 0;
670         if (retval < 0) strcpy(buf, "000");
671         return(retval);
672 }
673
674
675
676 /*
677  * The system-dependent part of master_cleanup() - close the master socket.
678  */
679 void sysdep_master_cleanup(void) {
680         struct ServiceFunctionHook *serviceptr;
681
682         /*
683          * close all protocol master sockets
684          */
685         for (serviceptr = ServiceHookTable; serviceptr != NULL;
686             serviceptr = serviceptr->next ) {
687
688                 if (serviceptr->tcp_port > 0)
689                         lprintf(3, "Closing listener on port %d\n",
690                                 serviceptr->tcp_port);
691
692                 if (serviceptr->sockpath != NULL)
693                         lprintf(3, "Closing listener on '%s'\n",
694                                 serviceptr->sockpath);
695
696                 close(serviceptr->msock);
697
698                 /* If it's a Unix domain socket, remove the file. */
699                 if (serviceptr->sockpath != NULL) {
700                         unlink(serviceptr->sockpath);
701                 }
702         }
703 }
704
705
706 /*
707  * Terminate another session.
708  * (This could justifiably be moved out of sysdep.c because it
709  * no longer does anything that is system-dependent.)
710  */
711 void kill_session(int session_to_kill) {
712         struct CitContext *ptr;
713
714         begin_critical_section(S_SESSION_TABLE);
715         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
716                 if (ptr->cs_pid == session_to_kill) {
717                         ptr->kill_me = 1;
718                 }
719         }
720         end_critical_section(S_SESSION_TABLE);
721 }
722
723
724
725
726 /*
727  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
728  */
729 void start_daemon(int do_close_stdio) {
730         if (do_close_stdio) {
731                 /* close(0); */
732                 close(1);
733                 close(2);
734         }
735         signal(SIGHUP,SIG_IGN);
736         signal(SIGINT,SIG_IGN);
737         signal(SIGQUIT,SIG_IGN);
738         if (fork()!=0) exit(0);
739 }
740
741
742
743 /*
744  * Generic routine to convert a login name to a full name (gecos)
745  * Returns nonzero if a conversion took place
746  */
747 int convert_login(char NameToConvert[]) {
748         struct passwd *pw;
749         int a;
750
751         pw = getpwnam(NameToConvert);
752         if (pw == NULL) {
753                 return(0);
754         }
755         else {
756                 strcpy(NameToConvert, pw->pw_gecos);
757                 for (a=0; a<strlen(NameToConvert); ++a) {
758                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
759                 }
760                 return(1);
761         }
762 }
763
764 struct worker_node *worker_list = NULL;
765
766
767 /*
768  * create a worker thread. this function must always be called from within
769  * an S_WORKER_LIST critical section!
770  */
771 void create_worker(void) {
772         int ret;
773         struct worker_node *n;
774         pthread_attr_t attr;
775
776         n = mallok(sizeof(struct worker_node));
777         if (n == NULL) {
778                 lprintf(1, "can't allocate worker_node, exiting\n");
779                 time_to_die = -1;
780                 return;
781         }
782
783         if ((ret = pthread_attr_init(&attr))) {
784                 lprintf(1, "pthread_attr_init: %s\n", strerror(ret));
785                 time_to_die = -1;
786                 return;
787         }
788
789         /* we seem to need something bigger than FreeBSD's default 64k stack */
790
791         if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
792                 lprintf(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
793                 time_to_die = -1;
794                 return;
795         }
796
797         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
798         {
799
800                 lprintf(1, "Can't create worker thread: %s\n",
801                         strerror(ret));
802         }
803
804         n->next = worker_list;
805         worker_list = n;
806 }
807
808
809
810 /*
811  * Purge all sessions which have the 'kill_me' flag set.
812  * This function has code to prevent it from running more than once every
813  * few seconds, because running it after every single unbind would waste a lot
814  * of CPU time and keep the context list locked too much.
815  *
816  * After that's done, we raise or lower the size of the worker thread pool
817  * if such an action is appropriate.
818  */
819 void dead_session_purge(void) {
820         struct CitContext *ptr, *rem;
821         struct worker_node **node, *tmp;
822         pthread_t self;
823
824         if ( (time(NULL) - last_purge) < 5 ) return;    /* Too soon, go away */
825         time(&last_purge);
826
827         do {
828                 rem = NULL;
829                 begin_critical_section(S_SESSION_TABLE);
830                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
831                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
832                                 rem = ptr;
833                         }
834                 }
835                 end_critical_section(S_SESSION_TABLE);
836
837                 /* RemoveContext() enters its own S_SESSION_TABLE critical
838                  * section, so we have to do it like this.
839                  */     
840                 if (rem != NULL) {
841                         lprintf(9, "Purging session %d\n", rem->cs_pid);
842                         RemoveContext(rem);
843                 }
844
845         } while (rem != NULL);
846
847
848         /* Raise or lower the size of the worker thread pool if such
849          * an action is appropriate.
850          */
851
852         self = pthread_self();
853
854         if ( (num_sessions > num_threads)
855            && (num_threads < config.c_max_workers) ) {
856                 begin_critical_section(S_WORKER_LIST);
857                 create_worker();
858                 end_critical_section(S_WORKER_LIST);
859         }
860         
861         /* don't let the initial thread die since it's responsible for
862            waiting for all the other threads to terminate. */
863         else if ( (num_sessions < num_threads)
864            && (num_threads > config.c_min_workers)
865            && (self != initial_thread) ) {
866                 cdb_free_tsd();
867                 begin_critical_section(S_WORKER_LIST);
868                 --num_threads;
869
870                 /* we're exiting before server shutdown... unlink ourself from
871                    the worker list and detach our thread to avoid memory leaks
872                  */
873
874                 for (node = &worker_list; *node != NULL; node = &(*node)->next)
875                         if ((*node)->tid == self) {
876                                 tmp = *node;
877                                 *node = (*node)->next;
878                                 phree(tmp);
879                                 break;
880                         }
881
882                 pthread_detach(self);
883                 end_critical_section(S_WORKER_LIST);
884                 pthread_exit(NULL);
885         }
886
887 }
888
889
890
891
892
893 /*
894  * Redirect a session's output to a file or socket.
895  * This function may be called with a file handle *or* a socket (but not
896  * both).  Call with neither to return output to its normal client socket.
897  */
898 void CtdlRedirectOutput(FILE *fp, int sock) {
899
900         if (fp != NULL) CC->redirect_fp = fp;
901         else CC->redirect_fp = NULL;
902
903         if (sock > 0) CC->redirect_sock = sock;
904         else CC->redirect_sock = (-1);
905
906 }
907
908
909 /*
910  * masterCC is the context we use when not attached to a session.  This
911  * function initializes it.
912  */
913 void InitializeMasterCC(void) {
914         memset(&masterCC, 0, sizeof(struct CitContext));
915         masterCC.internal_pgm = 1;
916         masterCC.cs_pid = 0;
917 }
918
919
920
921 /*
922  * Set up a fd_set containing all the master sockets to which we
923  * always listen.  It's computationally less expensive to just copy
924  * this to a local fd_set when starting a new select() and then add
925  * the client sockets than it is to initialize a new one and then
926  * figure out what to put there.
927  */
928 void init_master_fdset(void) {
929         struct ServiceFunctionHook *serviceptr;
930         int m;
931
932         lprintf(9, "Initializing master fdset\n");
933
934         FD_ZERO(&masterfds);
935         masterhighest = 0;
936
937         lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
938         FD_SET(rescan[0], &masterfds);
939         if (rescan[0] > masterhighest) masterhighest = rescan[0];
940
941         for (serviceptr = ServiceHookTable; serviceptr != NULL;
942             serviceptr = serviceptr->next ) {
943                 m = serviceptr->msock;
944                 lprintf(9, "Will listen on master socket %d\n", m);
945                 FD_SET(m, &masterfds);
946                 if (m > masterhighest) {
947                         masterhighest = m;
948                 }
949         }
950         lprintf(9, "masterhighest = %d\n", masterhighest);
951 }
952
953
954 /*
955  * Bind a thread to a context.  (It's inline merely to speed things up.)
956  */
957 INLINE void become_session(struct CitContext *which_con) {
958         pthread_setspecific(MyConKey, (void *)which_con );
959 }
960
961
962
963 /* 
964  * This loop just keeps going and going and going...
965  */     
966 void *worker_thread(void *arg) {
967         int i;
968         char junk;
969         int highest;
970         struct CitContext *ptr;
971         struct CitContext *bind_me = NULL;
972         fd_set readfds;
973         int retval;
974         struct CitContext *con= NULL;   /* Temporary context pointer */
975         struct ServiceFunctionHook *serviceptr;
976         int ssock;                      /* Descriptor for client socket */
977         struct timeval tv;
978
979         num_threads++;
980
981         cdb_allocate_tsd();
982
983         while (!time_to_die) {
984
985                 /* 
986                  * A naive implementation would have all idle threads
987                  * calling select() and then they'd all wake up at once
988                  * (known in computer science as the "thundering herd"
989                  * problem).  We solve this problem by putting the select()
990                  * in a critical section, so only one thread has the
991                  * opportunity to wake up.  If we wake up on a master
992                  * socket, create a new session context; otherwise, just
993                  * bind the thread to the context we want and go on our
994                  * merry way.
995                  */
996
997                 /* make doubly sure we're not holding any stale db handles
998                  * which might cause a deadlock.
999                  */
1000                 cdb_check_handles();
1001
1002                 begin_critical_section(S_I_WANNA_SELECT);
1003 SETUP_FD:       memcpy(&readfds, &masterfds, sizeof masterfds);
1004                 highest = masterhighest;
1005                 begin_critical_section(S_SESSION_TABLE);
1006                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1007                         if (ptr->state == CON_IDLE) {
1008                                 FD_SET(ptr->client_socket, &readfds);
1009                                 if (ptr->client_socket > highest)
1010                                         highest = ptr->client_socket;
1011                         }
1012                 }
1013                 end_critical_section(S_SESSION_TABLE);
1014
1015                 tv.tv_sec = 1;          /* wake up every second if no input */
1016                 tv.tv_usec = 0;
1017
1018                 do_select:
1019                 if (!time_to_die)
1020                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1021                 else {
1022                         end_critical_section(S_I_WANNA_SELECT);
1023                         break;
1024                 }
1025
1026                 /* Now figure out who made this select() unblock.
1027                  * First, check for an error or exit condition.
1028                  */
1029                 if (retval < 0) {
1030                         if (errno != EINTR) {
1031                                 lprintf(9, "Exiting (%s)\n", strerror(errno));
1032                                 time_to_die = 1;
1033                         } else if (!time_to_die)
1034                                 goto do_select;
1035                 }
1036
1037                 /* Next, check to see if it's a new client connecting
1038                  * on a master socket.
1039                  */
1040                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1041                      serviceptr = serviceptr->next ) {
1042
1043                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1044                                 ssock = accept(serviceptr->msock, NULL, 0);
1045                                 if (ssock < 0) {
1046                                         lprintf(2, "citserver: accept(): %s\n",
1047                                                 strerror(errno));
1048                                 }
1049                                 else {
1050                                         lprintf(7, "citserver: "
1051                                                 "New client socket %d\n",
1052                                                 ssock);
1053
1054                                         /* New context will be created already
1055                                         * set up in the CON_EXECUTING state.
1056                                         */
1057                                         con = CreateNewContext();
1058
1059                                         /* Assign new socket number to it. */
1060                                         con->client_socket = ssock;
1061                                         con->h_command_function =
1062                                                 serviceptr->h_command_function;
1063
1064                                         /* Determine whether local socket */
1065                                         if (serviceptr->sockpath != NULL)
1066                                                 con->is_local_socket = 1;
1067         
1068                                         /* Set the SO_REUSEADDR socket option */
1069                                         i = 1;
1070                                         setsockopt(ssock, SOL_SOCKET,
1071                                                 SO_REUSEADDR,
1072                                                 &i, sizeof(i));
1073
1074                                         become_session(con);
1075                                         begin_session(con);
1076                                         serviceptr->h_greeting_function();
1077                                         become_session(NULL);
1078                                         con->state = CON_IDLE;
1079                                         goto SETUP_FD;
1080                                 }
1081                         }
1082                 }
1083
1084                 /* If the rescan pipe went active, someone is telling this
1085                  * thread that the &readfds needs to be refreshed with more
1086                  * current data.
1087                  */
1088                 if (time_to_die) {
1089                         end_critical_section(S_I_WANNA_SELECT);
1090                         break;
1091                 }
1092
1093                 if (FD_ISSET(rescan[0], &readfds)) {
1094                         read(rescan[0], &junk, 1);
1095                         goto SETUP_FD;
1096                 }
1097
1098                 /* It must be a client socket.  Find a context that has data
1099                  * waiting on its socket *and* is in the CON_IDLE state.
1100                  */
1101                 else {
1102                         bind_me = NULL;
1103                         begin_critical_section(S_SESSION_TABLE);
1104                         for (ptr = ContextList;
1105                             ( (ptr != NULL) && (bind_me == NULL) );
1106                             ptr = ptr->next) {
1107                                 if ( (FD_ISSET(ptr->client_socket, &readfds))
1108                                    && (ptr->state == CON_IDLE) ) {
1109                                         bind_me = ptr;
1110                                 }
1111                         }
1112                         if (bind_me != NULL) {
1113                                 /* Found one.  Stake a claim to it before
1114                                  * letting anyone else touch the context list.
1115                                  */
1116                                 bind_me->state = CON_EXECUTING;
1117                         }
1118
1119                         end_critical_section(S_SESSION_TABLE);
1120                         end_critical_section(S_I_WANNA_SELECT);
1121
1122                         /* We're bound to a session, now do *one* command */
1123                         if (bind_me != NULL) {
1124                                 become_session(bind_me);
1125                                 CC->h_command_function();
1126                                 become_session(NULL);
1127                                 bind_me->state = CON_IDLE;
1128                                 if (bind_me->kill_me == 1) {
1129                                         RemoveContext(bind_me);
1130                                 } 
1131                                 write(rescan[1], &junk, 1);
1132                         }
1133
1134                 }
1135                 dead_session_purge();
1136                 do_housekeeping();
1137                 check_sched_shutdown();
1138         }
1139
1140         /* If control reaches this point, the server is shutting down */        
1141         --num_threads;
1142         return NULL;
1143 }