]> code.citadel.org Git - citadel.git/blob - citadel/sysdep.c
b819acca7eb459af80bbe63e8a10ece9ed837375
[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 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 #include <sys/socket.h>
26 #include <syslog.h>
27 #include <sys/syslog.h>
28
29 #if TIME_WITH_SYS_TIME
30 # include <sys/time.h>
31 # include <time.h>
32 #else
33 # if HAVE_SYS_TIME_H
34 #  include <sys/time.h>
35 # else
36 #  include <time.h>
37 # endif
38 #endif
39
40 #include <limits.h>
41 #include <sys/resource.h>
42 #include <netinet/in.h>
43 #include <netinet/tcp.h>
44 #include <arpa/inet.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 "sysdep_decls.h"
58 #include "citserver.h"
59 #include "support.h"
60 #include "config.h"
61 #include "database.h"
62 #include "housekeeping.h"
63 #include "tools.h"
64 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
65
66 #ifdef HAVE_SYS_SELECT_H
67 #include <sys/select.h>
68 #endif
69
70 #ifndef HAVE_SNPRINTF
71 #include "snprintf.h"
72 #endif
73
74
75 #ifdef DEBUG_MEMORY_LEAKS
76 struct igheap {
77         struct igheap *next;
78         char file[32];
79         int line;
80         void *block;
81 };
82
83 struct igheap *igheap = NULL;
84 #endif
85
86
87 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
88 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
89
90 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
91
92 struct CitContext masterCC;
93 time_t last_purge = 0;                          /* Last dead session purge */
94 static int num_threads = 0;                     /* Current number of threads */
95 int num_sessions = 0;                           /* Current number of sessions */
96
97 int syslog_facility = LOG_DAEMON;
98 int enable_syslog = 0;
99
100 void DestroyWorkerList(void);
101
102 /*
103  * lprintf()  ...   Write logging information
104  */
105 void lprintf(enum LogLevel loglevel, const char *format, ...) {   
106         va_list arg_ptr;
107
108         if (enable_syslog) {
109                 va_start(arg_ptr, format);
110                         vsyslog((syslog_facility | loglevel), format, arg_ptr);
111                 va_end(arg_ptr);
112         }
113
114         /* stderr output code */
115         if (enable_syslog || running_as_daemon) return;
116
117         /* if we run in forground and syslog is disabled, log to terminal */
118         if (loglevel <= verbosity) { 
119                 struct timeval tv;
120                 struct tm tim;
121                 time_t unixtime;
122
123                 gettimeofday(&tv, NULL);
124                 /* Promote to time_t; types differ on some OSes (like darwin) */
125                 unixtime = tv.tv_sec;
126                 localtime_r(&unixtime, &tim);
127                 if (CC->cs_pid != 0) {
128                         fprintf(stderr,
129                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld [%3d] ",
130                                 tim.tm_year + 1900, tim.tm_mon + 1,
131                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
132                                 tim.tm_sec, (long)tv.tv_usec,
133                                 CC->cs_pid);
134                 } else {
135                         fprintf(stderr,
136                                 "%04d/%02d/%02d %2d:%02d:%02d.%06ld ",
137                                 tim.tm_year + 1900, tim.tm_mon + 1,
138                                 tim.tm_mday, tim.tm_hour, tim.tm_min,
139                                 tim.tm_sec, (long)tv.tv_usec);
140                 }
141                 va_start(arg_ptr, format);   
142                         vfprintf(stderr, format, arg_ptr);   
143                 va_end(arg_ptr);   
144                 fflush(stderr);
145         }
146 }   
147
148
149
150 /*
151  * Signal handler to shut down the server.
152  */
153
154 volatile int time_to_die = 0;
155 volatile int shutdown_and_halt = 0;
156 volatile int restart_server = 0;
157 volatile int running_as_daemon = 0;
158
159 static RETSIGTYPE signal_cleanup(int signum) {
160         lprintf(CTDL_DEBUG, "Caught signal %d; shutting down.\n", signum);
161         time_to_die = 1;
162         master_cleanup(signum);
163 }
164
165 /*
166  * Some initialization stuff...
167  */
168 void init_sysdep(void) {
169         int i;
170         sigset_t set;
171
172         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
173 #ifdef FD_SETSIZE
174 #ifdef RLIMIT_NOFILE
175         struct rlimit rl;
176         getrlimit(RLIMIT_NOFILE, &rl);
177         rl.rlim_cur = FD_SETSIZE;
178         rl.rlim_max = FD_SETSIZE;
179         setrlimit(RLIMIT_NOFILE, &rl);
180 #endif
181 #endif
182
183         /* If we've got OpenSSL, we're going to use it. */
184 #ifdef HAVE_OPENSSL
185         init_ssl();
186 #endif
187
188         /* Set up a bunch of semaphores to be used for critical sections */
189         for (i=0; i<MAX_SEMAPHORES; ++i) {
190                 pthread_mutex_init(&Critters[i], NULL);
191         }
192
193         /*
194          * Set up a place to put thread-specific data.
195          * We only need a single pointer per thread - it points to the
196          * CitContext structure (in the ContextList linked list) of the
197          * session to which the calling thread is currently bound.
198          */
199         if (pthread_key_create(&MyConKey, NULL) != 0) {
200                 lprintf(CTDL_CRIT, "Can't create TSD key: %s\n",
201                         strerror(errno));
202         }
203
204         /*
205          * The action for unexpected signals and exceptions should be to
206          * call signal_cleanup() to gracefully shut down the server.
207          */
208         sigemptyset(&set);
209         sigaddset(&set, SIGINT);
210         sigaddset(&set, SIGQUIT);
211         sigaddset(&set, SIGHUP);
212         sigaddset(&set, SIGTERM);
213         // sigaddset(&set, SIGSEGV);    commented out because
214         // sigaddset(&set, SIGILL);     we want core dumps
215         // sigaddset(&set, SIGBUS);
216         sigprocmask(SIG_UNBLOCK, &set, NULL);
217
218         signal(SIGINT, signal_cleanup);
219         signal(SIGQUIT, signal_cleanup);
220         signal(SIGHUP, signal_cleanup);
221         signal(SIGTERM, signal_cleanup);
222         // signal(SIGSEGV, signal_cleanup);     commented out because
223         // signal(SIGILL, signal_cleanup);      we want core dumps
224         // signal(SIGBUS, signal_cleanup);
225
226         /*
227          * Do not shut down the server on broken pipe signals, otherwise the
228          * whole Citadel service would come down whenever a single client
229          * socket breaks.
230          */
231         signal(SIGPIPE, SIG_IGN);
232 }
233
234
235 /*
236  * Obtain a semaphore lock to begin a critical section.
237  */
238 void begin_critical_section(int which_one)
239 {
240         /* lprintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
241
242         /* For all types of critical sections except those listed here,
243          * ensure nobody ever tries to do a critical section within a
244          * transaction; this could lead to deadlock.
245          */
246         if (    (which_one != S_FLOORCACHE)
247 #ifdef DEBUG_MEMORY_LEAKS
248                 && (which_one != S_DEBUGMEMLEAKS)
249 #endif
250                 && (which_one != S_RPLIST)
251         ) {
252                 cdb_check_handles();
253         }
254         pthread_mutex_lock(&Critters[which_one]);
255 }
256
257 /*
258  * Release a semaphore lock to end a critical section.
259  */
260 void end_critical_section(int which_one)
261 {
262         pthread_mutex_unlock(&Critters[which_one]);
263 }
264
265
266
267 /*
268  * This is a generic function to set up a master socket for listening on
269  * a TCP port.  The server shuts down if the bind fails.
270  *
271  */
272 int ig_tcp_server(char *ip_addr, int port_number, int queue_len, char **errormessage)
273 {
274         struct sockaddr_in sin;
275         int s, i;
276         int actual_queue_len;
277
278         actual_queue_len = queue_len;
279         if (actual_queue_len < 5) actual_queue_len = 5;
280
281         memset(&sin, 0, sizeof(sin));
282         sin.sin_family = AF_INET;
283         sin.sin_port = htons((u_short)port_number);
284         if (ip_addr == NULL) {
285                 sin.sin_addr.s_addr = INADDR_ANY;
286         }
287         else {
288                 sin.sin_addr.s_addr = inet_addr(ip_addr);
289         }
290                                                                                 
291         if (sin.sin_addr.s_addr == !INADDR_ANY) {
292                 sin.sin_addr.s_addr = INADDR_ANY;
293         }
294
295         s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
296
297         if (s < 0) {
298                 *errormessage = (char*) malloc(SIZ + 1);
299                 snprintf(*errormessage, SIZ, 
300                                  "citserver: Can't create a socket: %s",
301                                  strerror(errno));
302                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
303                 return(-1);
304         }
305
306         i = 1;
307         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
308
309         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
310                 *errormessage = (char*) malloc(SIZ + 1);
311                 snprintf(*errormessage, SIZ, 
312                                  "citserver: Can't bind: %s",
313                                  strerror(errno));
314                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
315                 close(s);
316                 return(-1);
317         }
318
319         /* set to nonblock - we need this for some obscure situations */
320         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
321                 *errormessage = (char*) malloc(SIZ + 1);
322                 snprintf(*errormessage, SIZ, 
323                                  "citserver: Can't set socket to non-blocking: %s",
324                                  strerror(errno));
325                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
326                 close(s);
327                 return(-1);
328         }
329
330         if (listen(s, actual_queue_len) < 0) {
331                 *errormessage = (char*) malloc(SIZ + 1);
332                 snprintf(*errormessage, SIZ, 
333                                  "citserver: Can't listen: %s",
334                                  strerror(errno));
335                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
336                 close(s);
337                 return(-1);
338         }
339
340         return(s);
341 }
342
343
344
345 /*
346  * Create a Unix domain socket and listen on it
347  */
348 int ig_uds_server(char *sockpath, int queue_len, char **errormessage)
349 {
350         struct sockaddr_un addr;
351         int s;
352         int i;
353         int actual_queue_len;
354
355         actual_queue_len = queue_len;
356         if (actual_queue_len < 5) actual_queue_len = 5;
357
358         i = unlink(sockpath);
359         if (i != 0) if (errno != ENOENT) {
360                 *errormessage = (char*) malloc(SIZ + 1);
361                 snprintf(*errormessage, SIZ, "citserver: can't unlink %s: %s",
362                         sockpath, strerror(errno));
363                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
364                 return(-1);
365         }
366
367         memset(&addr, 0, sizeof(addr));
368         addr.sun_family = AF_UNIX;
369         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
370
371         s = socket(AF_UNIX, SOCK_STREAM, 0);
372         if (s < 0) {
373                 *errormessage = (char*) malloc(SIZ + 1);
374                 snprintf(*errormessage, SIZ, 
375                          "citserver: Can't create a socket: %s",
376                          strerror(errno));
377                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
378                 return(-1);
379         }
380
381         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
382                 *errormessage = (char*) malloc(SIZ + 1);
383                 snprintf(*errormessage, SIZ, 
384                          "citserver: Can't bind: %s",
385                          strerror(errno));
386                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
387                 return(-1);
388         }
389
390         /* set to nonblock - we need this for some obscure situations */
391         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
392                 *errormessage = (char*) malloc(SIZ + 1);
393                 snprintf(*errormessage, SIZ, 
394                          "citserver: Can't set socket to non-blocking: %s",
395                          strerror(errno));
396                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
397                 close(s);
398                 return(-1);
399         }
400
401         if (listen(s, actual_queue_len) < 0) {
402                 *errormessage = (char*) malloc(SIZ + 1);
403                 snprintf(*errormessage, SIZ, 
404                          "citserver: Can't listen: %s",
405                          strerror(errno));
406                 lprintf(CTDL_EMERG, "%s\n", *errormessage);
407                 return(-1);
408         }
409
410         chmod(sockpath, 0777);
411         return(s);
412 }
413
414
415
416 /*
417  * Return a pointer to the CitContext structure bound to the thread which
418  * called this function.  If there's no such binding (for example, if it's
419  * called by the housekeeper thread) then a generic 'master' CC is returned.
420  *
421  * This function is used *VERY* frequently and must be kept small.
422  */
423 struct CitContext *MyContext(void) {
424
425         register struct CitContext *c;
426
427         return ((c = (struct CitContext *) pthread_getspecific(MyConKey),
428                 c == NULL) ? &masterCC : c
429         );
430 }
431
432
433 /*
434  * Initialize a new context and place it in the list.  The session number
435  * used to be the PID (which is why it's called cs_pid), but that was when we
436  * had one process per session.  Now we just assign them sequentially, starting
437  * at 1 (don't change it to 0 because masterCC uses 0).
438  */
439 struct CitContext *CreateNewContext(void) {
440         struct CitContext *me;
441         static int next_pid = 0;
442
443         me = (struct CitContext *) malloc(sizeof(struct CitContext));
444         if (me == NULL) {
445                 lprintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
446                 return NULL;
447         }
448         memset(me, 0, sizeof(struct CitContext));
449
450         /* The new context will be created already in the CON_EXECUTING state
451          * in order to prevent another thread from grabbing it while it's
452          * being set up.
453          */
454         me->state = CON_EXECUTING;
455
456         /*
457          * Generate a unique session number and insert this context into
458          * the list.
459          */
460         begin_critical_section(S_SESSION_TABLE);
461         me->cs_pid = ++next_pid;
462         me->prev = NULL;
463         me->next = ContextList;
464         ContextList = me;
465         if (me->next != NULL) {
466                 me->next->prev = me;
467         }
468         ++num_sessions;
469         end_critical_section(S_SESSION_TABLE);
470         return(me);
471 }
472
473
474 /*
475  * The following functions implement output buffering. If the kernel supplies
476  * native TCP buffering (Linux & *BSD), use that; otherwise, emulate it with
477  * user-space buffering.
478  */
479 #ifndef HAVE_DARWIN
480 #ifdef TCP_CORK
481 #       define HAVE_TCP_BUFFERING
482 #else
483 #       ifdef TCP_NOPUSH
484 #               define HAVE_TCP_BUFFERING
485 #               define TCP_CORK TCP_NOPUSH
486 #       endif
487 #endif /* TCP_CORK */
488 #endif /* HAVE_DARWIN */
489
490 #ifdef HAVE_TCP_BUFFERING
491 static unsigned on = 1, off = 0;
492 void buffer_output(void) {
493         struct CitContext *ctx = MyContext();
494         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
495         ctx->buffering = 1;
496 }
497
498 void unbuffer_output(void) {
499         struct CitContext *ctx = MyContext();
500         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
501         ctx->buffering = 0;
502 }
503
504 void flush_output(void) {
505         struct CitContext *ctx = MyContext();
506         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
507         setsockopt(ctx->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
508 }
509 #else 
510 #ifdef HAVE_DARWIN
511 /* Stub functions for Darwin/OS X where TCP buffering isn't liked at all */
512 void buffer_output(void) {
513         CC->buffering = 0;
514 }
515 void unbuffer_output(void) {
516         CC->buffering = 0;
517 }
518 void flush_output(void) {
519 }
520 #else
521 void buffer_output(void) {
522         if (CC->buffering == 0) {
523                 CC->buffering = 1;
524                 CC->buffer_len = 0;
525                 CC->output_buffer = malloc(SIZ);
526         }
527 }
528
529 void flush_output(void) {
530         if (CC->buffering == 1) {
531                 client_write(CC->output_buffer, CC->buffer_len);
532                 CC->buffer_len = 0;
533         }
534 }
535
536 void unbuffer_output(void) {
537         if (CC->buffering == 1) {
538                 CC->buffering = 0;
539                 /* We don't call flush_output because we can't. */
540                 client_write(CC->output_buffer, CC->buffer_len);
541                 CC->buffer_len = 0;
542                 free(CC->output_buffer);
543                 CC->output_buffer = NULL;
544         }
545 }
546 #endif /* HAVE_DARWIN */
547 #endif /* HAVE_TCP_BUFFERING */
548
549
550
551 /*
552  * client_write()   ...    Send binary data to the client.
553  */
554 void client_write(char *buf, int nbytes)
555 {
556         int bytes_written = 0;
557         int retval;
558 #ifndef HAVE_TCP_BUFFERING
559         int old_buffer_len = 0;
560 #endif
561
562         if (CC->redirect_buffer != NULL) {
563                 if ((CC->redirect_len + nbytes + 2) >= CC->redirect_alloc) {
564                         CC->redirect_alloc = (CC->redirect_alloc * 2) + nbytes;
565                         CC->redirect_buffer = realloc(CC->redirect_buffer,
566                                                 CC->redirect_alloc);
567                 }
568                 memcpy(&CC->redirect_buffer[CC->redirect_len], buf, nbytes);
569                 CC->redirect_len += nbytes;
570                 CC->redirect_buffer[CC->redirect_len] = 0;
571                 return;
572         }
573
574 #ifndef HAVE_TCP_BUFFERING
575         /* If we're buffering for later, do that now. */
576         if (CC->buffering) {
577                 old_buffer_len = CC->buffer_len;
578                 CC->buffer_len += nbytes;
579                 CC->output_buffer = realloc(CC->output_buffer, CC->buffer_len);
580                 memcpy(&CC->output_buffer[old_buffer_len], buf, nbytes);
581                 return;
582         }
583 #endif
584
585         /* Ok, at this point we're not buffering.  Go ahead and write. */
586
587 #ifdef HAVE_OPENSSL
588         if (CC->redirect_ssl) {
589                 client_write_ssl(buf, nbytes);
590                 return;
591         }
592 #endif
593
594         while (bytes_written < nbytes) {
595                 retval = write(CC->client_socket, &buf[bytes_written],
596                         nbytes - bytes_written);
597                 if (retval < 1) {
598                         lprintf(CTDL_ERR,
599                                 "client_write(%d bytes) failed: %s (%d)\n",
600                                 nbytes - bytes_written,
601                                 strerror(errno), errno);
602                         CC->kill_me = 1;
603                         return;
604                 }
605                 bytes_written = bytes_written + retval;
606         }
607 }
608
609
610 /*
611  * cprintf()  ...   Send formatted printable data to the client.   It is
612  *                implemented in terms of client_write() but remains in
613  *                sysdep.c in case we port to somewhere without va_args...
614  */
615 void cprintf(const char *format, ...) {   
616         va_list arg_ptr;   
617         char buf[1024];   
618    
619         va_start(arg_ptr, format);   
620         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
621                 buf[sizeof buf - 2] = '\n';
622         client_write(buf, strlen(buf)); 
623         va_end(arg_ptr);
624 }   
625
626
627 /*
628  * Read data from the client socket.
629  * Return values are:
630  *      1       Requested number of bytes has been read.
631  *      0       Request timed out.
632  *      -1      The socket is broken.
633  * If the socket breaks, the session will be terminated.
634  */
635 int client_read_to(char *buf, int bytes, int timeout)
636 {
637         int len,rlen;
638         fd_set rfds;
639         struct timeval tv;
640         int retval;
641
642 #ifdef HAVE_OPENSSL
643         if (CC->redirect_ssl) {
644                 return (client_read_ssl(buf, bytes, timeout));
645         }
646 #endif
647         len = 0;
648         while(len<bytes) {
649                 FD_ZERO(&rfds);
650                 FD_SET(CC->client_socket, &rfds);
651                 tv.tv_sec = timeout;
652                 tv.tv_usec = 0;
653
654                 retval = select( (CC->client_socket)+1, 
655                                         &rfds, NULL, NULL, &tv);
656
657                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
658                         return(0);
659                 }
660
661                 rlen = read(CC->client_socket, &buf[len], bytes-len);
662                 if (rlen<1) {
663                         /* The socket has been disconnected! */
664                         CC->kill_me = 1;
665                         return(-1);
666                 }
667                 len = len + rlen;
668         }
669         return(1);
670 }
671
672 /*
673  * Read data from the client socket with default timeout.
674  * (This is implemented in terms of client_read_to() and could be
675  * justifiably moved out of sysdep.c)
676  */
677 INLINE int client_read(char *buf, int bytes)
678 {
679         return(client_read_to(buf, bytes, config.c_sleeping));
680 }
681
682
683 /*
684  * client_getln()   ...   Get a LF-terminated line of text from the client.
685  * (This is implemented in terms of client_read() and could be
686  * justifiably moved out of sysdep.c)
687  */
688 int client_getln(char *buf, int bufsize)
689 {
690         int i, retval;
691
692         /* Read one character at a time.
693          */
694         for (i = 0;;i++) {
695                 retval = client_read(&buf[i], 1);
696                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
697                         break;
698         }
699
700         /* If we got a long line, discard characters until the newline.
701          */
702         if (i == (bufsize-1))
703                 while (buf[i] != '\n' && retval == 1)
704                         retval = client_read(&buf[i], 1);
705
706         /* Strip the trailing LF, and the trailing CR if present.
707          */
708         buf[i] = 0;
709         while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
710                 buf[strlen(buf)-1] = 0;
711         }
712         if (retval < 0) safestrncpy(buf, "000", bufsize);
713         return(retval);
714 }
715
716
717
718 /*
719  * The system-dependent part of master_cleanup() - close the master socket.
720  */
721 void sysdep_master_cleanup(void) {
722         struct ServiceFunctionHook *serviceptr;
723
724 /////   DestroyWorkerList();
725         /*
726          * close all protocol master sockets
727          */
728         for (serviceptr = ServiceHookTable; serviceptr != NULL;
729             serviceptr = serviceptr->next ) {
730
731                 if (serviceptr->tcp_port > 0)
732                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
733                                 serviceptr->tcp_port);
734
735                 if (serviceptr->sockpath != NULL)
736                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
737                                 serviceptr->sockpath);
738
739                 close(serviceptr->msock);
740
741                 /* If it's a Unix domain socket, remove the file. */
742                 if (serviceptr->sockpath != NULL) {
743                         unlink(serviceptr->sockpath);
744                 }
745         }
746 #ifdef HAVE_OPENSSL
747         destruct_ssl();
748 #endif
749         serv_calendar_destroy();
750         CtdlDestroyProtoHooks();
751         CtdlDestroyDeleteHooks();
752         CtdlDestroyXmsgHooks();
753         CtdlDestroyNetprocHooks();
754         CtdlDestroyUserHooks();
755         CtdlDestroyMessageHook();
756         CtdlDestroyCleanupHooks();
757         CtdlDestroyFixedOutputHooks();  
758         CtdlDestroySessionHooks();
759         CtdlDestroyServiceHook();
760 }
761
762
763
764
765 /*
766  * Terminate another session.
767  * (This could justifiably be moved out of sysdep.c because it
768  * no longer does anything that is system-dependent.)
769  */
770 void kill_session(int session_to_kill) {
771         struct CitContext *ptr;
772
773         begin_critical_section(S_SESSION_TABLE);
774         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
775                 if (ptr->cs_pid == session_to_kill) {
776                         ptr->kill_me = 1;
777                 }
778         }
779         end_critical_section(S_SESSION_TABLE);
780 }
781
782 pid_t current_child;
783 void graceful_shutdown(int signum) {
784         kill(current_child, signum);
785         unlink(file_pid_file);
786         exit(0);
787 }
788
789
790 /*
791  * Start running as a daemon.
792  */
793 void start_daemon(int unused) {
794         int status = 0;
795         pid_t child = 0;
796         FILE *fp;
797         int do_restart = 0;
798
799         current_child = 0;
800
801         /* Close stdin/stdout/stderr and replace them with /dev/null.
802          * We don't just call close() because we don't want these fd's
803          * to be reused for other files.
804          */
805         chdir(ctdl_run_dir);
806
807         child = fork();
808         if (child != 0) {
809                 exit(0);
810         }
811         
812         signal(SIGHUP, SIG_IGN);
813         signal(SIGINT, SIG_IGN);
814         signal(SIGQUIT, SIG_IGN);
815
816         setsid();
817         umask(0);
818         freopen("/dev/null", "r", stdin);
819         freopen("/dev/null", "w", stdout);
820         freopen("/dev/null", "w", stderr);
821
822         do {
823                 current_child = fork();
824
825                 signal(SIGTERM, graceful_shutdown);
826         
827                 if (current_child < 0) {
828                         perror("fork");
829                         exit(errno);
830                 }
831         
832                 else if (current_child == 0) {
833                         return; /* continue starting citadel. */
834                 }
835         
836                 else {
837                         fp = fopen(file_pid_file, "w");
838                         if (fp != NULL) {
839                                 fprintf(fp, ""F_PID_T"\n", child);
840                                 fclose(fp);
841                         }
842                         waitpid(current_child, &status, 0);
843                 }
844
845                 do_restart = 0;
846
847                 /* Did the main process exit with an actual exit code? */
848                 if (WIFEXITED(status)) {
849
850                         /* Exit code 0 means the watcher should exit */
851                         if (WEXITSTATUS(status) == 0) {
852                                 do_restart = 0;
853                         }
854
855                         /* Exit code 101-109 means the watcher should exit */
856                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
857                                 do_restart = 0;
858                         }
859
860                         /* Any other exit code means we should restart. */
861                         else {
862                                 do_restart = 1;
863                         }
864                 }
865
866                 /* Any other type of termination (signals, etc.) should also restart. */
867                 else {
868                         do_restart = 1;
869                 }
870
871         } while (do_restart);
872
873         unlink(file_pid_file);
874         exit(WEXITSTATUS(status));
875 }
876
877
878
879 /*
880  * Generic routine to convert a login name to a full name (gecos)
881  * Returns nonzero if a conversion took place
882  */
883 int convert_login(char NameToConvert[]) {
884         struct passwd *pw;
885         int a;
886
887         pw = getpwnam(NameToConvert);
888         if (pw == NULL) {
889                 return(0);
890         }
891         else {
892                 strcpy(NameToConvert, pw->pw_gecos);
893                 for (a=0; a<strlen(NameToConvert); ++a) {
894                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
895                 }
896                 return(1);
897         }
898 }
899
900 struct worker_node *worker_list = NULL;
901
902
903 /*
904  * create a worker thread. this function must always be called from within
905  * an S_WORKER_LIST critical section!
906  */
907 void create_worker(void) {
908         int ret;
909         struct worker_node *n;
910         pthread_attr_t attr;
911
912         n = malloc(sizeof(struct worker_node));
913         if (n == NULL) {
914                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
915                 time_to_die = -1;
916                 return;
917         }
918
919         if ((ret = pthread_attr_init(&attr))) {
920                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
921                 time_to_die = -1;
922                 return;
923         }
924
925         /* Our per-thread stacks need to be bigger than the default size,
926          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
927          * crashes on 64-bit Linux.
928          */
929         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
930                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
931                         strerror(ret));
932                 time_to_die = -1;
933                 pthread_attr_destroy(&attr);
934                 return;
935         }
936
937         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
938         {
939
940                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
941                         strerror(ret));
942         }
943
944         n->next = worker_list;
945         worker_list = n;
946         pthread_attr_destroy(&attr);
947 }
948
949 void DestroyWorkerList(void)
950 {
951         struct CitContext *ptr;         /* general-purpose utility pointer */
952         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
953
954         begin_critical_section(S_SESSION_TABLE);
955         ptr = ContextList;
956         while (ptr != NULL){
957                 /* Remove the session from the active list */
958                 rem = ptr->next;
959                 --num_sessions;
960                 
961                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
962                 end_critical_section(S_SESSION_TABLE);
963                 RemoveContext(ptr);
964                 begin_critical_section(S_SESSION_TABLE);
965                 free (ptr);
966                 ptr = rem;
967         }
968         end_critical_section(S_SESSION_TABLE);
969
970         struct worker_node *cur, *p;
971         cur = worker_list;
972         while (cur != NULL)
973         {
974                 p = cur->next;
975                 free (cur);
976                 cur = p;
977         }
978         worker_list = NULL;
979 }
980
981 /*
982  * Create the maintenance threads and begin their operation.
983  */
984 void create_maintenance_threads(void) {
985         int ret;
986         pthread_attr_t attr;
987
988         if ((ret = pthread_attr_init(&attr))) {
989                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
990                 time_to_die = -1;
991                 return;
992         }
993
994         /* Our per-thread stacks need to be bigger than the default size,
995          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
996          * crashes on 64-bit Linux.
997          */
998         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
999                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1000                         strerror(ret));
1001                 time_to_die = -1;
1002                 pthread_attr_destroy(&attr);
1003                 return;
1004         }
1005         
1006         struct MaintenanceThreadHook *fcn;
1007
1008         lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1009
1010         for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1011                 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1012                         lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1013                 }
1014                 else
1015                 {
1016                         lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1017                                 fcn->MaintenanceThread_tid);
1018                 }
1019         }
1020
1021
1022         pthread_attr_destroy(&attr);
1023 }
1024
1025
1026
1027 /*
1028  * Purge all sessions which have the 'kill_me' flag set.
1029  * This function has code to prevent it from running more than once every
1030  * few seconds, because running it after every single unbind would waste a lot
1031  * of CPU time and keep the context list locked too much.  To force it to run
1032  * anyway, set "force" to nonzero.
1033  *
1034  *
1035  * After that's done, we raise the size of the worker thread pool
1036  * if such an action is appropriate.
1037  */
1038 void dead_session_purge(int force) {
1039         struct CitContext *ptr;         /* general-purpose utility pointer */
1040         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1041
1042         if (force == 0) {
1043                 if ( (time(NULL) - last_purge) < 5 ) {
1044                         return; /* Too soon, go away */
1045                 }
1046         }
1047         time(&last_purge);
1048
1049         begin_critical_section(S_SESSION_TABLE);
1050         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1051                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1052
1053                         /* Remove the session from the active list */
1054                         if (ptr->prev) {
1055                                 ptr->prev->next = ptr->next;
1056                         }
1057                         else {
1058                                 ContextList = ptr->next;
1059                         }
1060                         if (ptr->next) {
1061                                 ptr->next->prev = ptr->prev;
1062                         }
1063
1064                         --num_sessions;
1065
1066                         /* And put it on our to-be-destroyed list */
1067                         ptr->next = rem;
1068                         rem = ptr;
1069
1070                 }
1071         }
1072         end_critical_section(S_SESSION_TABLE);
1073
1074         /* Now that we no longer have the session list locked, we can take
1075          * our time and destroy any sessions on the to-be-killed list, which
1076          * is allocated privately on this thread's stack.
1077          */
1078         while (rem != NULL) {
1079                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1080                 RemoveContext(rem);
1081                 ptr = rem;
1082                 rem = rem->next;
1083                 free(ptr);
1084         }
1085
1086         /* Raise the size of the worker thread pool if necessary. */
1087         if ( (num_sessions > num_threads)
1088            && (num_threads < config.c_max_workers) ) {
1089                 begin_critical_section(S_WORKER_LIST);
1090                 create_worker();
1091                 end_critical_section(S_WORKER_LIST);
1092         }
1093 }
1094
1095
1096
1097
1098
1099 /*
1100  * masterCC is the context we use when not attached to a session.  This
1101  * function initializes it.
1102  */
1103 void InitializeMasterCC(void) {
1104         memset(&masterCC, 0, sizeof(struct CitContext));
1105         masterCC.internal_pgm = 1;
1106         masterCC.cs_pid = 0;
1107 }
1108
1109
1110
1111
1112
1113
1114 /*
1115  * Bind a thread to a context.  (It's inline merely to speed things up.)
1116  */
1117 INLINE void become_session(struct CitContext *which_con) {
1118         pthread_setspecific(MyConKey, (void *)which_con );
1119 }
1120
1121
1122
1123 /* 
1124  * This loop just keeps going and going and going...
1125  */     
1126 void *worker_thread(void *arg) {
1127         int i;
1128         int highest;
1129         struct CitContext *ptr;
1130         struct CitContext *bind_me = NULL;
1131         fd_set readfds;
1132         int retval = 0;
1133         struct CitContext *con= NULL;   /* Temporary context pointer */
1134         struct ServiceFunctionHook *serviceptr;
1135         int ssock;                      /* Descriptor for client socket */
1136         struct timeval tv;
1137         int force_purge = 0;
1138         int m;
1139
1140         num_threads++;
1141
1142         cdb_allocate_tsd();
1143
1144         while (!time_to_die) {
1145
1146                 /* make doubly sure we're not holding any stale db handles
1147                  * which might cause a deadlock.
1148                  */
1149                 cdb_check_handles();
1150 do_select:      force_purge = 0;
1151                 bind_me = NULL;         /* Which session shall we handle? */
1152
1153                 /* Initialize the fdset. */
1154                 FD_ZERO(&readfds);
1155                 highest = 0;
1156
1157                 begin_critical_section(S_SESSION_TABLE);
1158                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1159                         if (ptr->state == CON_IDLE) {
1160                                 FD_SET(ptr->client_socket, &readfds);
1161                                 if (ptr->client_socket > highest)
1162                                         highest = ptr->client_socket;
1163                         }
1164                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1165                                 bind_me = ptr;
1166                                 ptr->state = CON_EXECUTING;
1167                         }
1168                 }
1169                 end_critical_section(S_SESSION_TABLE);
1170
1171                 if (bind_me) {
1172                         goto SKIP_SELECT;
1173                 }
1174
1175                 /* If we got this far, it means that there are no sessions
1176                  * which a previous thread marked for attention, so we go
1177                  * ahead and get ready to select().
1178                  */
1179
1180                 /* First, add the various master sockets to the fdset. */
1181                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1182                 serviceptr = serviceptr->next ) {
1183                         m = serviceptr->msock;
1184                         FD_SET(m, &readfds);
1185                         if (m > highest) {
1186                                 highest = m;
1187                         }
1188                 }
1189
1190                 if (!time_to_die) {
1191                         tv.tv_sec = 1;          /* wake up every second if no input */
1192                         tv.tv_usec = 0;
1193                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1194                 }
1195
1196                 if (time_to_die) return(NULL);
1197
1198                 /* Now figure out who made this select() unblock.
1199                  * First, check for an error or exit condition.
1200                  */
1201                 if (retval < 0) {
1202                         if (errno == EBADF) {
1203                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1204                                         strerror(errno));
1205                                 goto do_select;
1206                         }
1207                         if (errno != EINTR) {
1208                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1209                                 time_to_die = 1;
1210                         } else if (!time_to_die)
1211                                 goto do_select;
1212                 }
1213
1214                 /* Next, check to see if it's a new client connecting
1215                  * on a master socket.
1216                  */
1217                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1218                      serviceptr = serviceptr->next ) {
1219
1220                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1221                                 ssock = accept(serviceptr->msock, NULL, 0);
1222                                 if (ssock >= 0) {
1223                                         lprintf(CTDL_DEBUG,
1224                                                 "New client socket %d\n",
1225                                                 ssock);
1226
1227                                         /* The master socket is non-blocking but the client
1228                                          * sockets need to be blocking, otherwise certain
1229                                          * operations barf on FreeBSD.  Not a fatal error.
1230                                          */
1231                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1232                                                 lprintf(CTDL_EMERG,
1233                                                         "citserver: Can't set socket to blocking: %s\n",
1234                                                         strerror(errno));
1235                                         }
1236
1237                                         /* New context will be created already
1238                                          * set up in the CON_EXECUTING state.
1239                                          */
1240                                         con = CreateNewContext();
1241
1242                                         /* Assign our new socket number to it. */
1243                                         con->client_socket = ssock;
1244                                         con->h_command_function =
1245                                                 serviceptr->h_command_function;
1246                                         con->h_async_function =
1247                                                 serviceptr->h_async_function;
1248
1249                                         /* Determine whether it's a local socket */
1250                                         if (serviceptr->sockpath != NULL)
1251                                                 con->is_local_socket = 1;
1252         
1253                                         /* Set the SO_REUSEADDR socket option */
1254                                         i = 1;
1255                                         setsockopt(ssock, SOL_SOCKET,
1256                                                 SO_REUSEADDR,
1257                                                 &i, sizeof(i));
1258
1259                                         become_session(con);
1260                                         begin_session(con);
1261                                         serviceptr->h_greeting_function();
1262                                         become_session(NULL);
1263                                         con->state = CON_IDLE;
1264                                         goto do_select;
1265                                 }
1266                         }
1267                 }
1268
1269                 /* It must be a client socket.  Find a context that has data
1270                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1271                  * active sockets other than our chosen one are marked as
1272                  * CON_READY so the next thread that comes around can just bind
1273                  * to one without having to select() again.
1274                  */
1275                 begin_critical_section(S_SESSION_TABLE);
1276                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1277                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1278                            && (ptr->state != CON_EXECUTING) ) {
1279                                 ptr->input_waiting = 1;
1280                                 if (!bind_me) {
1281                                         bind_me = ptr;  /* I choose you! */
1282                                         bind_me->state = CON_EXECUTING;
1283                                 }
1284                                 else {
1285                                         ptr->state = CON_READY;
1286                                 }
1287                         }
1288                 }
1289                 end_critical_section(S_SESSION_TABLE);
1290
1291 SKIP_SELECT:
1292                 /* We're bound to a session */
1293                 if (bind_me != NULL) {
1294                         become_session(bind_me);
1295
1296                         /* If the client has sent a command, execute it. */
1297                         if (CC->input_waiting) {
1298                                 CC->h_command_function();
1299                                 CC->input_waiting = 0;
1300                         }
1301
1302                         /* If there are asynchronous messages waiting and the
1303                          * client supports it, do those now */
1304                         if ((CC->is_async) && (CC->async_waiting)
1305                            && (CC->h_async_function != NULL)) {
1306                                 CC->h_async_function();
1307                                 CC->async_waiting = 0;
1308                         }
1309                         
1310                         force_purge = CC->kill_me;
1311                         become_session(NULL);
1312                         bind_me->state = CON_IDLE;
1313                 }
1314
1315                 dead_session_purge(force_purge);
1316                 do_housekeeping();
1317                 check_sched_shutdown();
1318         }
1319         if (con != NULL) free (con);//// TODO: could this harm other threads? 
1320         /* If control reaches this point, the server is shutting down */        
1321         return(NULL);
1322 }
1323
1324
1325
1326
1327 /*
1328  * SyslogFacility()
1329  * Translate text facility name to syslog.h defined value.
1330  */
1331 int SyslogFacility(char *name)
1332 {
1333         int i;
1334         struct
1335         {
1336                 int facility;
1337                 char *name;
1338         }   facTbl[] =
1339         {
1340                 {   LOG_KERN,   "kern"          },
1341                 {   LOG_USER,   "user"          },
1342                 {   LOG_MAIL,   "mail"          },
1343                 {   LOG_DAEMON, "daemon"        },
1344                 {   LOG_AUTH,   "auth"          },
1345                 {   LOG_SYSLOG, "syslog"        },
1346                 {   LOG_LPR,    "lpr"           },
1347                 {   LOG_NEWS,   "news"          },
1348                 {   LOG_UUCP,   "uucp"          },
1349                 {   LOG_LOCAL0, "local0"        },
1350                 {   LOG_LOCAL1, "local1"        },
1351                 {   LOG_LOCAL2, "local2"        },
1352                 {   LOG_LOCAL3, "local3"        },
1353                 {   LOG_LOCAL4, "local4"        },
1354                 {   LOG_LOCAL5, "local5"        },
1355                 {   LOG_LOCAL6, "local6"        },
1356                 {   LOG_LOCAL7, "local7"        },
1357                 {   0,            NULL          }
1358         };
1359         for(i = 0; facTbl[i].name != NULL; i++) {
1360                 if(!strcasecmp(name, facTbl[i].name))
1361                         return facTbl[i].facility;
1362         }
1363         enable_syslog = 0;
1364         return LOG_DAEMON;
1365 }
1366
1367
1368 /********** MEM CHEQQER ***********/
1369
1370 #ifdef DEBUG_MEMORY_LEAKS
1371
1372 #undef malloc
1373 #undef realloc
1374 #undef strdup
1375 #undef free
1376
1377 void *tracked_malloc(size_t size, char *file, int line) {
1378         struct igheap *thisheap;
1379         void *block;
1380
1381         block = malloc(size);
1382         if (block == NULL) return(block);
1383
1384         thisheap = malloc(sizeof(struct igheap));
1385         if (thisheap == NULL) {
1386                 free(block);
1387                 return(NULL);
1388         }
1389
1390         thisheap->block = block;
1391         strcpy(thisheap->file, file);
1392         thisheap->line = line;
1393         
1394         begin_critical_section(S_DEBUGMEMLEAKS);
1395         thisheap->next = igheap;
1396         igheap = thisheap;
1397         end_critical_section(S_DEBUGMEMLEAKS);
1398
1399         return(block);
1400 }
1401
1402
1403 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1404         struct igheap *thisheap;
1405         void *block;
1406
1407         block = realloc(ptr, size);
1408         if (block == NULL) return(block);
1409
1410         thisheap = malloc(sizeof(struct igheap));
1411         if (thisheap == NULL) {
1412                 free(block);
1413                 return(NULL);
1414         }
1415
1416         thisheap->block = block;
1417         strcpy(thisheap->file, file);
1418         thisheap->line = line;
1419         
1420         begin_critical_section(S_DEBUGMEMLEAKS);
1421         thisheap->next = igheap;
1422         igheap = thisheap;
1423         end_critical_section(S_DEBUGMEMLEAKS);
1424
1425         return(block);
1426 }
1427
1428
1429
1430 void tracked_free(void *ptr) {
1431         struct igheap *thisheap;
1432         struct igheap *trash;
1433
1434         free(ptr);
1435
1436         if (igheap == NULL) return;
1437         begin_critical_section(S_DEBUGMEMLEAKS);
1438         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1439                 if (thisheap->next != NULL) {
1440                         if (thisheap->next->block == ptr) {
1441                                 trash = thisheap->next;
1442                                 thisheap->next = thisheap->next->next;
1443                                 free(trash);
1444                         }
1445                 }
1446         }
1447         if (igheap->block == ptr) {
1448                 trash = igheap;
1449                 igheap = igheap->next;
1450                 free(trash);
1451         }
1452         end_critical_section(S_DEBUGMEMLEAKS);
1453 }
1454
1455 char *tracked_strdup(const char *s, char *file, int line) {
1456         char *ptr;
1457
1458         if (s == NULL) return(NULL);
1459         ptr = tracked_malloc(strlen(s) + 1, file, line);
1460         if (ptr == NULL) return(NULL);
1461         strncpy(ptr, s, strlen(s));
1462         return(ptr);
1463 }
1464
1465 void dump_heap(void) {
1466         struct igheap *thisheap;
1467
1468         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1469                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1470                         thisheap->file, thisheap->line);
1471         }
1472 }
1473
1474 #endif /*  DEBUG_MEMORY_LEAKS */