]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* When a session kills itself (for example, due to a broken socket),
[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 #ifdef HAVE_OPENSSL
210         init_ssl();
211 #endif
212
213         /* Set up a bunch of semaphores to be used for critical sections */
214         for (a=0; a<MAX_SEMAPHORES; ++a) {
215                 pthread_mutex_init(&Critters[a], NULL);
216         }
217
218         /*
219          * Set up a place to put thread-specific data.
220          * We only need a single pointer per thread - it points to the
221          * CitContext structure (in the ContextList linked list) of the
222          * session to which the calling thread is currently bound.
223          */
224         if (pthread_key_create(&MyConKey, NULL) != 0) {
225                 lprintf(CTDL_CRIT, "Can't create TSD key!!  %s\n", strerror(errno));
226         }
227
228         /*
229          * The action for unexpected signals and exceptions should be to
230          * call signal_cleanup() to gracefully shut down the server.
231          */
232         signal(SIGINT, signal_cleanup);
233         signal(SIGQUIT, signal_cleanup);
234         signal(SIGHUP, signal_cleanup);
235         signal(SIGTERM, signal_cleanup);
236
237         /*
238          * Do not shut down the server on broken pipe signals, otherwise the
239          * whole Citadel service would come down whenever a single client
240          * socket breaks.
241          */
242         signal(SIGPIPE, SIG_IGN);
243 }
244
245
246 /*
247  * Obtain a semaphore lock to begin a critical section.
248  */
249 void begin_critical_section(int which_one)
250 {
251         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
252
253         /* For all types of critical sections except those listed here,
254          * ensure nobody ever tries to do a critical section within a
255          * transaction; this could lead to deadlock.
256          */
257         if (    (which_one != S_FLOORCACHE)
258 #ifdef DEBUG_MEMORY_LEAKS
259                 && (which_one != S_DEBUGMEMLEAKS)
260 #endif
261         ) {
262                 cdb_check_handles();
263         }
264         pthread_mutex_lock(&Critters[which_one]);
265 }
266
267 /*
268  * Release a semaphore lock to end a critical section.
269  */
270 void end_critical_section(int which_one)
271 {
272         pthread_mutex_unlock(&Critters[which_one]);
273 }
274
275
276
277 /*
278  * This is a generic function to set up a master socket for listening on
279  * a TCP port.  The server shuts down if the bind fails.
280  *
281  */
282 int ig_tcp_server(int port_number, int queue_len)
283 {
284         struct sockaddr_in sin;
285         int s, i;
286         int actual_queue_len;
287
288         actual_queue_len = queue_len;
289         if (actual_queue_len < 5) actual_queue_len = 5;
290
291         memset(&sin, 0, sizeof(sin));
292         sin.sin_family = AF_INET;
293         sin.sin_addr.s_addr = INADDR_ANY;
294         sin.sin_port = htons((u_short)port_number);
295
296         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
297
298         if (s < 0) {
299                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
300                         strerror(errno));
301                 return(-1);
302         }
303
304         i = 1;
305         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
306
307         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
308                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
309                         strerror(errno));
310                 close(s);
311                 return(-1);
312         }
313
314         if (listen(s, actual_queue_len) < 0) {
315                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
316                 close(s);
317                 return(-1);
318         }
319
320         return(s);
321 }
322
323
324
325 /*
326  * Create a Unix domain socket and listen on it
327  */
328 int ig_uds_server(char *sockpath, int queue_len)
329 {
330         struct sockaddr_un addr;
331         int s;
332         int 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         i = unlink(sockpath);
339         if (i != 0) if (errno != ENOENT) {
340                 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
341                         sockpath, strerror(errno));
342                 return(-1);
343         }
344
345         memset(&addr, 0, sizeof(addr));
346         addr.sun_family = AF_UNIX;
347         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
348
349         s = socket(AF_UNIX, SOCK_STREAM, 0);
350         if (s < 0) {
351                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
352                         strerror(errno));
353                 return(-1);
354         }
355
356         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
357                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
358                         strerror(errno));
359                 return(-1);
360         }
361
362         if (listen(s, actual_queue_len) < 0) {
363                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
364                 return(-1);
365         }
366
367         chmod(sockpath, 0777);
368         return(s);
369 }
370
371
372
373 /*
374  * Return a pointer to the CitContext structure bound to the thread which
375  * called this function.  If there's no such binding (for example, if it's
376  * called by the housekeeper thread) then a generic 'master' CC is returned.
377  *
378  * It's inlined because it's used *VERY* frequently.
379  */
380 INLINE struct CitContext *MyContext(void) {
381         return ((pthread_getspecific(MyConKey) == NULL)
382                 ? &masterCC
383                 : (struct CitContext *) pthread_getspecific(MyConKey)
384         );
385 }
386
387
388 /*
389  * Initialize a new context and place it in the list.  The session number
390  * used to be the PID (which is why it's called cs_pid), but that was when we
391  * had one process per session.  Now we just assign them sequentially, starting
392  * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
393  * sessions terminate.
394  */
395 struct CitContext *CreateNewContext(void) {
396         struct CitContext *me, *ptr;
397
398         me = (struct CitContext *) malloc(sizeof(struct CitContext));
399         if (me == NULL) {
400                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
401                 return NULL;
402         }
403         memset(me, 0, sizeof(struct CitContext));
404
405         /* The new context will be created already in the CON_EXECUTING state
406          * in order to prevent another thread from grabbing it while it's
407          * being set up.
408          */
409         me->state = CON_EXECUTING;
410
411
412         /*
413          * Generate a unique session number and insert this context into
414          * the list.
415          */
416         begin_critical_section(S_SESSION_TABLE);
417
418         if (ContextList == NULL) {
419                 ContextList = me;
420                 me->cs_pid = 1;
421                 me->next = NULL;
422         }
423
424         else if (ContextList->cs_pid > 1) {
425                 me->next = ContextList;
426                 ContextList = me;
427                 me->cs_pid = 1;
428         }
429
430         else {
431                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
432                         if (ptr->next == NULL) {
433                                 ptr->next = me;
434                                 me->cs_pid = ptr->cs_pid + 1;
435                                 me->next = NULL;
436                                 goto DONE;
437                         }
438                         else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
439                                 me->next = ptr->next;
440                                 ptr->next = me;
441                                 me->cs_pid = ptr->cs_pid + 1;
442                                 goto DONE;
443                         }
444                 }
445         }
446
447 DONE:   ++num_sessions;
448         end_critical_section(S_SESSION_TABLE);
449         return(me);
450 }
451
452
453 /*
454  * buffer_output() ... tell client_write to buffer all output until
455  *                     instructed to dump it all out later
456  */
457 void buffer_output(void) {
458         if (CC->buffering == 0) {
459                 CC->buffering = 1;
460                 CC->buffer_len = 0;
461                 CC->output_buffer = malloc(SIZ);
462         }
463 }
464
465 /*
466  * unbuffer_output()  ...  dump out all that output we've been buffering.
467  */
468 void unbuffer_output(void) {
469         if (CC->buffering == 1) {
470                 CC->buffering = 0;
471                 client_write(CC->output_buffer, CC->buffer_len);
472                 free(CC->output_buffer);
473                 CC->output_buffer = NULL;
474                 CC->buffer_len = 0;
475         }
476 }
477
478
479
480 /*
481  * client_write()   ...    Send binary data to the client.
482  */
483 void client_write(char *buf, int nbytes)
484 {
485         int bytes_written = 0;
486         int retval;
487         int sock;
488         int old_buffer_len = 0;
489
490         if (CC->redirect_fp != NULL) {
491                 fwrite(buf, nbytes, 1, CC->redirect_fp);
492                 return;
493         }
494
495         if (CC->redirect_sock > 0) {
496                 sock = CC->redirect_sock;       /* and continue below... */
497         }
498         else {
499                 sock = CC->client_socket;
500         }
501
502         /* If we're buffering for later, do that now. */
503         if (CC->buffering) {
504                 old_buffer_len = CC->buffer_len;
505                 CC->buffer_len += nbytes;
506                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
507                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
508                 return;
509         }
510
511         /* Ok, at this point we're not buffering.  Go ahead and write. */
512
513 #ifdef HAVE_OPENSSL
514         if (CC->redirect_ssl) {
515                 client_write_ssl(buf, nbytes);
516                 return;
517         }
518 #endif
519
520         while (bytes_written < nbytes) {
521                 retval = write(sock, &buf[bytes_written],
522                         nbytes - bytes_written);
523                 if (retval < 1) {
524                         lprintf(CTDL_ERR, "client_write() failed: %s\n",
525                                 strerror(errno));
526                         if (sock == CC->client_socket) CC->kill_me = 1;
527                         return;
528                 }
529                 bytes_written = bytes_written + retval;
530         }
531 }
532
533
534 /*
535  * cprintf()  ...   Send formatted printable data to the client.   It is
536  *                  implemented in terms of client_write() but remains in
537  *                  sysdep.c in case we port to somewhere without va_args...
538  */
539 void cprintf(const char *format, ...) {   
540         va_list arg_ptr;   
541         char buf[SIZ];   
542    
543         va_start(arg_ptr, format);   
544         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
545                 buf[sizeof buf - 2] = '\n';
546         client_write(buf, strlen(buf)); 
547         va_end(arg_ptr);
548 }   
549
550
551 /*
552  * Read data from the client socket.
553  * Return values are:
554  *      1       Requested number of bytes has been read.
555  *      0       Request timed out.
556  *      -1      The socket is broken.
557  * If the socket breaks, the session will be terminated.
558  */
559 int client_read_to(char *buf, int bytes, int timeout)
560 {
561         int len,rlen;
562         fd_set rfds;
563         struct timeval tv;
564         int retval;
565
566 #ifdef HAVE_OPENSSL
567         if (CC->redirect_ssl) {
568                 return (client_read_ssl(buf, bytes, timeout));
569         }
570 #endif
571         len = 0;
572         while(len<bytes) {
573                 FD_ZERO(&rfds);
574                 FD_SET(CC->client_socket, &rfds);
575                 tv.tv_sec = timeout;
576                 tv.tv_usec = 0;
577
578                 retval = select( (CC->client_socket)+1, 
579                                         &rfds, NULL, NULL, &tv);
580
581                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
582                         return(0);
583                 }
584
585                 rlen = read(CC->client_socket, &buf[len], bytes-len);
586                 if (rlen<1) {
587                         lprintf(CTDL_ERR, "client_read() failed: %s\n",
588                                 strerror(errno));
589                         CC->kill_me = 1;
590                         return(-1);
591                 }
592                 len = len + rlen;
593         }
594         return(1);
595 }
596
597 /*
598  * Read data from the client socket with default timeout.
599  * (This is implemented in terms of client_read_to() and could be
600  * justifiably moved out of sysdep.c)
601  */
602 INLINE int client_read(char *buf, int bytes)
603 {
604         return(client_read_to(buf, bytes, config.c_sleeping));
605 }
606
607
608 /*
609  * client_gets()   ...   Get a LF-terminated line of text from the client.
610  * (This is implemented in terms of client_read() and could be
611  * justifiably moved out of sysdep.c)
612  */
613 int client_gets(char *buf)
614 {
615         int i, retval;
616
617         /* Read one character at a time.
618          */
619         for (i = 0;;i++) {
620                 retval = client_read(&buf[i], 1);
621                 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
622                         break;
623         }
624
625         /* If we got a long line, discard characters until the newline.
626          */
627         if (i == (SIZ-1))
628                 while (buf[i] != '\n' && retval == 1)
629                         retval = client_read(&buf[i], 1);
630
631         /* Strip the trailing newline and any trailing nonprintables (cr's)
632          */
633         buf[i] = 0;
634         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
635                 buf[strlen(buf)-1] = 0;
636         if (retval < 0) strcpy(buf, "000");
637         return(retval);
638 }
639
640
641
642 /*
643  * The system-dependent part of master_cleanup() - close the master socket.
644  */
645 void sysdep_master_cleanup(void) {
646         struct ServiceFunctionHook *serviceptr;
647
648         /*
649          * close all protocol master sockets
650          */
651         for (serviceptr = ServiceHookTable; serviceptr != NULL;
652             serviceptr = serviceptr->next ) {
653
654                 if (serviceptr->tcp_port > 0)
655                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
656                                 serviceptr->tcp_port);
657
658                 if (serviceptr->sockpath != NULL)
659                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
660                                 serviceptr->sockpath);
661
662                 close(serviceptr->msock);
663
664                 /* If it's a Unix domain socket, remove the file. */
665                 if (serviceptr->sockpath != NULL) {
666                         unlink(serviceptr->sockpath);
667                 }
668         }
669 }
670
671
672 /*
673  * Terminate another session.
674  * (This could justifiably be moved out of sysdep.c because it
675  * no longer does anything that is system-dependent.)
676  */
677 void kill_session(int session_to_kill) {
678         struct CitContext *ptr;
679
680         begin_critical_section(S_SESSION_TABLE);
681         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
682                 if (ptr->cs_pid == session_to_kill) {
683                         ptr->kill_me = 1;
684                 }
685         }
686         end_critical_section(S_SESSION_TABLE);
687 }
688
689
690
691
692 /*
693  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
694  */
695 void start_daemon(int do_close_stdio) {
696         if (do_close_stdio) {
697                 /* close(0); */
698                 close(1);
699                 close(2);
700         }
701         signal(SIGHUP,SIG_IGN);
702         signal(SIGINT,SIG_IGN);
703         signal(SIGQUIT,SIG_IGN);
704         if (fork()!=0) exit(0);
705 }
706
707
708
709 /*
710  * Generic routine to convert a login name to a full name (gecos)
711  * Returns nonzero if a conversion took place
712  */
713 int convert_login(char NameToConvert[]) {
714         struct passwd *pw;
715         int a;
716
717         pw = getpwnam(NameToConvert);
718         if (pw == NULL) {
719                 return(0);
720         }
721         else {
722                 strcpy(NameToConvert, pw->pw_gecos);
723                 for (a=0; a<strlen(NameToConvert); ++a) {
724                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
725                 }
726                 return(1);
727         }
728 }
729
730 struct worker_node *worker_list = NULL;
731
732
733 /*
734  * create a worker thread. this function must always be called from within
735  * an S_WORKER_LIST critical section!
736  */
737 void create_worker(void) {
738         int ret;
739         struct worker_node *n;
740         pthread_attr_t attr;
741
742         n = malloc(sizeof(struct worker_node));
743         if (n == NULL) {
744                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
745                 time_to_die = -1;
746                 return;
747         }
748
749         if ((ret = pthread_attr_init(&attr))) {
750                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
751                 time_to_die = -1;
752                 return;
753         }
754
755         /* we seem to need something bigger than FreeBSD's default 64k stack */
756
757         if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
758                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
759                 time_to_die = -1;
760                 return;
761         }
762
763         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
764         {
765
766                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
767                         strerror(ret));
768         }
769
770         n->next = worker_list;
771         worker_list = n;
772 }
773
774
775
776 /*
777  * Purge all sessions which have the 'kill_me' flag set.
778  * This function has code to prevent it from running more than once every
779  * few seconds, because running it after every single unbind would waste a lot
780  * of CPU time and keep the context list locked too much.  To force it to run
781  * anyway, set "force" to nonzero.
782  *
783  *
784  * After that's done, we raise the size of the worker thread pool
785  * if such an action is appropriate.
786  */
787 void dead_session_purge(int force) {
788         struct CitContext *ptr, *rem;
789
790         if (force == 0) {
791                 if ( (time(NULL) - last_purge) < 5 ) {
792                         return; /* Too soon, go away */
793                 }
794         }
795         time(&last_purge);
796
797         do {
798                 rem = NULL;
799                 begin_critical_section(S_SESSION_TABLE);
800                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
801                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
802                                 rem = ptr;
803                         }
804                 }
805                 end_critical_section(S_SESSION_TABLE);
806
807                 /* RemoveContext() enters its own S_SESSION_TABLE critical
808                  * section, so we have to do it like this.
809                  */     
810                 if (rem != NULL) {
811                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
812                         RemoveContext(rem);
813                 }
814
815         } while (rem != NULL);
816
817         /* Raise the size of the worker thread pool if necessary. */
818
819         if ( (num_sessions > num_threads)
820            && (num_threads < config.c_max_workers) ) {
821                 begin_critical_section(S_WORKER_LIST);
822                 create_worker();
823                 end_critical_section(S_WORKER_LIST);
824         }
825 }
826
827
828
829
830
831 /*
832  * Redirect a session's output to a file or socket.
833  * This function may be called with a file handle *or* a socket (but not
834  * both).  Call with neither to return output to its normal client socket.
835  */
836 void CtdlRedirectOutput(FILE *fp, int sock) {
837
838         if (fp != NULL) CC->redirect_fp = fp;
839         else CC->redirect_fp = NULL;
840
841         if (sock > 0) CC->redirect_sock = sock;
842         else CC->redirect_sock = (-1);
843
844 }
845
846
847 /*
848  * masterCC is the context we use when not attached to a session.  This
849  * function initializes it.
850  */
851 void InitializeMasterCC(void) {
852         memset(&masterCC, 0, sizeof(struct CitContext));
853         masterCC.internal_pgm = 1;
854         masterCC.cs_pid = 0;
855 }
856
857
858
859 /*
860  * Set up a fd_set containing all the master sockets to which we
861  * always listen.  It's computationally less expensive to just copy
862  * this to a local fd_set when starting a new select() and then add
863  * the client sockets than it is to initialize a new one and then
864  * figure out what to put there.
865  */
866 void init_master_fdset(void) {
867         struct ServiceFunctionHook *serviceptr;
868         int m;
869
870         lprintf(CTDL_DEBUG, "Initializing master fdset\n");
871
872         FD_ZERO(&masterfds);
873         masterhighest = 0;
874
875         lprintf(CTDL_DEBUG, "Will listen on rescan pipe %d\n", rescan[0]);
876         FD_SET(rescan[0], &masterfds);
877         if (rescan[0] > masterhighest) masterhighest = rescan[0];
878
879         for (serviceptr = ServiceHookTable; serviceptr != NULL;
880             serviceptr = serviceptr->next ) {
881                 m = serviceptr->msock;
882                 lprintf(CTDL_DEBUG, "Will listen on master socket %d\n", m);
883                 FD_SET(m, &masterfds);
884                 if (m > masterhighest) {
885                         masterhighest = m;
886                 }
887         }
888         lprintf(CTDL_DEBUG, "masterhighest = %d\n", masterhighest);
889 }
890
891
892 /*
893  * Bind a thread to a context.  (It's inline merely to speed things up.)
894  */
895 INLINE void become_session(struct CitContext *which_con) {
896         pthread_setspecific(MyConKey, (void *)which_con );
897 }
898
899
900
901 /* 
902  * This loop just keeps going and going and going...
903  */     
904 void *worker_thread(void *arg) {
905         int i;
906         char junk;
907         int highest;
908         /* This is synchronized below; it helps implement round robin mode */
909         static struct CitContext* next_session = NULL;
910         struct CitContext *ptr;
911         struct CitContext *bind_me = NULL;
912         fd_set readfds;
913         int retval;
914         struct CitContext *con= NULL;   /* Temporary context pointer */
915         struct ServiceFunctionHook *serviceptr;
916         int ssock;                      /* Descriptor for client socket */
917         struct timeval tv;
918         int force_purge = 0;
919
920         num_threads++;
921
922         cdb_allocate_tsd();
923
924         while (!time_to_die) {
925
926                 /* 
927                  * A naive implementation would have all idle threads
928                  * calling select() and then they'd all wake up at once
929                  * (known in computer science as the "thundering herd"
930                  * problem).  We solve this problem by putting the select()
931                  * in a critical section, so only one thread has the
932                  * opportunity to wake up.  If we wake up on a master
933                  * socket, create a new session context; otherwise, just
934                  * bind the thread to the context we want and go on our
935                  * merry way.
936                  */
937
938                 /* make doubly sure we're not holding any stale db handles
939                  * which might cause a deadlock.
940                  */
941                 cdb_check_handles();
942                 force_purge = 0;
943
944                 begin_critical_section(S_I_WANNA_SELECT);
945 SETUP_FD:       memcpy(&readfds, &masterfds, sizeof masterfds);
946                 highest = masterhighest;
947                 begin_critical_section(S_SESSION_TABLE);
948                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
949                         if (ptr->state == CON_IDLE) {
950                                 FD_SET(ptr->client_socket, &readfds);
951                                 if (ptr->client_socket > highest)
952                                         highest = ptr->client_socket;
953                         }
954                 }
955                 end_critical_section(S_SESSION_TABLE);
956
957                 tv.tv_sec = 1;          /* wake up every second if no input */
958                 tv.tv_usec = 0;
959
960                 do_select:
961                 if (!time_to_die)
962                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
963                 else {
964                         end_critical_section(S_I_WANNA_SELECT);
965                         break;
966                 }
967
968                 /* Now figure out who made this select() unblock.
969                  * First, check for an error or exit condition.
970                  */
971                 if (retval < 0) {
972                         if (errno == EBADF) {
973                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
974                                         strerror(errno));
975                                 goto SETUP_FD;
976                         }
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 (time_to_die) {
1033                         end_critical_section(S_I_WANNA_SELECT);
1034                         break;
1035                 }
1036
1037                 /* If the rescan pipe went active, someone is telling this
1038                  * thread that the &readfds needs to be refreshed with more
1039                  * current data.
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                                 force_purge = CC->kill_me;
1091                                 become_session(NULL);
1092                                 bind_me->state = CON_IDLE;
1093                                 write(rescan[1], &junk, 1);
1094                         }
1095
1096                 }
1097                 dead_session_purge(force_purge);
1098                 do_housekeeping();
1099                 check_sched_shutdown();
1100         }
1101
1102         /* If control reaches this point, the server is shutting down */        
1103         --num_threads;
1104         return NULL;
1105 }
1106
1107
1108
1109
1110 /*
1111  * SyslogFacility()
1112  * Translate text facility name to syslog.h defined value.
1113  */
1114 int SyslogFacility(char *name)
1115 {
1116         int i;
1117         struct
1118         {
1119                 int facility;
1120                 char *name;
1121         }   facTbl[] =
1122         {
1123                 {   LOG_KERN,   "kern"          },
1124                 {   LOG_USER,   "user"          },
1125                 {   LOG_MAIL,   "mail"          },
1126                 {   LOG_DAEMON, "daemon"        },
1127                 {   LOG_AUTH,   "auth"          },
1128                 {   LOG_SYSLOG, "syslog"        },
1129                 {   LOG_LPR,    "lpr"           },
1130                 {   LOG_NEWS,   "news"          },
1131                 {   LOG_UUCP,   "uucp"          },
1132                 {   LOG_LOCAL0, "local0"        },
1133                 {   LOG_LOCAL1, "local1"        },
1134                 {   LOG_LOCAL2, "local2"        },
1135                 {   LOG_LOCAL3, "local3"        },
1136                 {   LOG_LOCAL4, "local4"        },
1137                 {   LOG_LOCAL5, "local5"        },
1138                 {   LOG_LOCAL6, "local6"        },
1139                 {   LOG_LOCAL7, "local7"        },
1140                 {   0,            NULL          }
1141         };
1142         for(i = 0; facTbl[i].name != NULL; i++) {
1143                 if(!strcasecmp(name, facTbl[i].name))
1144                         return facTbl[i].facility;
1145         }
1146         return -1;
1147 }
1148
1149
1150 /********** MEM CHEQQER ***********/
1151
1152 #ifdef DEBUG_MEMORY_LEAKS
1153
1154 #undef malloc
1155 #undef realloc
1156 #undef strdup
1157 #undef free
1158
1159 void *tracked_malloc(size_t size, char *file, int line) {
1160         struct igheap *thisheap;
1161         void *block;
1162
1163         block = malloc(size);
1164         if (block == NULL) return(block);
1165
1166         thisheap = malloc(sizeof(struct igheap));
1167         if (thisheap == NULL) {
1168                 free(block);
1169                 return(NULL);
1170         }
1171
1172         thisheap->block = block;
1173         strcpy(thisheap->file, file);
1174         thisheap->line = line;
1175         
1176         begin_critical_section(S_DEBUGMEMLEAKS);
1177         thisheap->next = igheap;
1178         igheap = thisheap;
1179         end_critical_section(S_DEBUGMEMLEAKS);
1180
1181         return(block);
1182 }
1183
1184
1185 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1186         struct igheap *thisheap;
1187         void *block;
1188
1189         block = realloc(ptr, size);
1190         if (block == NULL) return(block);
1191
1192         thisheap = malloc(sizeof(struct igheap));
1193         if (thisheap == NULL) {
1194                 free(block);
1195                 return(NULL);
1196         }
1197
1198         thisheap->block = block;
1199         strcpy(thisheap->file, file);
1200         thisheap->line = line;
1201         
1202         begin_critical_section(S_DEBUGMEMLEAKS);
1203         thisheap->next = igheap;
1204         igheap = thisheap;
1205         end_critical_section(S_DEBUGMEMLEAKS);
1206
1207         return(block);
1208 }
1209
1210
1211
1212 void tracked_free(void *ptr) {
1213         struct igheap *thisheap;
1214         struct igheap *trash;
1215
1216         free(ptr);
1217
1218         if (igheap == NULL) return;
1219         begin_critical_section(S_DEBUGMEMLEAKS);
1220         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1221                 if (thisheap->next != NULL) {
1222                         if (thisheap->next->block == ptr) {
1223                                 trash = thisheap->next;
1224                                 thisheap->next = thisheap->next->next;
1225                                 free(trash);
1226                         }
1227                 }
1228         }
1229         if (igheap->block == ptr) {
1230                 trash = igheap;
1231                 igheap = igheap->next;
1232                 free(trash);
1233         }
1234         end_critical_section(S_DEBUGMEMLEAKS);
1235 }
1236
1237 char *tracked_strdup(const char *s, char *file, int line) {
1238         char *ptr;
1239
1240         if (s == NULL) return(NULL);
1241         ptr = tracked_malloc(strlen(s) + 1, file, line);
1242         if (ptr == NULL) return(NULL);
1243         strncpy(ptr, s, strlen(s));
1244         return(ptr);
1245 }
1246
1247 void dump_heap(void) {
1248         struct igheap *thisheap;
1249
1250         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1251                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1252                         thisheap->file, thisheap->line);
1253         }
1254 }
1255
1256 #endif /*  DEBUG_MEMORY_LEAKS */