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