]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
* configure.ac: check for <sys/prctl.h>
[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.
781  *
782  * After that's done, we raise or lower the size of the worker thread pool
783  * if such an action is appropriate.
784  */
785 void dead_session_purge(void) {
786         struct CitContext *ptr, *rem;
787
788         if ( (time(NULL) - last_purge) < 5 ) return;    /* Too soon, go away */
789         time(&last_purge);
790
791         do {
792                 rem = NULL;
793                 begin_critical_section(S_SESSION_TABLE);
794                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
795                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
796                                 rem = ptr;
797                         }
798                 }
799                 end_critical_section(S_SESSION_TABLE);
800
801                 /* RemoveContext() enters its own S_SESSION_TABLE critical
802                  * section, so we have to do it like this.
803                  */     
804                 if (rem != NULL) {
805                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
806                         RemoveContext(rem);
807                 }
808
809         } while (rem != NULL);
810
811         /* Raise the size of the worker thread pool if necessary. */
812
813         if ( (num_sessions > num_threads)
814            && (num_threads < config.c_max_workers) ) {
815                 begin_critical_section(S_WORKER_LIST);
816                 create_worker();
817                 end_critical_section(S_WORKER_LIST);
818         }
819 }
820
821
822
823
824
825 /*
826  * Redirect a session's output to a file or socket.
827  * This function may be called with a file handle *or* a socket (but not
828  * both).  Call with neither to return output to its normal client socket.
829  */
830 void CtdlRedirectOutput(FILE *fp, int sock) {
831
832         if (fp != NULL) CC->redirect_fp = fp;
833         else CC->redirect_fp = NULL;
834
835         if (sock > 0) CC->redirect_sock = sock;
836         else CC->redirect_sock = (-1);
837
838 }
839
840
841 /*
842  * masterCC is the context we use when not attached to a session.  This
843  * function initializes it.
844  */
845 void InitializeMasterCC(void) {
846         memset(&masterCC, 0, sizeof(struct CitContext));
847         masterCC.internal_pgm = 1;
848         masterCC.cs_pid = 0;
849 }
850
851
852
853 /*
854  * Set up a fd_set containing all the master sockets to which we
855  * always listen.  It's computationally less expensive to just copy
856  * this to a local fd_set when starting a new select() and then add
857  * the client sockets than it is to initialize a new one and then
858  * figure out what to put there.
859  */
860 void init_master_fdset(void) {
861         struct ServiceFunctionHook *serviceptr;
862         int m;
863
864         lprintf(CTDL_DEBUG, "Initializing master fdset\n");
865
866         FD_ZERO(&masterfds);
867         masterhighest = 0;
868
869         lprintf(CTDL_DEBUG, "Will listen on rescan pipe %d\n", rescan[0]);
870         FD_SET(rescan[0], &masterfds);
871         if (rescan[0] > masterhighest) masterhighest = rescan[0];
872
873         for (serviceptr = ServiceHookTable; serviceptr != NULL;
874             serviceptr = serviceptr->next ) {
875                 m = serviceptr->msock;
876                 lprintf(CTDL_DEBUG, "Will listen on master socket %d\n", m);
877                 FD_SET(m, &masterfds);
878                 if (m > masterhighest) {
879                         masterhighest = m;
880                 }
881         }
882         lprintf(CTDL_DEBUG, "masterhighest = %d\n", masterhighest);
883 }
884
885
886 /*
887  * Bind a thread to a context.  (It's inline merely to speed things up.)
888  */
889 INLINE void become_session(struct CitContext *which_con) {
890         pthread_setspecific(MyConKey, (void *)which_con );
891 }
892
893
894
895 /* 
896  * This loop just keeps going and going and going...
897  */     
898 void *worker_thread(void *arg) {
899         int i;
900         char junk;
901         int highest;
902         /* This is synchronized below; it helps implement round robin mode */
903         static struct CitContext* next_session = NULL;
904         struct CitContext *ptr;
905         struct CitContext *bind_me = NULL;
906         fd_set readfds;
907         int retval;
908         struct CitContext *con= NULL;   /* Temporary context pointer */
909         struct ServiceFunctionHook *serviceptr;
910         int ssock;                      /* Descriptor for client socket */
911         struct timeval tv;
912
913         num_threads++;
914
915         cdb_allocate_tsd();
916
917         while (!time_to_die) {
918
919                 /* 
920                  * A naive implementation would have all idle threads
921                  * calling select() and then they'd all wake up at once
922                  * (known in computer science as the "thundering herd"
923                  * problem).  We solve this problem by putting the select()
924                  * in a critical section, so only one thread has the
925                  * opportunity to wake up.  If we wake up on a master
926                  * socket, create a new session context; otherwise, just
927                  * bind the thread to the context we want and go on our
928                  * merry way.
929                  */
930
931                 /* make doubly sure we're not holding any stale db handles
932                  * which might cause a deadlock.
933                  */
934                 cdb_check_handles();
935
936                 begin_critical_section(S_I_WANNA_SELECT);
937 SETUP_FD:       memcpy(&readfds, &masterfds, sizeof masterfds);
938                 highest = masterhighest;
939                 begin_critical_section(S_SESSION_TABLE);
940                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
941                         if (ptr->state == CON_IDLE) {
942                                 FD_SET(ptr->client_socket, &readfds);
943                                 if (ptr->client_socket > highest)
944                                         highest = ptr->client_socket;
945                         }
946                 }
947                 end_critical_section(S_SESSION_TABLE);
948
949                 tv.tv_sec = 1;          /* wake up every second if no input */
950                 tv.tv_usec = 0;
951
952                 do_select:
953                 if (!time_to_die)
954                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
955                 else {
956                         end_critical_section(S_I_WANNA_SELECT);
957                         break;
958                 }
959
960                 /* Now figure out who made this select() unblock.
961                  * First, check for an error or exit condition.
962                  */
963                 if (retval < 0) {
964                         if (errno != EINTR) {
965                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
966                                 time_to_die = 1;
967                         } else if (!time_to_die)
968                                 goto do_select;
969                 }
970
971                 /* Next, check to see if it's a new client connecting
972                  * on a master socket.
973                  */
974                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
975                      serviceptr = serviceptr->next ) {
976
977                         if (FD_ISSET(serviceptr->msock, &readfds)) {
978                                 ssock = accept(serviceptr->msock, NULL, 0);
979                                 if (ssock < 0) {
980                                         lprintf(CTDL_CRIT,
981                                                 "citserver: accept(): %s\n",
982                                                 strerror(errno));
983                                 }
984                                 else {
985                                         lprintf(CTDL_NOTICE,
986                                                 "New client socket %d\n",
987                                                 ssock);
988
989                                         /* New context will be created already
990                                         * set up in the CON_EXECUTING state.
991                                         */
992                                         con = CreateNewContext();
993
994                                         /* Assign new socket number to it. */
995                                         con->client_socket = ssock;
996                                         con->h_command_function =
997                                                 serviceptr->h_command_function;
998
999                                         /* Determine whether local socket */
1000                                         if (serviceptr->sockpath != NULL)
1001                                                 con->is_local_socket = 1;
1002         
1003                                         /* Set the SO_REUSEADDR socket option */
1004                                         i = 1;
1005                                         setsockopt(ssock, SOL_SOCKET,
1006                                                 SO_REUSEADDR,
1007                                                 &i, sizeof(i));
1008
1009                                         become_session(con);
1010                                         begin_session(con);
1011                                         serviceptr->h_greeting_function();
1012                                         become_session(NULL);
1013                                         con->state = CON_IDLE;
1014                                         goto SETUP_FD;
1015                                 }
1016                         }
1017                 }
1018
1019                 if (time_to_die) {
1020                         end_critical_section(S_I_WANNA_SELECT);
1021                         break;
1022                 }
1023
1024                 /* If the rescan pipe went active, someone is telling this
1025                  * thread that the &readfds needs to be refreshed with more
1026                  * current data.
1027                  */
1028                 if (FD_ISSET(rescan[0], &readfds)) {
1029                         read(rescan[0], &junk, 1);
1030                         goto SETUP_FD;
1031                 }
1032
1033                 /* It must be a client socket.  Find a context that has data
1034                  * waiting on its socket *and* is in the CON_IDLE state.
1035                  */
1036                 else {
1037                         bind_me = NULL;
1038                         begin_critical_section(S_SESSION_TABLE);
1039                         /*
1040                          * We start where we left off.  If we get to the end
1041                          * we'll start from the beginning again, then give up
1042                          * if we still don't find anything.  This ensures
1043                          * that all contexts get a more-or-less equal chance
1044                          * to run. And yes, I did add a goto to the code. -IO
1045                          */
1046 find_session:           if (next_session == NULL)
1047                                 next_session = ContextList;
1048                         for (ptr = next_session;
1049                             ( (ptr != NULL) && (bind_me == NULL) );
1050                             ptr = ptr->next) {
1051                                 if ( (FD_ISSET(ptr->client_socket, &readfds))
1052                                    && (ptr->state == CON_IDLE) ) {
1053                                         bind_me = ptr;
1054                                 }
1055                         }
1056                         if (bind_me != NULL) {
1057                                 /* Found one.  Stake a claim to it before
1058                                  * letting anyone else touch the context list.
1059                                  */
1060                                 bind_me->state = CON_EXECUTING;
1061                                 next_session = bind_me->next;
1062                         } else if (next_session == ContextList) {
1063                                 next_session = NULL;
1064                         }
1065                         if (bind_me == NULL && next_session != NULL) {
1066                                 next_session = NULL;
1067                                 goto find_session;
1068                         }
1069
1070                         end_critical_section(S_SESSION_TABLE);
1071                         end_critical_section(S_I_WANNA_SELECT);
1072
1073                         /* We're bound to a session, now do *one* command */
1074                         if (bind_me != NULL) {
1075                                 become_session(bind_me);
1076                                 CC->h_command_function();
1077                                 become_session(NULL);
1078                                 bind_me->state = CON_IDLE;
1079                                 write(rescan[1], &junk, 1);
1080                         }
1081
1082                 }
1083                 dead_session_purge();
1084                 do_housekeeping();
1085                 check_sched_shutdown();
1086         }
1087
1088         /* If control reaches this point, the server is shutting down */        
1089         --num_threads;
1090         return NULL;
1091 }
1092
1093
1094
1095
1096 /*
1097  * SyslogFacility()
1098  * Translate text facility name to syslog.h defined value.
1099  */
1100 int SyslogFacility(char *name)
1101 {
1102         int i;
1103         struct
1104         {
1105                 int facility;
1106                 char *name;
1107         }   facTbl[] =
1108         {
1109                 {   LOG_KERN,   "kern"          },
1110                 {   LOG_USER,   "user"          },
1111                 {   LOG_MAIL,   "mail"          },
1112                 {   LOG_DAEMON, "daemon"        },
1113                 {   LOG_AUTH,   "auth"          },
1114                 {   LOG_SYSLOG, "syslog"        },
1115                 {   LOG_LPR,    "lpr"           },
1116                 {   LOG_NEWS,   "news"          },
1117                 {   LOG_UUCP,   "uucp"          },
1118                 {   LOG_LOCAL0, "local0"        },
1119                 {   LOG_LOCAL1, "local1"        },
1120                 {   LOG_LOCAL2, "local2"        },
1121                 {   LOG_LOCAL3, "local3"        },
1122                 {   LOG_LOCAL4, "local4"        },
1123                 {   LOG_LOCAL5, "local5"        },
1124                 {   LOG_LOCAL6, "local6"        },
1125                 {   LOG_LOCAL7, "local7"        },
1126                 {   0,            NULL          }
1127         };
1128         for(i = 0; facTbl[i].name != NULL; i++) {
1129                 if(!strcasecmp(name, facTbl[i].name))
1130                         return facTbl[i].facility;
1131         }
1132         return -1;
1133 }
1134
1135
1136 /********** MEM CHEQQER ***********/
1137
1138 #ifdef DEBUG_MEMORY_LEAKS
1139
1140 #undef malloc
1141 #undef realloc
1142 #undef strdup
1143 #undef free
1144
1145 void *tracked_malloc(size_t size, char *file, int line) {
1146         struct igheap *thisheap;
1147         void *block;
1148
1149         block = malloc(size);
1150         if (block == NULL) return(block);
1151
1152         thisheap = malloc(sizeof(struct igheap));
1153         if (thisheap == NULL) {
1154                 free(block);
1155                 return(NULL);
1156         }
1157
1158         thisheap->block = block;
1159         strcpy(thisheap->file, file);
1160         thisheap->line = line;
1161         
1162         begin_critical_section(S_DEBUGMEMLEAKS);
1163         thisheap->next = igheap;
1164         igheap = thisheap;
1165         end_critical_section(S_DEBUGMEMLEAKS);
1166
1167         return(block);
1168 }
1169
1170
1171 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1172         struct igheap *thisheap;
1173         void *block;
1174
1175         block = realloc(ptr, size);
1176         if (block == NULL) return(block);
1177
1178         thisheap = malloc(sizeof(struct igheap));
1179         if (thisheap == NULL) {
1180                 free(block);
1181                 return(NULL);
1182         }
1183
1184         thisheap->block = block;
1185         strcpy(thisheap->file, file);
1186         thisheap->line = line;
1187         
1188         begin_critical_section(S_DEBUGMEMLEAKS);
1189         thisheap->next = igheap;
1190         igheap = thisheap;
1191         end_critical_section(S_DEBUGMEMLEAKS);
1192
1193         return(block);
1194 }
1195
1196
1197
1198 void tracked_free(void *ptr) {
1199         struct igheap *thisheap;
1200         struct igheap *trash;
1201
1202         free(ptr);
1203
1204         if (igheap == NULL) return;
1205         begin_critical_section(S_DEBUGMEMLEAKS);
1206         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1207                 if (thisheap->next != NULL) {
1208                         if (thisheap->next->block == ptr) {
1209                                 trash = thisheap->next;
1210                                 thisheap->next = thisheap->next->next;
1211                                 free(trash);
1212                         }
1213                 }
1214         }
1215         if (igheap->block == ptr) {
1216                 trash = igheap;
1217                 igheap = igheap->next;
1218                 free(trash);
1219         }
1220         end_critical_section(S_DEBUGMEMLEAKS);
1221 }
1222
1223 char *tracked_strdup(const char *s, char *file, int line) {
1224         char *ptr;
1225
1226         if (s == NULL) return(NULL);
1227         ptr = tracked_malloc(strlen(s) + 1, file, line);
1228         if (ptr == NULL) return(NULL);
1229         strncpy(ptr, s, strlen(s));
1230         return(ptr);
1231 }
1232
1233 void dump_heap(void) {
1234         struct igheap *thisheap;
1235
1236         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1237                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1238                         thisheap->file, thisheap->line);
1239         }
1240 }
1241
1242 #endif /*  DEBUG_MEMORY_LEAKS */