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