cd7f12107a5a15da0f3841d489cf7fda72b93cfe
[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         long ret, ret2;
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, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
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                         cit_backtrace();
603                         CC->kill_me = 1;
604                         return;
605                 }
606                 bytes_written = bytes_written + retval;
607         }
608 }
609
610
611 /*
612  * cprintf()  ...   Send formatted printable data to the client.   It is
613  *                implemented in terms of client_write() but remains in
614  *                sysdep.c in case we port to somewhere without va_args...
615  */
616 void cprintf(const char *format, ...) {   
617         va_list arg_ptr;   
618         char buf[1024];   
619    
620         va_start(arg_ptr, format);   
621         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
622                 buf[sizeof buf - 2] = '\n';
623         client_write(buf, strlen(buf)); 
624         va_end(arg_ptr);
625 }   
626
627
628 /*
629  * Read data from the client socket.
630  * Return values are:
631  *      1       Requested number of bytes has been read.
632  *      0       Request timed out.
633  *      -1      The socket is broken.
634  * If the socket breaks, the session will be terminated.
635  */
636 int client_read_to(char *buf, int bytes, int timeout)
637 {
638         int len,rlen;
639         fd_set rfds;
640         struct timeval tv;
641         int retval;
642
643 #ifdef HAVE_OPENSSL
644         if (CC->redirect_ssl) {
645                 return (client_read_ssl(buf, bytes, timeout));
646         }
647 #endif
648         len = 0;
649         while(len<bytes) {
650                 FD_ZERO(&rfds);
651                 FD_SET(CC->client_socket, &rfds);
652                 tv.tv_sec = timeout;
653                 tv.tv_usec = 0;
654
655                 retval = select( (CC->client_socket)+1, 
656                                         &rfds, NULL, NULL, &tv);
657
658                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
659                         return(0);
660                 }
661
662                 rlen = read(CC->client_socket, &buf[len], bytes-len);
663                 if (rlen<1) {
664                         /* The socket has been disconnected! */
665                         CC->kill_me = 1;
666                         return(-1);
667                 }
668                 len = len + rlen;
669         }
670         return(1);
671 }
672
673 /*
674  * Read data from the client socket with default timeout.
675  * (This is implemented in terms of client_read_to() and could be
676  * justifiably moved out of sysdep.c)
677  */
678 INLINE int client_read(char *buf, int bytes)
679 {
680         return(client_read_to(buf, bytes, config.c_sleeping));
681 }
682
683
684 /*
685  * client_getln()   ...   Get a LF-terminated line of text from the client.
686  * (This is implemented in terms of client_read() and could be
687  * justifiably moved out of sysdep.c)
688  */
689 int client_getln(char *buf, int bufsize)
690 {
691         int i, retval;
692
693         /* Read one character at a time.
694          */
695         for (i = 0;;i++) {
696                 retval = client_read(&buf[i], 1);
697                 if (retval != 1 || buf[i] == '\n' || i == (bufsize-1))
698                         break;
699         }
700
701         /* If we got a long line, discard characters until the newline.
702          */
703         if (i == (bufsize-1))
704                 while (buf[i] != '\n' && retval == 1)
705                         retval = client_read(&buf[i], 1);
706
707         /* Strip the trailing LF, and the trailing CR if present.
708          */
709         buf[i] = 0;
710         while ( (!IsEmptyStr(buf)) && ((buf[strlen(buf)-1]==10) || (buf[strlen(buf)-1] == 13)) ) {
711                 buf[strlen(buf)-1] = 0;
712         }
713         if (retval < 0) safestrncpy(buf, "000", bufsize);
714         return(retval);
715 }
716
717
718
719 /*
720  * The system-dependent part of master_cleanup() - close the master socket.
721  */
722 void sysdep_master_cleanup(void) {
723         struct ServiceFunctionHook *serviceptr;
724
725 /////   DestroyWorkerList();
726         /*
727          * close all protocol master sockets
728          */
729         for (serviceptr = ServiceHookTable; serviceptr != NULL;
730             serviceptr = serviceptr->next ) {
731
732                 if (serviceptr->tcp_port > 0)
733                         lprintf(CTDL_INFO, "Closing listener on port %d\n",
734                                 serviceptr->tcp_port);
735
736                 if (serviceptr->sockpath != NULL)
737                         lprintf(CTDL_INFO, "Closing listener on '%s'\n",
738                                 serviceptr->sockpath);
739
740                 close(serviceptr->msock);
741
742                 /* If it's a Unix domain socket, remove the file. */
743                 if (serviceptr->sockpath != NULL) {
744                         unlink(serviceptr->sockpath);
745                 }
746         }
747 #ifdef HAVE_OPENSSL
748         destruct_ssl();
749 #endif
750         serv_calendar_destroy();
751         CtdlDestroyProtoHooks();
752         CtdlDestroyDeleteHooks();
753         CtdlDestroyXmsgHooks();
754         CtdlDestroyNetprocHooks();
755         CtdlDestroyUserHooks();
756         CtdlDestroyMessageHook();
757         CtdlDestroyCleanupHooks();
758         CtdlDestroyFixedOutputHooks();  
759         CtdlDestroySessionHooks();
760         CtdlDestroyServiceHook();
761 }
762
763
764
765
766 /*
767  * Terminate another session.
768  * (This could justifiably be moved out of sysdep.c because it
769  * no longer does anything that is system-dependent.)
770  */
771 void kill_session(int session_to_kill) {
772         struct CitContext *ptr;
773
774         begin_critical_section(S_SESSION_TABLE);
775         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
776                 if (ptr->cs_pid == session_to_kill) {
777                         ptr->kill_me = 1;
778                 }
779         }
780         end_critical_section(S_SESSION_TABLE);
781 }
782
783 pid_t current_child;
784 void graceful_shutdown(int signum) {
785         kill(current_child, signum);
786         unlink(file_pid_file);
787         exit(0);
788 }
789
790
791 /*
792  * Start running as a daemon.
793  */
794 void start_daemon(int unused) {
795         int status = 0;
796         pid_t child = 0;
797         FILE *fp;
798         int do_restart = 0;
799
800         current_child = 0;
801
802         /* Close stdin/stdout/stderr and replace them with /dev/null.
803          * We don't just call close() because we don't want these fd's
804          * to be reused for other files.
805          */
806         chdir(ctdl_run_dir);
807
808         child = fork();
809         if (child != 0) {
810                 exit(0);
811         }
812         
813         signal(SIGHUP, SIG_IGN);
814         signal(SIGINT, SIG_IGN);
815         signal(SIGQUIT, SIG_IGN);
816
817         setsid();
818         umask(0);
819         freopen("/dev/null", "r", stdin);
820         freopen("/dev/null", "w", stdout);
821         freopen("/dev/null", "w", stderr);
822
823         do {
824                 current_child = fork();
825
826                 signal(SIGTERM, graceful_shutdown);
827         
828                 if (current_child < 0) {
829                         perror("fork");
830                         exit(errno);
831                 }
832         
833                 else if (current_child == 0) {
834                         return; /* continue starting citadel. */
835                 }
836         
837                 else {
838                         fp = fopen(file_pid_file, "w");
839                         if (fp != NULL) {
840                                 fprintf(fp, ""F_PID_T"\n", child);
841                                 fclose(fp);
842                         }
843                         waitpid(current_child, &status, 0);
844                 }
845
846                 do_restart = 0;
847
848                 /* Did the main process exit with an actual exit code? */
849                 if (WIFEXITED(status)) {
850
851                         /* Exit code 0 means the watcher should exit */
852                         if (WEXITSTATUS(status) == 0) {
853                                 do_restart = 0;
854                         }
855
856                         /* Exit code 101-109 means the watcher should exit */
857                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
858                                 do_restart = 0;
859                         }
860
861                         /* Any other exit code means we should restart. */
862                         else {
863                                 do_restart = 1;
864                         }
865                 }
866
867                 /* Any other type of termination (signals, etc.) should also restart. */
868                 else {
869                         do_restart = 1;
870                 }
871
872         } while (do_restart);
873
874         unlink(file_pid_file);
875         exit(WEXITSTATUS(status));
876 }
877
878
879
880 /*
881  * Generic routine to convert a login name to a full name (gecos)
882  * Returns nonzero if a conversion took place
883  */
884 int convert_login(char NameToConvert[]) {
885         struct passwd *pw;
886         int a;
887
888         pw = getpwnam(NameToConvert);
889         if (pw == NULL) {
890                 return(0);
891         }
892         else {
893                 strcpy(NameToConvert, pw->pw_gecos);
894                 for (a=0; a<strlen(NameToConvert); ++a) {
895                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
896                 }
897                 return(1);
898         }
899 }
900
901 struct worker_node *worker_list = NULL;
902
903
904 /*
905  * create a worker thread. this function must always be called from within
906  * an S_WORKER_LIST critical section!
907  */
908 void create_worker(void) {
909         int ret;
910         struct worker_node *n;
911         pthread_attr_t attr;
912
913         n = malloc(sizeof(struct worker_node));
914         if (n == NULL) {
915                 lprintf(CTDL_EMERG, "can't allocate worker_node, exiting\n");
916                 time_to_die = -1;
917                 return;
918         }
919
920         if ((ret = pthread_attr_init(&attr))) {
921                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
922                 time_to_die = -1;
923                 return;
924         }
925
926         /* Our per-thread stacks need to be bigger than the default size,
927          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
928          * crashes on 64-bit Linux.
929          */
930         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
931                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
932                         strerror(ret));
933                 time_to_die = -1;
934                 pthread_attr_destroy(&attr);
935                 return;
936         }
937
938         if ((ret = pthread_create(&n->tid, &attr, worker_thread, NULL) != 0))
939         {
940
941                 lprintf(CTDL_ALERT, "Can't create worker thread: %s\n",
942                         strerror(ret));
943         }
944
945         n->next = worker_list;
946         worker_list = n;
947         pthread_attr_destroy(&attr);
948 }
949
950 void DestroyWorkerList(void)
951 {
952         struct CitContext *ptr;         /* general-purpose utility pointer */
953         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
954
955         begin_critical_section(S_SESSION_TABLE);
956         ptr = ContextList;
957         while (ptr != NULL){
958                 /* Remove the session from the active list */
959                 rem = ptr->next;
960                 --num_sessions;
961                 
962                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
963                 end_critical_section(S_SESSION_TABLE);
964                 RemoveContext(ptr);
965                 begin_critical_section(S_SESSION_TABLE);
966                 free (ptr);
967                 ptr = rem;
968         }
969         end_critical_section(S_SESSION_TABLE);
970
971         struct worker_node *cur, *p;
972         cur = worker_list;
973         while (cur != NULL)
974         {
975                 p = cur->next;
976                 free (cur);
977                 cur = p;
978         }
979         worker_list = NULL;
980 }
981
982 /*
983  * Create the maintenance threads and begin their operation.
984  */
985 void create_maintenance_threads(void) {
986         int ret;
987         pthread_attr_t attr;
988
989         if ((ret = pthread_attr_init(&attr))) {
990                 lprintf(CTDL_EMERG, "pthread_attr_init: %s\n", strerror(ret));
991                 time_to_die = -1;
992                 return;
993         }
994
995         /* Our per-thread stacks need to be bigger than the default size,
996          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
997          * crashes on 64-bit Linux.
998          */
999         if ((ret = pthread_attr_setstacksize(&attr, THREADSTACKSIZE))) {
1000                 lprintf(CTDL_EMERG, "pthread_attr_setstacksize: %s\n",
1001                         strerror(ret));
1002                 time_to_die = -1;
1003                 pthread_attr_destroy(&attr);
1004                 return;
1005         }
1006         
1007         struct MaintenanceThreadHook *fcn;
1008
1009         lprintf(CTDL_DEBUG, "Performing startup of maintenance thread hooks\n");
1010
1011         for (fcn = MaintenanceThreadHookTable; fcn != NULL; fcn = fcn->next) {
1012                 if ((ret = pthread_create(&(fcn->MaintenanceThread_tid), &attr, fcn->fcn_ptr, NULL) != 0)) {
1013                         lprintf(CTDL_ALERT, "Can't create thread: %s\n", strerror(ret));
1014                 }
1015                 else
1016                 {
1017                         lprintf(CTDL_NOTICE, "Spawned a new maintenance thread \"%s\" (%ld). \n", fcn->name,
1018                                 fcn->MaintenanceThread_tid);
1019                 }
1020         }
1021
1022
1023         pthread_attr_destroy(&attr);
1024 }
1025
1026
1027
1028 /*
1029  * Purge all sessions which have the 'kill_me' flag set.
1030  * This function has code to prevent it from running more than once every
1031  * few seconds, because running it after every single unbind would waste a lot
1032  * of CPU time and keep the context list locked too much.  To force it to run
1033  * anyway, set "force" to nonzero.
1034  *
1035  *
1036  * After that's done, we raise the size of the worker thread pool
1037  * if such an action is appropriate.
1038  */
1039 void dead_session_purge(int force) {
1040         struct CitContext *ptr;         /* general-purpose utility pointer */
1041         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
1042
1043         if (force == 0) {
1044                 if ( (time(NULL) - last_purge) < 5 ) {
1045                         return; /* Too soon, go away */
1046                 }
1047         }
1048         time(&last_purge);
1049
1050         begin_critical_section(S_SESSION_TABLE);
1051         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1052                 if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
1053
1054                         /* Remove the session from the active list */
1055                         if (ptr->prev) {
1056                                 ptr->prev->next = ptr->next;
1057                         }
1058                         else {
1059                                 ContextList = ptr->next;
1060                         }
1061                         if (ptr->next) {
1062                                 ptr->next->prev = ptr->prev;
1063                         }
1064
1065                         --num_sessions;
1066
1067                         /* And put it on our to-be-destroyed list */
1068                         ptr->next = rem;
1069                         rem = ptr;
1070
1071                 }
1072         }
1073         end_critical_section(S_SESSION_TABLE);
1074
1075         /* Now that we no longer have the session list locked, we can take
1076          * our time and destroy any sessions on the to-be-killed list, which
1077          * is allocated privately on this thread's stack.
1078          */
1079         while (rem != NULL) {
1080                 lprintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
1081                 RemoveContext(rem);
1082                 ptr = rem;
1083                 rem = rem->next;
1084                 free(ptr);
1085         }
1086
1087         /* Raise the size of the worker thread pool if necessary. */
1088         if ( (num_sessions > num_threads)
1089            && (num_threads < config.c_max_workers) ) {
1090                 begin_critical_section(S_WORKER_LIST);
1091                 create_worker();
1092                 end_critical_section(S_WORKER_LIST);
1093         }
1094 }
1095
1096
1097
1098
1099
1100 /*
1101  * masterCC is the context we use when not attached to a session.  This
1102  * function initializes it.
1103  */
1104 void InitializeMasterCC(void) {
1105         memset(&masterCC, 0, sizeof(struct CitContext));
1106         masterCC.internal_pgm = 1;
1107         masterCC.cs_pid = 0;
1108 }
1109
1110
1111
1112
1113
1114
1115 /*
1116  * Bind a thread to a context.  (It's inline merely to speed things up.)
1117  */
1118 INLINE void become_session(struct CitContext *which_con) {
1119         pthread_setspecific(MyConKey, (void *)which_con );
1120 }
1121
1122
1123
1124 /* 
1125  * This loop just keeps going and going and going...
1126  */     
1127 void *worker_thread(void *arg) {
1128         int i;
1129         int highest;
1130         struct CitContext *ptr;
1131         struct CitContext *bind_me = NULL;
1132         fd_set readfds;
1133         int retval = 0;
1134         struct CitContext *con= NULL;   /* Temporary context pointer */
1135         struct ServiceFunctionHook *serviceptr;
1136         int ssock;                      /* Descriptor for client socket */
1137         struct timeval tv;
1138         int force_purge = 0;
1139         int m;
1140
1141         num_threads++;
1142
1143         cdb_allocate_tsd();
1144
1145         while (!time_to_die) {
1146
1147                 /* make doubly sure we're not holding any stale db handles
1148                  * which might cause a deadlock.
1149                  */
1150                 cdb_check_handles();
1151 do_select:      force_purge = 0;
1152                 bind_me = NULL;         /* Which session shall we handle? */
1153
1154                 /* Initialize the fdset. */
1155                 FD_ZERO(&readfds);
1156                 highest = 0;
1157
1158                 begin_critical_section(S_SESSION_TABLE);
1159                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1160                         if (ptr->state == CON_IDLE) {
1161                                 FD_SET(ptr->client_socket, &readfds);
1162                                 if (ptr->client_socket > highest)
1163                                         highest = ptr->client_socket;
1164                         }
1165                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
1166                                 bind_me = ptr;
1167                                 ptr->state = CON_EXECUTING;
1168                         }
1169                 }
1170                 end_critical_section(S_SESSION_TABLE);
1171
1172                 if (bind_me) {
1173                         goto SKIP_SELECT;
1174                 }
1175
1176                 /* If we got this far, it means that there are no sessions
1177                  * which a previous thread marked for attention, so we go
1178                  * ahead and get ready to select().
1179                  */
1180
1181                 /* First, add the various master sockets to the fdset. */
1182                 for (serviceptr = ServiceHookTable; serviceptr != NULL;
1183                 serviceptr = serviceptr->next ) {
1184                         m = serviceptr->msock;
1185                         FD_SET(m, &readfds);
1186                         if (m > highest) {
1187                                 highest = m;
1188                         }
1189                 }
1190
1191                 if (!time_to_die) {
1192                         tv.tv_sec = 1;          /* wake up every second if no input */
1193                         tv.tv_usec = 0;
1194                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1195                 }
1196
1197                 if (time_to_die) return(NULL);
1198
1199                 /* Now figure out who made this select() unblock.
1200                  * First, check for an error or exit condition.
1201                  */
1202                 if (retval < 0) {
1203                         if (errno == EBADF) {
1204                                 lprintf(CTDL_NOTICE, "select() failed: (%s)\n",
1205                                         strerror(errno));
1206                                 goto do_select;
1207                         }
1208                         if (errno != EINTR) {
1209                                 lprintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1210                                 time_to_die = 1;
1211                         } else if (!time_to_die)
1212                                 goto do_select;
1213                 }
1214
1215                 /* Next, check to see if it's a new client connecting
1216                  * on a master socket.
1217                  */
1218                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1219                      serviceptr = serviceptr->next ) {
1220
1221                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1222                                 ssock = accept(serviceptr->msock, NULL, 0);
1223                                 if (ssock >= 0) {
1224                                         lprintf(CTDL_DEBUG,
1225                                                 "New client socket %d\n",
1226                                                 ssock);
1227
1228                                         /* The master socket is non-blocking but the client
1229                                          * sockets need to be blocking, otherwise certain
1230                                          * operations barf on FreeBSD.  Not a fatal error.
1231                                          */
1232                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1233                                                 lprintf(CTDL_EMERG,
1234                                                         "citserver: Can't set socket to blocking: %s\n",
1235                                                         strerror(errno));
1236                                         }
1237
1238                                         /* New context will be created already
1239                                          * set up in the CON_EXECUTING state.
1240                                          */
1241                                         con = CreateNewContext();
1242
1243                                         /* Assign our new socket number to it. */
1244                                         con->client_socket = ssock;
1245                                         con->h_command_function =
1246                                                 serviceptr->h_command_function;
1247                                         con->h_async_function =
1248                                                 serviceptr->h_async_function;
1249
1250                                         /* Determine whether it's a local socket */
1251                                         if (serviceptr->sockpath != NULL)
1252                                                 con->is_local_socket = 1;
1253         
1254                                         /* Set the SO_REUSEADDR socket option */
1255                                         i = 1;
1256                                         setsockopt(ssock, SOL_SOCKET,
1257                                                 SO_REUSEADDR,
1258                                                 &i, sizeof(i));
1259
1260                                         become_session(con);
1261                                         begin_session(con);
1262                                         serviceptr->h_greeting_function();
1263                                         become_session(NULL);
1264                                         con->state = CON_IDLE;
1265                                         goto do_select;
1266                                 }
1267                         }
1268                 }
1269
1270                 /* It must be a client socket.  Find a context that has data
1271                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1272                  * active sockets other than our chosen one are marked as
1273                  * CON_READY so the next thread that comes around can just bind
1274                  * to one without having to select() again.
1275                  */
1276                 begin_critical_section(S_SESSION_TABLE);
1277                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1278                         if ( (FD_ISSET(ptr->client_socket, &readfds))
1279                            && (ptr->state != CON_EXECUTING) ) {
1280                                 ptr->input_waiting = 1;
1281                                 if (!bind_me) {
1282                                         bind_me = ptr;  /* I choose you! */
1283                                         bind_me->state = CON_EXECUTING;
1284                                 }
1285                                 else {
1286                                         ptr->state = CON_READY;
1287                                 }
1288                         }
1289                 }
1290                 end_critical_section(S_SESSION_TABLE);
1291
1292 SKIP_SELECT:
1293                 /* We're bound to a session */
1294                 if (bind_me != NULL) {
1295                         become_session(bind_me);
1296
1297                         /* If the client has sent a command, execute it. */
1298                         if (CC->input_waiting) {
1299                                 CC->h_command_function();
1300                                 CC->input_waiting = 0;
1301                         }
1302
1303                         /* If there are asynchronous messages waiting and the
1304                          * client supports it, do those now */
1305                         if ((CC->is_async) && (CC->async_waiting)
1306                            && (CC->h_async_function != NULL)) {
1307                                 CC->h_async_function();
1308                                 CC->async_waiting = 0;
1309                         }
1310                         
1311                         force_purge = CC->kill_me;
1312                         become_session(NULL);
1313                         bind_me->state = CON_IDLE;
1314                 }
1315
1316                 dead_session_purge(force_purge);
1317                 do_housekeeping();
1318                 check_sched_shutdown();
1319         }
1320         if (con != NULL) free (con);//// TODO: could this harm other threads? 
1321         /* If control reaches this point, the server is shutting down */        
1322         return(NULL);
1323 }
1324
1325
1326
1327
1328 /*
1329  * SyslogFacility()
1330  * Translate text facility name to syslog.h defined value.
1331  */
1332 int SyslogFacility(char *name)
1333 {
1334         int i;
1335         struct
1336         {
1337                 int facility;
1338                 char *name;
1339         }   facTbl[] =
1340         {
1341                 {   LOG_KERN,   "kern"          },
1342                 {   LOG_USER,   "user"          },
1343                 {   LOG_MAIL,   "mail"          },
1344                 {   LOG_DAEMON, "daemon"        },
1345                 {   LOG_AUTH,   "auth"          },
1346                 {   LOG_SYSLOG, "syslog"        },
1347                 {   LOG_LPR,    "lpr"           },
1348                 {   LOG_NEWS,   "news"          },
1349                 {   LOG_UUCP,   "uucp"          },
1350                 {   LOG_LOCAL0, "local0"        },
1351                 {   LOG_LOCAL1, "local1"        },
1352                 {   LOG_LOCAL2, "local2"        },
1353                 {   LOG_LOCAL3, "local3"        },
1354                 {   LOG_LOCAL4, "local4"        },
1355                 {   LOG_LOCAL5, "local5"        },
1356                 {   LOG_LOCAL6, "local6"        },
1357                 {   LOG_LOCAL7, "local7"        },
1358                 {   0,            NULL          }
1359         };
1360         for(i = 0; facTbl[i].name != NULL; i++) {
1361                 if(!strcasecmp(name, facTbl[i].name))
1362                         return facTbl[i].facility;
1363         }
1364         enable_syslog = 0;
1365         return LOG_DAEMON;
1366 }
1367
1368
1369 /********** MEM CHEQQER ***********/
1370
1371 #ifdef DEBUG_MEMORY_LEAKS
1372
1373 #undef malloc
1374 #undef realloc
1375 #undef strdup
1376 #undef free
1377
1378 void *tracked_malloc(size_t size, char *file, int line) {
1379         struct igheap *thisheap;
1380         void *block;
1381
1382         block = malloc(size);
1383         if (block == NULL) return(block);
1384
1385         thisheap = malloc(sizeof(struct igheap));
1386         if (thisheap == NULL) {
1387                 free(block);
1388                 return(NULL);
1389         }
1390
1391         thisheap->block = block;
1392         strcpy(thisheap->file, file);
1393         thisheap->line = line;
1394         
1395         begin_critical_section(S_DEBUGMEMLEAKS);
1396         thisheap->next = igheap;
1397         igheap = thisheap;
1398         end_critical_section(S_DEBUGMEMLEAKS);
1399
1400         return(block);
1401 }
1402
1403
1404 void *tracked_realloc(void *ptr, size_t size, char *file, int line) {
1405         struct igheap *thisheap;
1406         void *block;
1407
1408         block = realloc(ptr, size);
1409         if (block == NULL) return(block);
1410
1411         thisheap = malloc(sizeof(struct igheap));
1412         if (thisheap == NULL) {
1413                 free(block);
1414                 return(NULL);
1415         }
1416
1417         thisheap->block = block;
1418         strcpy(thisheap->file, file);
1419         thisheap->line = line;
1420         
1421         begin_critical_section(S_DEBUGMEMLEAKS);
1422         thisheap->next = igheap;
1423         igheap = thisheap;
1424         end_critical_section(S_DEBUGMEMLEAKS);
1425
1426         return(block);
1427 }
1428
1429
1430
1431 void tracked_free(void *ptr) {
1432         struct igheap *thisheap;
1433         struct igheap *trash;
1434
1435         free(ptr);
1436
1437         if (igheap == NULL) return;
1438         begin_critical_section(S_DEBUGMEMLEAKS);
1439         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1440                 if (thisheap->next != NULL) {
1441                         if (thisheap->next->block == ptr) {
1442                                 trash = thisheap->next;
1443                                 thisheap->next = thisheap->next->next;
1444                                 free(trash);
1445                         }
1446                 }
1447         }
1448         if (igheap->block == ptr) {
1449                 trash = igheap;
1450                 igheap = igheap->next;
1451                 free(trash);
1452         }
1453         end_critical_section(S_DEBUGMEMLEAKS);
1454 }
1455
1456 char *tracked_strdup(const char *s, char *file, int line) {
1457         char *ptr;
1458
1459         if (s == NULL) return(NULL);
1460         ptr = tracked_malloc(strlen(s) + 1, file, line);
1461         if (ptr == NULL) return(NULL);
1462         strncpy(ptr, s, strlen(s));
1463         return(ptr);
1464 }
1465
1466 void dump_heap(void) {
1467         struct igheap *thisheap;
1468
1469         for (thisheap = igheap; thisheap != NULL; thisheap = thisheap->next) {
1470                 lprintf(CTDL_CRIT, "UNFREED: %30s : %d\n",
1471                         thisheap->file, thisheap->line);
1472         }
1473 }
1474
1475 #endif /*  DEBUG_MEMORY_LEAKS */