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