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