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