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