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