2eccadc64685ca2a000ae7719b26888ad87ce3f7
[citadel] / citadel / sysdep.c
1 /*
2  * Citadel "system dependent" stuff.
3  *
4  * Here's where we (hopefully) have most parts of the Citadel server that
5  * might need tweaking when run on different operating system variants.
6  *
7  * Copyright (c) 1987-2021 by the citadel.org team
8  *
9  * This program is open source software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License, version 3.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  */
17
18 #include "sysdep.h"
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <syslog.h>
26 #include <sys/syslog.h>
27 #include <netdb.h>
28 #include <sys/un.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <netinet/tcp.h>
34 #include <arpa/inet.h>
35 #define SHOW_ME_VAPPEND_PRINTF
36 #include <libcitadel.h>
37 #include "citserver.h"
38 #include "config.h"
39 #include "ctdl_module.h"
40 #include "sysdep_decls.h"
41 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
42 #include "housekeeping.h"
43 #include "context.h"
44
45 /*
46  * Signal handler to shut down the server.
47  */
48
49 volatile int exit_signal = 0;
50 volatile int shutdown_and_halt = 0;
51 volatile int restart_server = 0;
52 volatile int running_as_daemon = 0;
53
54
55 static RETSIGTYPE signal_cleanup(int signum) {
56         syslog(LOG_DEBUG, "sysdep: caught signal %d; shutting down.", signum);
57         exit_signal = signum;
58         server_shutting_down = 1;
59 }
60
61
62 static RETSIGTYPE signal_exit(int signum) {
63         exit(1);
64 }
65
66
67 /*
68  * Some initialization stuff...
69  */
70 void init_sysdep(void) {
71         sigset_t set;
72
73         /* Avoid vulnerabilities related to FD_SETSIZE if we can. */
74 #ifdef FD_SETSIZE
75 #ifdef RLIMIT_NOFILE
76         struct rlimit rl;
77         getrlimit(RLIMIT_NOFILE, &rl);
78         rl.rlim_cur = FD_SETSIZE;
79         rl.rlim_max = FD_SETSIZE;
80         setrlimit(RLIMIT_NOFILE, &rl);
81 #endif
82 #endif
83
84         /* If we've got OpenSSL, we're going to use it. */
85 #ifdef HAVE_OPENSSL
86         init_ssl();
87 #endif
88
89         if (pthread_key_create(&ThreadKey, NULL) != 0) {                        // TSD for threads
90                 syslog(LOG_ERR, "pthread_key_create() : %m");
91                 abort();
92         }
93         
94         if (pthread_key_create(&MyConKey, NULL) != 0) {                         // TSD for sessions
95                 syslog(LOG_CRIT, "sysdep: can't create TSD key: %m");
96                 abort();
97         }
98
99         /*
100          * Interript, hangup, and terminate signals should cause the server
101          * to gracefully clean up and shut down.
102          */
103         sigemptyset(&set);
104         sigaddset(&set, SIGINT);
105         sigaddset(&set, SIGHUP);
106         sigaddset(&set, SIGTERM);
107         sigprocmask(SIG_UNBLOCK, &set, NULL);
108
109         signal(SIGINT, signal_cleanup);
110         signal(SIGHUP, signal_cleanup);
111         signal(SIGTERM, signal_cleanup);
112         signal(SIGUSR2, signal_exit);
113
114         /*
115          * Do not shut down the server on broken pipe signals, otherwise the
116          * whole Citadel service would come down whenever a single client
117          * socket breaks.
118          */
119         signal(SIGPIPE, SIG_IGN);
120 }
121
122
123 /* 
124  * This is a generic function to set up a master socket for listening on
125  * a TCP port.  The server shuts down if the bind fails.  (IPv4/IPv6 version)
126  *
127  * ip_addr      IP address to bind
128  * port_number  port number to bind
129  * queue_len    number of incoming connections to allow in the queue
130  */
131 int ctdl_tcp_server(char *ip_addr, int port_number, int queue_len)
132 {
133         struct protoent *p;
134         struct sockaddr_in6 sin6;
135         struct sockaddr_in sin4;
136         int s, i, b;
137         int ip_version = 6;
138
139         memset(&sin6, 0, sizeof(sin6));
140         memset(&sin4, 0, sizeof(sin4));
141         sin6.sin6_family = AF_INET6;
142         sin4.sin_family = AF_INET;
143
144         if (    (ip_addr == NULL)                                                       /* any IPv6 */
145                 || (IsEmptyStr(ip_addr))
146                 || (!strcmp(ip_addr, "*"))
147         ) {
148                 ip_version = 6;
149                 sin6.sin6_addr = in6addr_any;
150         }
151         else if (!strcmp(ip_addr, "0.0.0.0"))                                           /* any IPv4 */
152         {
153                 ip_version = 4;
154                 sin4.sin_addr.s_addr = INADDR_ANY;
155         }
156         else if ((strchr(ip_addr, '.')) && (!strchr(ip_addr, ':')))                     /* specific IPv4 */
157         {
158                 ip_version = 4;
159                 if (inet_pton(AF_INET, ip_addr, &sin4.sin_addr) <= 0) {
160                         syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
161                         return (-1);
162                 }
163         }
164         else                                                                            /* specific IPv6 */
165         {
166                 ip_version = 6;
167                 if (inet_pton(AF_INET6, ip_addr, &sin6.sin6_addr) <= 0) {
168                         syslog(LOG_ALERT, "tcpserver: inet_pton: %m");
169                         return (-1);
170                 }
171         }
172
173         if (port_number == 0) {
174                 syslog(LOG_ALERT, "tcpserver: no port number was specified");
175                 return (-1);
176         }
177         sin6.sin6_port = htons((u_short) port_number);
178         sin4.sin_port = htons((u_short) port_number);
179
180         p = getprotobyname("tcp");
181         if (p == NULL) {
182                 syslog(LOG_ALERT, "tcpserver: getprotobyname: %m");
183                 return (-1);
184         }
185
186         s = socket( ((ip_version == 6) ? PF_INET6 : PF_INET), SOCK_STREAM, (p->p_proto));
187         if (s < 0) {
188                 syslog(LOG_ALERT, "tcpserver: socket: %m");
189                 return (-1);
190         }
191         /* Set some socket options that make sense. */
192         i = 1;
193         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
194
195         if (ip_version == 6) {
196                 b = bind(s, (struct sockaddr *) &sin6, sizeof(sin6));
197         }
198         else {
199                 b = bind(s, (struct sockaddr *) &sin4, sizeof(sin4));
200         }
201
202         if (b < 0) {
203                 syslog(LOG_ALERT, "tcpserver: bind: %m");
204                 return (-1);
205         }
206
207         fcntl(s, F_SETFL, O_NONBLOCK);
208
209         if (listen(s, ((queue_len >= 5) ? queue_len : 5) ) < 0) {
210                 syslog(LOG_ALERT, "tcpserver: listen: %m");
211                 return (-1);
212         }
213         return (s);
214 }
215
216
217 /*
218  * Create a Unix domain socket and listen on it
219  */
220 int ctdl_uds_server(char *sockpath, int queue_len)
221 {
222         struct sockaddr_un addr;
223         int s;
224         int i;
225         int actual_queue_len;
226 #ifdef HAVE_STRUCT_UCRED
227         int passcred = 1;
228 #endif
229
230         actual_queue_len = queue_len;
231         if (actual_queue_len < 5) actual_queue_len = 5;
232
233         i = unlink(sockpath);
234         if ((i != 0) && (errno != ENOENT)) {
235                 syslog(LOG_ERR, "udsserver: %m");
236                 return(-1);
237         }
238
239         memset(&addr, 0, sizeof(addr));
240         addr.sun_family = AF_UNIX;
241         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
242
243         s = socket(AF_UNIX, SOCK_STREAM, 0);
244         if (s < 0) {
245                 syslog(LOG_ERR, "udsserver: socket: %m");
246                 return(-1);
247         }
248
249         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
250                 syslog(LOG_ERR, "udsserver: bind: %m");
251                 return(-1);
252         }
253
254         /* set to nonblock - we need this for some obscure situations */
255         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0) {
256                 syslog(LOG_ERR, "udsserver: fcntl: %m");
257                 close(s);
258                 return(-1);
259         }
260
261         if (listen(s, actual_queue_len) < 0) {
262                 syslog(LOG_ERR, "udsserver: listen: %m");
263                 return(-1);
264         }
265
266 #ifdef HAVE_STRUCT_UCRED
267         setsockopt(s, SOL_SOCKET, SO_PASSCRED, &passcred, sizeof(passcred));
268 #endif
269
270         chmod(sockpath, S_ISGID|S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
271         return(s);
272 }
273
274
275 /*
276  * The following functions implement output buffering on operating systems which
277  * support it (such as Linux and various BSD flavors).
278  */
279 #ifndef HAVE_DARWIN
280 #ifdef TCP_CORK
281 #       define HAVE_TCP_BUFFERING
282 #else
283 #       ifdef TCP_NOPUSH
284 #               define HAVE_TCP_BUFFERING
285 #               define TCP_CORK TCP_NOPUSH
286 #       endif
287 #endif /* TCP_CORK */
288 #endif /* HAVE_DARWIN */
289
290 static unsigned on = 1, off = 0;
291
292 void buffer_output(void) {
293 #ifdef HAVE_TCP_BUFFERING
294 #ifdef HAVE_OPENSSL
295         if (!CC->redirect_ssl)
296 #endif
297                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
298 #endif
299 }
300
301 void unbuffer_output(void) {
302 #ifdef HAVE_TCP_BUFFERING
303 #ifdef HAVE_OPENSSL
304         if (!CC->redirect_ssl)
305 #endif
306                 setsockopt(CC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
307 #endif
308 }
309
310 void flush_output(void) {
311 #ifdef HAVE_TCP_BUFFERING
312         struct CitContext *CCC = CC;
313         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &off, 4);
314         setsockopt(CCC->client_socket, IPPROTO_TCP, TCP_CORK, &on, 4);
315 #endif
316 }
317
318 /*
319 static void flush_client_inbuf(void)
320 {
321         CitContext *CCC=CC;
322
323         FlushStrBuf(CCC->ReadBuf);
324         CCC->RecvBuf->ReadWritePointer = NULL;
325 }
326 */
327
328
329 /*
330  * client_close()       ...     close the client socket
331  */
332 void client_close(void) {
333         CitContext *CCC = CC;
334
335         if (!CCC) return;
336         if (CCC->client_socket <= 0) return;
337         syslog(LOG_DEBUG, "sysdep: closing socket %d", CCC->client_socket);
338         close(CCC->client_socket);
339         CCC->client_socket = -1 ;
340 }
341
342
343 /*
344  * client_write()   ...    Send binary data to the client.
345  */
346 int client_write(const char *buf, int nbytes)
347 {
348         int bytes_written = 0;
349         int retval;
350 #ifndef HAVE_TCP_BUFFERING
351         int old_buffer_len = 0;
352 #endif
353         fd_set wset;
354         CitContext *Ctx;
355         int fdflags;
356
357         if (nbytes < 1) return(0);
358
359         Ctx = CC;
360
361         if (Ctx->redirect_buffer != NULL) {
362                 StrBufAppendBufPlain(Ctx->redirect_buffer,
363                                      buf, nbytes, 0);
364                 return 0;
365         }
366
367 #ifdef HAVE_OPENSSL
368         if (Ctx->redirect_ssl) {
369                 client_write_ssl(buf, nbytes);
370                 return 0;
371         }
372 #endif
373         if (Ctx->client_socket == -1) return -1;
374
375         fdflags = fcntl(Ctx->client_socket, F_GETFL);
376
377         while ((bytes_written < nbytes) && (Ctx->client_socket != -1)){
378                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
379                         FD_ZERO(&wset);
380                         FD_SET(Ctx->client_socket, &wset);
381                         if (select(1, NULL, &wset, NULL, NULL) == -1) {
382                                 if (errno == EINTR)
383                                 {
384                                         syslog(LOG_DEBUG, "sysdep: client_write(%d bytes) select() interrupted.", nbytes-bytes_written);
385                                         if (server_shutting_down) {
386                                                 CC->kill_me = KILLME_SELECT_INTERRUPTED;
387                                                 return (-1);
388                                         } else {
389                                                 /* can't trust fd's and stuff so we need to re-create them */
390                                                 continue;
391                                         }
392                                 } else {
393                                         syslog(LOG_ERR, "sysdep: client_write(%d bytes) select failed: %m", nbytes - bytes_written);
394                                         client_close();
395                                         Ctx->kill_me = KILLME_SELECT_FAILED;
396                                         return -1;
397                                 }
398                         }
399                 }
400
401                 retval = write(Ctx->client_socket, &buf[bytes_written], nbytes - bytes_written);
402                 if (retval < 1) {
403                         syslog(LOG_ERR, "sysdep: client_write(%d bytes) failed: %m", nbytes - bytes_written);
404                         client_close();
405                         Ctx->kill_me = KILLME_WRITE_FAILED;
406                         return -1;
407                 }
408                 bytes_written = bytes_written + retval;
409         }
410         return 0;
411 }
412
413 void cputbuf(const StrBuf *Buf) {   
414         client_write(ChrPtr(Buf), StrLength(Buf)); 
415 }   
416
417
418 /*
419  * cprintf()    Send formatted printable data to the client.
420  *              Implemented in terms of client_write() so it's technically not sysdep...
421  */
422 void cprintf(const char *format, ...) {   
423         va_list arg_ptr;   
424         char buf[1024];
425    
426         va_start(arg_ptr, format);   
427         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
428                 buf[sizeof buf - 2] = '\n';
429         client_write(buf, strlen(buf)); 
430         va_end(arg_ptr);
431 }   
432
433
434 /*
435  * Read data from the client socket.
436  *
437  * sock         socket fd to read from
438  * buf          buffer to read into 
439  * bytes        number of bytes to read
440  * timeout      Number of seconds to wait before timing out
441  *
442  * Possible return values:
443  *      1       Requested number of bytes has been read.
444  *      0       Request timed out.
445  *      -1      Connection is broken, or other error.
446  */
447 int client_read_blob(StrBuf *Target, int bytes, int timeout)
448 {
449         CitContext *CCC=CC;
450         const char *Error;
451         int retval = 0;
452
453 #ifdef HAVE_OPENSSL
454         if (CCC->redirect_ssl) {
455                 retval = client_read_sslblob(Target, bytes, timeout);
456                 if (retval < 0) {
457                         syslog(LOG_ERR, "sysdep: client_read_blob() failed");
458                 }
459         }
460         else 
461 #endif
462         {
463                 retval = StrBufReadBLOBBuffered(Target, 
464                                                 CCC->RecvBuf.Buf,
465                                                 &CCC->RecvBuf.ReadWritePointer,
466                                                 &CCC->client_socket,
467                                                 1, 
468                                                 bytes,
469                                                 O_TERM,
470                                                 &Error
471                 );
472                 if (retval < 0) {
473                         syslog(LOG_ERR, "sysdep: client_read_blob() failed: %s", Error);
474                         client_close();
475                         return retval;
476                 }
477         }
478         return retval;
479 }
480
481
482 /*
483  * to make client_read_random_blob() more efficient, increase buffer size.
484  * just use in greeting function, else your buffer may be flushed
485  */
486 void client_set_inbound_buf(long N)
487 {
488         CitContext *CCC=CC;
489         FlushStrBuf(CCC->RecvBuf.Buf);
490         ReAdjustEmptyBuf(CCC->RecvBuf.Buf, N * SIZ, N * SIZ);
491 }
492
493 int client_read_random_blob(StrBuf *Target, int timeout)
494 {
495         CitContext *CCC=CC;
496         int rc;
497
498         rc =  client_read_blob(Target, 1, timeout);
499         if (rc > 0)
500         {
501                 long len;
502                 const char *pch;
503                 
504                 len = StrLength(CCC->RecvBuf.Buf);
505                 pch = ChrPtr(CCC->RecvBuf.Buf);
506
507                 if (len > 0)
508                 {
509                         if (CCC->RecvBuf.ReadWritePointer != NULL) {
510                                 len -= CCC->RecvBuf.ReadWritePointer - pch;
511                                 pch = CCC->RecvBuf.ReadWritePointer;
512                         }
513                         StrBufAppendBufPlain(Target, pch, len, 0);
514                         FlushStrBuf(CCC->RecvBuf.Buf);
515                         CCC->RecvBuf.ReadWritePointer = NULL;
516                         return StrLength(Target);
517                 }
518                 return rc;
519         }
520         else
521                 return rc;
522 }
523
524 int client_read_to(char *buf, int bytes, int timeout)
525 {
526         CitContext *CCC=CC;
527         int rc;
528
529         rc = client_read_blob(CCC->MigrateBuf, bytes, timeout);
530         if (rc < 0)
531         {
532                 *buf = '\0';
533                 return rc;
534         }
535         else
536         {
537                 memcpy(buf, 
538                        ChrPtr(CCC->MigrateBuf),
539                        StrLength(CCC->MigrateBuf) + 1);
540                 FlushStrBuf(CCC->MigrateBuf);
541                 return rc;
542         }
543 }
544
545
546 int HaveMoreLinesWaiting(CitContext *CCC) {
547         if ((CCC->kill_me != 0) ||
548             ( (CCC->RecvBuf.ReadWritePointer == NULL) && 
549               (StrLength(CCC->RecvBuf.Buf) == 0) && 
550               (CCC->client_socket != -1)) )
551                 return 0;
552         else
553                 return 1;
554 }
555
556
557 /*
558  * Read data from the client socket with default timeout.
559  * (This is implemented in terms of client_read_to() and could be
560  * justifiably moved out of sysdep.c)
561  */
562 INLINE int client_read(char *buf, int bytes) {
563         return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
564 }
565
566 int CtdlClientGetLine(StrBuf *Target) {
567         CitContext *CCC=CC;
568         const char *Error;
569         int rc;
570
571         FlushStrBuf(Target);
572 #ifdef HAVE_OPENSSL
573         if (CCC->redirect_ssl) {
574                 rc = client_readline_sslbuffer(Target, CCC->RecvBuf.Buf, &CCC->RecvBuf.ReadWritePointer, 1);
575                 return rc;
576         }
577         else 
578 #endif
579         {
580                 rc = StrBufTCP_read_buffered_line_fast(Target, 
581                                                        CCC->RecvBuf.Buf,
582                                                        &CCC->RecvBuf.ReadWritePointer,
583                                                        &CCC->client_socket,
584                                                        5,
585                                                        1,
586                                                        &Error
587                 );
588                 return rc;
589         }
590 }
591
592
593 /*
594  * client_getln()   ...   Get a LF-terminated line of text from the client.
595  * (This is implemented in terms of client_read() and could be
596  * justifiably moved out of sysdep.c)
597  */
598 int client_getln(char *buf, int bufsize) {
599         int i, retval;
600         CitContext *CCC=CC;
601         const char *pCh;
602
603         retval = CtdlClientGetLine(CCC->MigrateBuf);
604         if (retval < 0)
605           return(retval >= 0);
606
607
608         i = StrLength(CCC->MigrateBuf);
609         pCh = ChrPtr(CCC->MigrateBuf);
610         /* Strip the trailing LF, and the trailing CR if present.
611          */
612         if (bufsize <= i)
613                 i = bufsize - 1;
614         while ( (i > 0)
615                 && ( (pCh[i - 1]==13)
616                      || ( pCh[i - 1]==10)) ) {
617                 i--;
618         }
619         memcpy(buf, pCh, i);
620         buf[i] = 0;
621
622         FlushStrBuf(CCC->MigrateBuf);
623         if (retval < 0) {
624                 safestrncpy(&buf[i], "000", bufsize - i);
625         }
626         return(retval >= 0);
627 }
628
629
630 /*
631  * Cleanup any contexts that are left lying around
632  */
633 void close_masters(void) {
634         struct ServiceFunctionHook *serviceptr;
635         const char *Text;
636
637         /*
638          * close all protocol master sockets
639          */
640         for (serviceptr = ServiceHookTable; serviceptr != NULL;
641             serviceptr = serviceptr->next ) {
642
643                 if (serviceptr->tcp_port > 0) {
644                         if (serviceptr->msock == -1) {
645                                 Text = "not closing again";
646                         }
647                         else {
648                                 Text = "Closing";
649                         }
650                         syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
651                                Text,
652                                serviceptr->msock,
653                                serviceptr->tcp_port
654                         );
655                         serviceptr->tcp_port = 0;
656                 }
657                 
658                 if (serviceptr->sockpath != NULL) {
659                         if (serviceptr->msock == -1) {
660                                 Text = "not closing again";
661                         }
662                         else {
663                                 Text = "Closing";
664                         }
665                         syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
666                                Text,
667                                serviceptr->msock,
668                                serviceptr->sockpath
669                         );
670                 }
671
672                 if (serviceptr->msock != -1) {
673                         close(serviceptr->msock);
674                         serviceptr->msock = -1;
675                 }
676
677                 /* If it's a Unix domain socket, remove the file. */
678                 if (serviceptr->sockpath != NULL) {
679                         unlink(serviceptr->sockpath);
680                         serviceptr->sockpath = NULL;
681                 }
682         }
683 }
684
685
686 /*
687  * The system-dependent part of master_cleanup() - close the master socket.
688  */
689 void sysdep_master_cleanup(void) {
690         close_masters();
691         context_cleanup();
692 #ifdef HAVE_OPENSSL
693         destruct_ssl();
694 #endif
695 }
696
697
698
699 pid_t current_child;
700 void graceful_shutdown(int signum) {
701         kill(current_child, signum);
702         unlink(file_pid_file);
703         exit(0);
704 }
705
706 int nFireUps = 0;
707 int nFireUpsNonRestart = 0;
708 pid_t ForkedPid = 1;
709
710 /*
711  * Start running as a daemon.
712  */
713 void start_daemon(int unused) {
714         int status = 0;
715         pid_t child = 0;
716         FILE *fp;
717         int do_restart = 0;
718         current_child = 0;
719
720         //if (chdir(ctdl_run_dir) != 0) {
721                 //syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
722         //}
723
724         /* Close stdin/stdout/stderr and replace them with /dev/null.
725          * We don't just call close() because we don't want these fd's
726          * to be reused for other files.
727          */
728         child = fork();
729         if (child != 0) {
730                 exit(0);
731         }
732         
733         signal(SIGHUP, SIG_IGN);
734         signal(SIGINT, SIG_IGN);
735         signal(SIGQUIT, SIG_IGN);
736
737         setsid();
738         umask(0);
739         if (    (freopen("/dev/null", "r", stdin) != stdin) || 
740                 (freopen("/dev/null", "w", stdout) != stdout) || 
741                 (freopen("/dev/null", "w", stderr) != stderr)
742         ) {
743                 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
744         }
745
746         do {
747                 current_child = fork();
748                 signal(SIGTERM, graceful_shutdown);
749                 if (current_child < 0) {
750                         perror("fork");
751                         exit(errno);
752                 }
753                 else if (current_child == 0) {
754                         return; /* continue starting citadel. */
755                 }
756                 else {
757                         fp = fopen(file_pid_file, "w");
758                         if (fp != NULL) {
759                                 fprintf(fp, ""F_PID_T"\n", getpid());
760                                 fclose(fp);
761                         }
762                         waitpid(current_child, &status, 0);
763                 }
764                 nFireUpsNonRestart = nFireUps;
765                 
766                 /* Exit code 0 means the watcher should exit */
767                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
768                         do_restart = 0;
769                 }
770
771                 /* Exit code 101-109 means the watcher should exit */
772                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
773                         do_restart = 0;
774                 }
775
776                 /* Any other exit code, or no exit code, means we should restart. */
777                 else {
778                         do_restart = 1;
779                         nFireUps++;
780                         ForkedPid = current_child;
781                 }
782
783         } while (do_restart);
784
785         unlink(file_pid_file);
786         exit(WEXITSTATUS(status));
787 }
788
789
790 void checkcrash(void) {
791         if (nFireUpsNonRestart != nFireUps) {
792                 StrBuf *CrashMail;
793                 CrashMail = NewStrBuf();
794                 syslog(LOG_ALERT, "sysdep: posting crash message");
795                 StrBufPrintf(CrashMail, 
796                         " \n"
797                         " The Citadel server process (citserver) terminated unexpectedly."
798                         "\n \n"
799                         " This could be the result of a bug in the server program, or some external "
800                         "factor.\n \n"
801                         " You can obtain more information about this by enabling core dumps.\n \n"
802                         " For more information, please see:\n \n"
803                         " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
804                         "\n \n"
805
806                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
807                         ,
808                         ctdl_run_dir, ForkedPid);
809                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
810                 FreeStrBuf(&CrashMail);
811         }
812 }
813
814
815 /*
816  * Generic routine to convert a login name to a full name (gecos)
817  * Returns nonzero if a conversion took place
818  */
819 int convert_login(char NameToConvert[]) {
820         struct passwd *pw;
821         unsigned int a;
822
823         pw = getpwnam(NameToConvert);
824         if (pw == NULL) {
825                 return(0);
826         }
827         else {
828                 strcpy(NameToConvert, pw->pw_gecos);
829                 for (a=0; a<strlen(NameToConvert); ++a) {
830                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
831                 }
832                 return(1);
833         }
834 }
835
836
837 void HuntBadSession(void) {
838         int highest;
839         CitContext *ptr;
840         fd_set readfds;
841         struct timeval tv;
842         struct ServiceFunctionHook *serviceptr;
843
844         /* Next, add all of the client sockets. */
845         begin_critical_section(S_SESSION_TABLE);
846         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
847                 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
848                         continue;
849                 /* Initialize the fdset. */
850                 FD_ZERO(&readfds);
851                 highest = 0;
852                 tv.tv_sec = 0;          /* wake up every second if no input */
853                 tv.tv_usec = 0;
854
855                 /* Don't select on dead sessions, only truly idle ones */
856                 if (    (ptr->state == CON_IDLE)
857                         && (ptr->kill_me == 0)
858                         && (ptr->client_socket > 0)
859                 ) {
860                         FD_SET(ptr->client_socket, &readfds);
861                         if (ptr->client_socket > highest)
862                                 highest = ptr->client_socket;
863                         
864                         if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
865                         {
866                                 /* Gotcha! */
867                                 syslog(LOG_ERR,
868                                        "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
869                                         ptr->cs_pid,
870                                         ptr->client_socket,
871                                         ptr->curr_user,
872                                         ptr->cs_host,
873                                         ptr->cs_addr
874                                 );
875                                 ptr->kill_me = 1;
876                                 ptr->client_socket = -1;
877                                 break;
878                         }
879                 }
880         }
881         end_critical_section(S_SESSION_TABLE);
882
883         /* First, add the various master sockets to the fdset. */
884         for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
885
886                 /* Initialize the fdset. */
887                 highest = 0;
888                 tv.tv_sec = 0;          /* wake up every second if no input */
889                 tv.tv_usec = 0;
890
891                 FD_SET(serviceptr->msock, &readfds);
892                 if (serviceptr->msock > highest) {
893                         highest = serviceptr->msock;
894                 }
895                 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
896                     (errno == EBADF))
897                 {
898                         /* Gotcha! server socket dead? commit suicide! */
899                         syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
900                         server_shutting_down = 1;
901                         break;
902                 }
903         }
904 }
905
906
907 /* 
908  * This loop just keeps going and going and going...
909  */
910 void *worker_thread(void *blah) {
911         int highest;
912         CitContext *ptr;
913         CitContext *bind_me = NULL;
914         fd_set readfds;
915         int retval = 0;
916         struct timeval tv;
917         int force_purge = 0;
918         struct ServiceFunctionHook *serviceptr;
919         int ssock;                      /* Descriptor for client socket */
920         CitContext *con = NULL;         /* Temporary context pointer */
921         int i;
922
923         pthread_mutex_lock(&ThreadCountMutex);
924         ++num_workers;
925         pthread_mutex_unlock(&ThreadCountMutex);
926
927         while (!server_shutting_down) {
928
929                 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
930                 cdb_check_handles();
931 do_select:      force_purge = 0;
932                 bind_me = NULL;         /* Which session shall we handle? */
933
934                 /* Initialize the fdset. */
935                 FD_ZERO(&readfds);
936                 highest = 0;
937
938                 /* First, add the various master sockets to the fdset. */
939                 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
940                         FD_SET(serviceptr->msock, &readfds);
941                         if (serviceptr->msock > highest) {
942                                 highest = serviceptr->msock;
943                         }
944                 }
945
946                 /* Next, add all of the client sockets. */
947                 begin_critical_section(S_SESSION_TABLE);
948                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
949                         if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
950                             continue;
951
952                         /* Don't select on dead sessions, only truly idle ones */
953                         if (    (ptr->state == CON_IDLE)
954                                 && (ptr->kill_me == 0)
955                                 && (ptr->client_socket > 0)
956                         ) {
957                                 FD_SET(ptr->client_socket, &readfds);
958                                 if (ptr->client_socket > highest)
959                                         highest = ptr->client_socket;
960                         }
961                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
962                                 bind_me = ptr;
963                                 ptr->state = CON_EXECUTING;
964                                 break;
965                         }
966                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
967                                 bind_me = ptr;
968                                 ptr->state = CON_STARTING;
969                                 break;
970                         }
971                 }
972                 end_critical_section(S_SESSION_TABLE);
973
974                 if (bind_me) {
975                         goto SKIP_SELECT;
976                 }
977
978                 /* If we got this far, it means that there are no sessions
979                  * which a previous thread marked for attention, so we go
980                  * ahead and get ready to select().
981                  */
982
983                 if (!server_shutting_down) {
984                         tv.tv_sec = 1;          /* wake up every second if no input */
985                         tv.tv_usec = 0;
986                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
987                 }
988                 else {
989                         --num_workers;
990                         return NULL;
991                 }
992
993                 /* Now figure out who made this select() unblock.
994                  * First, check for an error or exit condition.
995                  */
996                 if (retval < 0) {
997                         if (errno == EBADF) {
998                                 syslog(LOG_ERR, "sysdep: select() failed: %m");
999                                 HuntBadSession();
1000                                 goto do_select;
1001                         }
1002                         if (errno != EINTR) {
1003                                 syslog(LOG_ERR, "sysdep: exiting: %m");
1004                                 server_shutting_down = 1;
1005                                 continue;
1006                         } else {
1007                                 if (server_shutting_down) {
1008                                         --num_workers;
1009                                         return(NULL);
1010                                 }
1011                                 goto do_select;
1012                         }
1013                 }
1014                 else if (retval == 0) {
1015                         if (server_shutting_down) {
1016                                 --num_workers;
1017                                 return(NULL);
1018                         }
1019                 }
1020
1021                 /* Next, check to see if it's a new client connecting on a master socket. */
1022
1023                 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1024
1025                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1026                                 ssock = accept(serviceptr->msock, NULL, 0);
1027                                 if (ssock >= 0) {
1028                                         syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1029
1030                                         /* The master socket is non-blocking but the client
1031                                          * sockets need to be blocking, otherwise certain
1032                                          * operations barf on FreeBSD.  Not a fatal error.
1033                                          */
1034                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1035                                                 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1036                                         }
1037
1038                                         /* New context will be created already
1039                                          * set up in the CON_EXECUTING state.
1040                                          */
1041                                         con = CreateNewContext();
1042
1043                                         /* Assign our new socket number to it. */
1044                                         con->tcp_port = serviceptr->tcp_port;
1045                                         con->client_socket = ssock;
1046                                         con->h_command_function = serviceptr->h_command_function;
1047                                         con->h_async_function = serviceptr->h_async_function;
1048                                         con->h_greeting_function = serviceptr->h_greeting_function;
1049                                         con->ServiceName = serviceptr->ServiceName;
1050                                         
1051                                         /* Connections on a local client are always from the same host */
1052                                         if (serviceptr->sockpath != NULL) {
1053                                                 con->is_local_client = 1;
1054                                         }
1055         
1056                                         /* Set the SO_REUSEADDR socket option */
1057                                         i = 1;
1058                                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1059                                         con->state = CON_GREETING;
1060                                         retval--;
1061                                         if (retval == 0)
1062                                                 break;
1063                                 }
1064                         }
1065                 }
1066
1067                 /* It must be a client socket.  Find a context that has data
1068                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1069                  * active sockets other than our chosen one are marked as
1070                  * CON_READY so the next thread that comes around can just bind
1071                  * to one without having to select() again.
1072                  */
1073                 begin_critical_section(S_SESSION_TABLE);
1074                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1075                         int checkfd = ptr->client_socket;
1076                         if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1077                                 if (FD_ISSET(checkfd, &readfds)) {
1078                                         ptr->input_waiting = 1;
1079                                         if (!bind_me) {
1080                                                 bind_me = ptr;  /* I choose you! */
1081                                                 bind_me->state = CON_EXECUTING;
1082                                         }
1083                                         else {
1084                                                 ptr->state = CON_READY;
1085                                         }
1086                                 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1087                                         if (!bind_me) {
1088                                                 bind_me = ptr;  /* I choose you! */
1089                                                 bind_me->state = CON_EXECUTING;
1090                                         }
1091                                         else {
1092                                                 ptr->state = CON_READY;
1093                                         }
1094                                 }
1095                         }
1096                 }
1097                 end_critical_section(S_SESSION_TABLE);
1098
1099 SKIP_SELECT:
1100                 /* We're bound to a session */
1101                 pthread_mutex_lock(&ThreadCountMutex);
1102                 ++active_workers;
1103                 pthread_mutex_unlock(&ThreadCountMutex);
1104
1105                 if (bind_me != NULL) {
1106                         become_session(bind_me);
1107
1108                         if (bind_me->state == CON_STARTING) {
1109                                 bind_me->state = CON_EXECUTING;
1110                                 begin_session(bind_me);
1111                                 bind_me->h_greeting_function();
1112                         }
1113                         /* If the client has sent a command, execute it. */
1114                         if (CC->input_waiting) {
1115                                 CC->h_command_function();
1116
1117                                 while (HaveMoreLinesWaiting(CC))
1118                                        CC->h_command_function();
1119
1120                                 CC->input_waiting = 0;
1121                         }
1122
1123                         /* If there are asynchronous messages waiting and the client supports it, do those now */
1124                         if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1125                                 CC->h_async_function();
1126                                 CC->async_waiting = 0;
1127                         }
1128
1129                         force_purge = CC->kill_me;
1130                         become_session(NULL);
1131                         bind_me->state = CON_IDLE;
1132                 }
1133
1134                 dead_session_purge(force_purge);
1135                 do_housekeeping();
1136
1137                 pthread_mutex_lock(&ThreadCountMutex);
1138                 --active_workers;
1139                 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1140                     (num_workers > CtdlGetConfigInt("c_min_workers")))
1141                 {
1142                         num_workers--;
1143                         pthread_mutex_unlock(&ThreadCountMutex);
1144                         return (NULL);
1145                 }
1146                 pthread_mutex_unlock(&ThreadCountMutex);
1147         }
1148
1149         /* If control reaches this point, the server is shutting down */
1150         pthread_mutex_lock(&ThreadCountMutex);
1151         --num_workers;
1152         pthread_mutex_unlock(&ThreadCountMutex);
1153         return(NULL);
1154 }
1155
1156
1157 /*
1158  * SyslogFacility()
1159  * Translate text facility name to syslog.h defined value.
1160  */
1161 int SyslogFacility(char *name)
1162 {
1163         int i;
1164         struct
1165         {
1166                 int facility;
1167                 char *name;
1168         }   facTbl[] =
1169         {
1170                 {   LOG_KERN,   "kern"          },
1171                 {   LOG_USER,   "user"          },
1172                 {   LOG_MAIL,   "mail"          },
1173                 {   LOG_DAEMON, "daemon"        },
1174                 {   LOG_AUTH,   "auth"          },
1175                 {   LOG_SYSLOG, "syslog"        },
1176                 {   LOG_LPR,    "lpr"           },
1177                 {   LOG_NEWS,   "news"          },
1178                 {   LOG_UUCP,   "uucp"          },
1179                 {   LOG_LOCAL0, "local0"        },
1180                 {   LOG_LOCAL1, "local1"        },
1181                 {   LOG_LOCAL2, "local2"        },
1182                 {   LOG_LOCAL3, "local3"        },
1183                 {   LOG_LOCAL4, "local4"        },
1184                 {   LOG_LOCAL5, "local5"        },
1185                 {   LOG_LOCAL6, "local6"        },
1186                 {   LOG_LOCAL7, "local7"        },
1187                 {   0,            NULL          }
1188         };
1189         for(i = 0; facTbl[i].name != NULL; i++) {
1190                 if(!strcasecmp(name, facTbl[i].name))
1191                         return facTbl[i].facility;
1192         }
1193         return LOG_DAEMON;
1194 }