]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
9c281673539412fc8996b27275bb71ad3c8a7737
[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 /* This is synchronized below; it helps implement round robin mode */
107 extern struct CitContext* next_session;
108
109 /*
110  * lprintf()  ...   Write logging information
111  * 
112  * Note: the variable "buf" below needs to be large enough to handle any
113  * log data sent through this function.  BE CAREFUL!
114  */
115 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
116         va_list arg_ptr;
117         char buf[SIZ];
118  
119         va_start(arg_ptr, format);   
120         vsnprintf(buf, sizeof(buf), format, arg_ptr);   
121         va_end(arg_ptr);   
122
123         if (syslog_facility >= 0) {
124                 if (loglevel <= verbosity) {
125                         /* Hackery -IO */
126                         if (CC && CC->cs_pid) {
127                                 memmove(buf + 6, buf, sizeof(buf) - 6);
128                                 snprintf(buf, 6, "[%3d]", CC->cs_pid);
129                                 buf[5] = ' ';
130                         }
131                         syslog(loglevel, buf);
132                 }
133         }
134         else if (loglevel <= verbosity) { 
135                 struct timeval tv;
136                 struct tm *tim;
137                 time_t unixtime;
138
139                 gettimeofday(&tv, NULL);
140                 /* Promote to time_t; types differ on some OSes (like darwin) */
141                 unixtime = tv.tv_sec;
142                 tim = localtime(&unixtime);
143                 /*
144                  * Log provides millisecond accuracy.  If you need
145                  * microsecond accuracy and your OS supports it, change
146                  * %03ld to %06ld and remove " / 1000" after tv.tv_usec.
147                  */
148                 if (CC && CC->cs_pid) {
149 #if 0
150                         /* Millisecond display */
151                         fprintf(stderr,
152                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%3d] %s",
153                                 tim->tm_year + 1900, tim->tm_mon + 1,
154                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
155                                 tim->tm_sec, (long)tv.tv_usec / 1000,
156                                 CC->cs_pid, buf);
157 #endif
158                         /* Microsecond display */
159                         fprintf(stderr,
160                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] %s",
161                                 tim->tm_year + 1900, tim->tm_mon + 1,
162                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
163                                 tim->tm_sec, (long)tv.tv_usec,
164                                 CC->cs_pid, buf);
165                 } else {
166 #if 0
167                         /* Millisecond display */
168                         fprintf(stderr,
169                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld %s",
170                                 tim->tm_year + 1900, tim->tm_mon + 1,
171                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
172                                 tim->tm_sec, (long)tv.tv_usec / 1000, buf);
173 #endif
174                         /* Microsecond display */
175                         fprintf(stderr,
176                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld %s",
177                                 tim->tm_year + 1900, tim->tm_mon + 1,
178                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
179                                 tim->tm_sec, (long)tv.tv_usec, buf);
180                 }
181                 fflush(stderr);
182         }
183
184         PerformLogHooks(loglevel, buf);
185 }   
186
187
188
189 /*
190  * We used to use master_cleanup() as a signal handler to shut down the server.
191  * however, master_cleanup() and the functions it calls do some things that
192  * aren't such a good idea to do from a signal handler: acquiring mutexes,
193  * playing with signal masks on BSDI systems, etc. so instead we install the
194  * following signal handler to set a global variable to inform the main loop
195  * that it's time to call master_cleanup() and exit.
196  */
197
198 volatile int time_to_die = 0;
199
200 static RETSIGTYPE signal_cleanup(int signum) {
201         time_to_die = 1;
202 }
203
204
205 /*
206  * Some initialization stuff...
207  */
208 void init_sysdep(void) {
209         int a;
210
211 #ifdef HAVE_OPENSSL
212         init_ssl();
213 #endif
214
215         /* Set up a bunch of semaphores to be used for critical sections */
216         for (a=0; a<MAX_SEMAPHORES; ++a) {
217                 pthread_mutex_init(&Critters[a], NULL);
218         }
219
220         /*
221          * Set up a place to put thread-specific data.
222          * We only need a single pointer per thread - it points to the
223          * CitContext structure (in the ContextList linked list) of the
224          * session to which the calling thread is currently bound.
225          */
226         if (pthread_key_create(&MyConKey, NULL) != 0) {
227                 lprintf(CTDL_CRIT, "Can't create TSD key!!  %s\n", strerror(errno));
228         }
229
230         /*
231          * The action for unexpected signals and exceptions should be to
232          * call signal_cleanup() to gracefully shut down the server.
233          */
234         signal(SIGINT, signal_cleanup);
235         signal(SIGQUIT, signal_cleanup);
236         signal(SIGHUP, signal_cleanup);
237         signal(SIGTERM, signal_cleanup);
238
239         /*
240          * Do not shut down the server on broken pipe signals, otherwise the
241          * whole Citadel service would come down whenever a single client
242          * socket breaks.
243          */
244         signal(SIGPIPE, SIG_IGN);
245 }
246
247
248 /*
249  * Obtain a semaphore lock to begin a critical section.
250  */
251 void begin_critical_section(int which_one)
252 {
253         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
254
255         /* For all types of critical sections except those listed here,
256          * ensure nobody ever tries to do a critical section within a
257          * transaction; this could lead to deadlock.
258          */
259         if (    (which_one != S_FLOORCACHE)
260 #ifdef DEBUG_MEMORY_LEAKS
261                 && (which_one != S_DEBUGMEMLEAKS)
262 #endif
263         ) {
264                 cdb_check_handles();
265         }
266         pthread_mutex_lock(&Critters[which_one]);
267 }
268
269 /*
270  * Release a semaphore lock to end a critical section.
271  */
272 void end_critical_section(int which_one)
273 {
274         pthread_mutex_unlock(&Critters[which_one]);
275 }
276
277
278
279 /*
280  * This is a generic function to set up a master socket for listening on
281  * a TCP port.  The server shuts down if the bind fails.
282  *
283  */
284 int ig_tcp_server(int port_number, int queue_len)
285 {
286         struct sockaddr_in sin;
287         int s, i;
288         int actual_queue_len;
289
290         actual_queue_len = queue_len;
291         if (actual_queue_len < 5) actual_queue_len = 5;
292
293         memset(&sin, 0, sizeof(sin));
294         sin.sin_family = AF_INET;
295         sin.sin_addr.s_addr = INADDR_ANY;
296         sin.sin_port = htons((u_short)port_number);
297
298         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
299
300         if (s < 0) {
301                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
302                         strerror(errno));
303                 return(-1);
304         }
305
306         i = 1;
307         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
308
309         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
310                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
311                         strerror(errno));
312                 close(s);
313                 return(-1);
314         }
315
316         if (listen(s, actual_queue_len) < 0) {
317                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
318                 close(s);
319                 return(-1);
320         }
321
322         return(s);
323 }
324
325
326
327 /*
328  * Create a Unix domain socket and listen on it
329  */
330 int ig_uds_server(char *sockpath, int queue_len)
331 {
332         struct sockaddr_un addr;
333         int s;
334         int i;
335         int actual_queue_len;
336
337         actual_queue_len = queue_len;
338         if (actual_queue_len < 5) actual_queue_len = 5;
339
340         i = unlink(sockpath);
341         if (i != 0) if (errno != ENOENT) {
342                 lprintf(CTDL_EMERG, "citserver: can't unlink %s: %s\n",
343                         sockpath, strerror(errno));
344                 return(-1);
345         }
346
347         memset(&addr, 0, sizeof(addr));
348         addr.sun_family = AF_UNIX;
349         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
350
351         s = socket(AF_UNIX, SOCK_STREAM, 0);
352         if (s < 0) {
353                 lprintf(CTDL_EMERG, "citserver: Can't create a socket: %s\n",
354                         strerror(errno));
355                 return(-1);
356         }
357
358         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
359                 lprintf(CTDL_EMERG, "citserver: Can't bind: %s\n",
360                         strerror(errno));
361                 return(-1);
362         }
363
364         if (listen(s, actual_queue_len) < 0) {
365                 lprintf(CTDL_EMERG, "citserver: Can't listen: %s\n", strerror(errno));
366                 return(-1);
367         }
368
369         chmod(sockpath, 0777);
370         return(s);
371 }
372
373
374
375 /*
376  * Return a pointer to the CitContext structure bound to the thread which
377  * called this function.  If there's no such binding (for example, if it's
378  * called by the housekeeper thread) then a generic 'master' CC is returned.
379  *
380  * It's inlined because it's used *VERY* frequently.
381  */
382 INLINE struct CitContext *MyContext(void) {
383         return ((pthread_getspecific(MyConKey) == NULL)
384                 ? &masterCC
385                 : (struct CitContext *) pthread_getspecific(MyConKey)
386         );
387 }
388
389
390 /*
391  * Initialize a new context and place it in the list.  The session number
392  * used to be the PID (which is why it's called cs_pid), but that was when we
393  * had one process per session.  Now we just assign them sequentially, starting
394  * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
395  * sessions terminate.
396  */
397 struct CitContext *CreateNewContext(void) {
398         struct CitContext *me, *ptr;
399
400         me = (struct CitContext *) malloc(sizeof(struct CitContext));
401         if (me == NULL) {
402                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
403                 return NULL;
404         }
405         memset(me, 0, sizeof(struct CitContext));
406
407         /* The new context will be created already in the CON_EXECUTING state
408          * in order to prevent another thread from grabbing it while it's
409          * being set up.
410          */
411         me->state = CON_EXECUTING;
412
413
414         /*
415          * Generate a unique session number and insert this context into
416          * the list.
417          */
418         begin_critical_section(S_SESSION_TABLE);
419
420         if (ContextList == NULL) {
421                 ContextList = me;
422                 me->cs_pid = 1;
423                 me->next = NULL;
424         }
425
426         else if (ContextList->cs_pid > 1) {
427                 me->next = ContextList;
428                 ContextList = me;
429                 me->cs_pid = 1;
430         }
431
432         else {
433                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
434                         if (ptr->next == NULL) {
435                                 ptr->next = me;
436                                 me->cs_pid = ptr->cs_pid + 1;
437                                 me->next = NULL;
438                                 goto DONE;
439                         }
440                         else if (ptr->next->cs_pid > (ptr->cs_pid+1)) {
441                                 me->next = ptr->next;
442                                 ptr->next = me;
443                                 me->cs_pid = ptr->cs_pid + 1;
444                                 goto DONE;
445                         }
446                 }
447         }
448
449 DONE:   ++num_sessions;
450         end_critical_section(S_SESSION_TABLE);
451         return(me);
452 }
453
454
455 /*
456  * buffer_output() ... tell client_write to buffer all output until
457  *                     instructed to dump it all out later
458  */
459 void buffer_output(void) {
460         if (CC->buffering == 0) {
461                 CC->buffering = 1;
462                 CC->buffer_len = 0;
463                 CC->output_buffer = malloc(SIZ);
464         }
465 }
466
467 /*
468  * unbuffer_output()  ...  dump out all that output we've been buffering.
469  */
470 void unbuffer_output(void) {
471         if (CC->buffering == 1) {
472                 CC->buffering = 0;
473                 client_write(CC->output_buffer, CC->buffer_len);
474                 free(CC->output_buffer);
475                 CC->output_buffer = NULL;
476                 CC->buffer_len = 0;
477         }
478 }
479
480
481
482 /*
483  * client_write()   ...    Send binary data to the client.
484  */
485 void client_write(char *buf, int nbytes)
486 {
487         int bytes_written = 0;
488         int retval;
489         int sock;
490         int old_buffer_len = 0;
491
492         if (CC->redirect_fp != NULL) {
493                 fwrite(buf, nbytes, 1, CC->redirect_fp);
494                 return;
495         }
496
497         if (CC->redirect_sock > 0) {
498                 sock = CC->redirect_sock;       /* and continue below... */
499         }
500         else {
501                 sock = CC->client_socket;
502         }
503
504         /* If we're buffering for later, do that now. */
505         if (CC->buffering) {
506                 old_buffer_len = CC->buffer_len;
507                 CC->buffer_len += nbytes;
508                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
509                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
510                 return;
511         }
512
513         /* Ok, at this point we're not buffering.  Go ahead and write. */
514
515 #ifdef HAVE_OPENSSL
516         if (CC->redirect_ssl) {
517                 client_write_ssl(buf, nbytes);
518                 return;
519         }
520 #endif
521
522         while (bytes_written < nbytes) {
523                 retval = write(sock, &buf[bytes_written],
524                         nbytes - bytes_written);
525                 if (retval < 1) {
526                         lprintf(CTDL_ERR, "client_write() failed: %s\n",
527                                 strerror(errno));
528                         if (sock == CC->client_socket) CC->kill_me = 1;
529                         return;
530                 }
531                 bytes_written = bytes_written + retval;
532         }
533 }
534
535
536 /*
537  * cprintf()  ...   Send formatted printable data to the client.   It is
538  *                  implemented in terms of client_write() but remains in
539  *                  sysdep.c in case we port to somewhere without va_args...
540  */
541 void cprintf(const char *format, ...) {   
542         va_list arg_ptr;   
543         char buf[SIZ];   
544    
545         va_start(arg_ptr, format);   
546         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
547                 buf[sizeof buf - 2] = '\n';
548         client_write(buf, strlen(buf)); 
549         va_end(arg_ptr);
550 }   
551
552
553 /*
554  * Read data from the client socket.
555  * Return values are:
556  *      1       Requested number of bytes has been read.
557  *      0       Request timed out.
558  *      -1      The socket is broken.
559  * If the socket breaks, the session will be terminated.
560  */
561 int client_read_to(char *buf, int bytes, int timeout)
562 {
563         int len,rlen;
564         fd_set rfds;
565         struct timeval tv;
566         int retval;
567
568 #ifdef HAVE_OPENSSL
569         if (CC->redirect_ssl) {
570                 return (client_read_ssl(buf, bytes, timeout));
571         }
572 #endif
573         len = 0;
574         while(len<bytes) {
575                 FD_ZERO(&rfds);
576                 FD_SET(CC->client_socket, &rfds);
577                 tv.tv_sec = timeout;
578                 tv.tv_usec = 0;
579
580                 retval = select( (CC->client_socket)+1, 
581                                         &rfds, NULL, NULL, &tv);
582
583                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
584                         return(0);
585                 }
586
587                 rlen = read(CC->client_socket, &buf[len], bytes-len);
588                 if (rlen<1) {
589                         lprintf(CTDL_ERR, "client_read() failed: %s\n",
590                                 strerror(errno));
591                         CC->kill_me = 1;
592                         return(-1);
593                 }
594                 len = len + rlen;
595         }
596         return(1);
597 }
598
599 /*
600  * Read data from the client socket with default timeout.
601  * (This is implemented in terms of client_read_to() and could be
602  * justifiably moved out of sysdep.c)
603  */
604 INLINE int client_read(char *buf, int bytes)
605 {
606         return(client_read_to(buf, bytes, config.c_sleeping));
607 }
608
609
610 /*
611  * client_gets()   ...   Get a LF-terminated line of text from the client.
612  * (This is implemented in terms of client_read() and could be
613  * justifiably moved out of sysdep.c)
614  */
615 int client_gets(char *buf)
616 {
617         int i, retval;
618
619         /* Read one character at a time.
620          */
621         for (i = 0;;i++) {
622                 retval = client_read(&buf[i], 1);
623                 if (retval != 1 || buf[i] == '\n' || i == (SIZ-1))
624                         break;
625         }
626
627         /* If we got a long line, discard characters until the newline.
628          */
629         if (i == (SIZ-1))
630                 while (buf[i] != '\n' && retval == 1)
631                         retval = client_read(&buf[i], 1);
632
633         /* Strip the trailing newline and any trailing nonprintables (cr's)
634          */
635         buf[i] = 0;
636         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
637                 buf[strlen(buf)-1] = 0;
638         if (retval < 0) strcpy(buf, "000");
639         return(retval);
640 }
641
642
643
644 /*
645  * The system-dependent part of master_cleanup() - close the master socket.
646  */
647 void sysdep_master_cleanup(void) {
648         struct ServiceFunctionHook *serviceptr;
649
650         /*
651          * close all protocol master sockets
652          */
653         for (serviceptr = ServiceHookTable; serviceptr != NULL;
654             serviceptr = serviceptr->next ) {
655
656                 if (serviceptr->tcp_port > 0)
657                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
658                                 serviceptr->tcp_port);
659
660                 if (serviceptr->sockpath != NULL)
661                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
662                                 serviceptr->sockpath);
663
664                 close(serviceptr->msock);
665
666                 /* If it's a Unix domain socket, remove the file. */
667                 if (serviceptr->sockpath != NULL) {
668                         unlink(serviceptr->sockpath);
669                 }
670         }
671 }
672
673
674 /*
675  * Terminate another session.
676  * (This could justifiably be moved out of sysdep.c because it
677  * no longer does anything that is system-dependent.)
678  */
679 void kill_session(int session_to_kill) {
680         struct CitContext *ptr;
681
682         begin_critical_section(S_SESSION_TABLE);
683         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
684                 if (ptr->cs_pid == session_to_kill) {
685                         ptr->kill_me = 1;
686                 }
687         }
688         end_critical_section(S_SESSION_TABLE);
689 }
690
691
692
693
694 /*
695  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
696  */
697 void start_daemon(int do_close_stdio) {
698         if (do_close_stdio) {
699                 /* close(0); */
700                 close(1);
701                 close(2);
702         }
703         signal(SIGHUP,SIG_IGN);
704         signal(SIGINT,SIG_IGN);
705         signal(SIGQUIT,SIG_IGN);
706         if (fork()!=0) exit(0);
707 }
708
709
710
711 /*
712  * Generic routine to convert a login name to a full name (gecos)
713  * Returns nonzero if a conversion took place
714  */
715 int convert_login(char NameToConvert[]) {
716         struct passwd *pw;
717         int a;
718
719         pw = getpwnam(NameToConvert);
720         if (pw == NULL) {
721                 return(0);
722         }
723         else {
724                 strcpy(NameToConvert, pw->pw_gecos);
725                 for (a=0; a<strlen(NameToConvert); ++a) {
726                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
727                 }
728                 return(1);
729         }
730 }
731
732 struct worker_node *worker_list = NULL;
733
734
735 /*
736  * create a worker thread. this function must always be called from within
737  * an S_WORKER_LIST critical section!
738  */
739 void create_worker(void) {
740         int ret;
741         struct worker_node *n;
742         pthread_attr_t attr;
743
744         n = malloc(sizeof(struct worker_node));
745         if (n == NULL) {
746                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
747                 time_to_die = -1;
748                 return;
749         }
750
751         if ((ret = pthread_attr_init(&attr))) {
752                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
753                 time_to_die = -1;
754                 return;
755         }
756
757         /* we seem to need something bigger than FreeBSD's default 64k stack */
758
759         if ((ret = pthread_attr_setstacksize(&attr, 128 * 1024))) {
760                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n", strerror(ret));
761                 time_to_die = -1;
762                 return;
763         }
764
765         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
766         {
767
768                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
769                         strerror(ret));
770         }
771
772         n->next = worker_list;
773         worker_list = n;
774 }
775
776
777
778 /*
779  * Purge all sessions which have the 'kill_me' flag set.
780  * This function has code to prevent it from running more than once every
781  * few seconds, because running it after every single unbind would waste a lot
782  * of CPU time and keep the context list locked too much.  To force it to run
783  * anyway, set "force" to nonzero.
784  *
785  *
786  * After that's done, we raise the size of the worker thread pool
787  * if such an action is appropriate.
788  */
789 void dead_session_purge(int force) {
790         struct CitContext *ptr, *rem;
791
792         if (force == 0) {
793                 if ( (time(NULL) - last_purge) < 5 ) {
794                         return; /* Too soon, go away */
795                 }
796         }
797         time(&last_purge);
798
799         do {
800                 rem = NULL;
801                 begin_critical_section(S_SESSION_TABLE);
802                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
803                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
804                                 rem = ptr;
805                         }
806                 }
807                 end_critical_section(S_SESSION_TABLE);
808
809                 /* RemoveContext() enters its own S_SESSION_TABLE critical
810                  * section, so we have to do it like this.
811                  */     
812                 if (rem != NULL) {
813                         lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
814                         RemoveContext(rem);
815                 }
816
817         } while (rem != NULL);
818
819         /* Raise the size of the worker thread pool if necessary. */
820
821         if ( (num_sessions > num_threads)
822            && (num_threads < config.c_max_workers) ) {
823                 begin_critical_section(S_WORKER_LIST);
824                 create_worker();
825                 end_critical_section(S_WORKER_LIST);
826         }
827 }
828
829
830
831
832
833 /*
834  * Redirect a session's output to a file or socket.
835  * This function may be called with a file handle *or* a socket (but not
836  * both).  Call with neither to return output to its normal client socket.
837  */
838 void CtdlRedirectOutput(FILE *fp, int sock) {
839
840         if (fp != NULL) CC->redirect_fp = fp;
841         else CC->redirect_fp = NULL;
842
843         if (sock > 0) CC->redirect_sock = sock;
844         else CC->redirect_sock = (-1);
845
846 }
847
848
849 /*
850  * masterCC is the context we use when not attached to a session.  This
851  * function initializes it.
852  */
853 void InitializeMasterCC(void) {
854         memset(&masterCC, 0, sizeof(struct CitContext));
855         masterCC.internal_pgm = 1;
856         masterCC.cs_pid = 0;
857 }
858
859
860
861 /*
862  * Set up a fd_set containing all the master sockets to which we
863  * always listen.  It's computationally less expensive to just copy
864  * this to a local fd_set when starting a new select() and then add
865  * the client sockets than it is to initialize a new one and then
866  * figure out what to put there.
867  */
868 void init_master_fdset(void) {
869         struct ServiceFunctionHook *serviceptr;
870         int m;
871
872         lprintf(CTDL_DEBUG, "Initializing master fdset\n");
873
874         FD_ZERO(&masterfds);
875         masterhighest = 0;
876
877         lprintf(CTDL_DEBUG, "Will listen on rescan pipe %d\n", rescan[0]);
878         FD_SET(rescan[0], &masterfds);
879         if (rescan[0] > masterhighest) masterhighest = rescan[0];
880
881         for (serviceptr = ServiceHookTable; serviceptr != NULL;
882             serviceptr = serviceptr->next ) {
883                 m = serviceptr->msock;
884                 lprintf(CTDL_DEBUG, "Will listen on master socket %d\n", m);
885                 FD_SET(m, &masterfds);
886                 if (m > masterhighest) {
887                         masterhighest = m;
888                 }
889         }
890         lprintf(CTDL_DEBUG, "masterhighest = %d\n", masterhighest);
891 }
892
893
894 /*
895  * Bind a thread to a context.  (It's inline merely to speed things up.)
896  */
897 INLINE void become_session(struct CitContext *which_con) {
898         pthread_setspecific(MyConKey, (void *)which_con );
899 }
900
901
902
903 /* 
904  * This loop just keeps going and going and going...
905  */     
906 void *worker_thread(void *arg) {
907         int i;
908         char junk;
909         int highest;
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 */