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