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