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