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