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