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