Removed an old debugging harness
[citadel.git] / 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 {
548         if ((CCC->kill_me != 0) ||
549             ( (CCC->RecvBuf.ReadWritePointer == NULL) && 
550               (StrLength(CCC->RecvBuf.Buf) == 0) && 
551               (CCC->client_socket != -1)) )
552                 return 0;
553         else
554                 return 1;
555 }
556
557
558 /*
559  * Read data from the client socket with default timeout.
560  * (This is implemented in terms of client_read_to() and could be
561  * justifiably moved out of sysdep.c)
562  */
563 INLINE int client_read(char *buf, int bytes)
564 {
565         return(client_read_to(buf, bytes, CtdlGetConfigInt("c_sleeping")));
566 }
567
568 int CtdlClientGetLine(StrBuf *Target)
569 {
570         CitContext *CCC=CC;
571         const char *Error;
572         int rc;
573
574         FlushStrBuf(Target);
575 #ifdef HAVE_OPENSSL
576         if (CCC->redirect_ssl) {
577                 rc = client_readline_sslbuffer(Target, CCC->RecvBuf.Buf, &CCC->RecvBuf.ReadWritePointer, 1);
578                 return rc;
579         }
580         else 
581 #endif
582         {
583                 rc = StrBufTCP_read_buffered_line_fast(Target, 
584                                                        CCC->RecvBuf.Buf,
585                                                        &CCC->RecvBuf.ReadWritePointer,
586                                                        &CCC->client_socket,
587                                                        5,
588                                                        1,
589                                                        &Error
590                 );
591                 return rc;
592         }
593 }
594
595
596 /*
597  * client_getln()   ...   Get a LF-terminated line of text from the client.
598  * (This is implemented in terms of client_read() and could be
599  * justifiably moved out of sysdep.c)
600  */
601 int client_getln(char *buf, int bufsize)
602 {
603         int i, retval;
604         CitContext *CCC=CC;
605         const char *pCh;
606
607         retval = CtdlClientGetLine(CCC->MigrateBuf);
608         if (retval < 0)
609           return(retval >= 0);
610
611
612         i = StrLength(CCC->MigrateBuf);
613         pCh = ChrPtr(CCC->MigrateBuf);
614         /* Strip the trailing LF, and the trailing CR if present.
615          */
616         if (bufsize <= i)
617                 i = bufsize - 1;
618         while ( (i > 0)
619                 && ( (pCh[i - 1]==13)
620                      || ( pCh[i - 1]==10)) ) {
621                 i--;
622         }
623         memcpy(buf, pCh, i);
624         buf[i] = 0;
625
626         FlushStrBuf(CCC->MigrateBuf);
627         if (retval < 0) {
628                 safestrncpy(&buf[i], "000", bufsize - i);
629         }
630         return(retval >= 0);
631 }
632
633
634 /*
635  * Cleanup any contexts that are left lying around
636  */
637
638
639 void close_masters (void)
640 {
641         struct ServiceFunctionHook *serviceptr;
642         const char *Text;
643
644         /*
645          * close all protocol master sockets
646          */
647         for (serviceptr = ServiceHookTable; serviceptr != NULL;
648             serviceptr = serviceptr->next ) {
649
650                 if (serviceptr->tcp_port > 0)
651                 {
652                         if (serviceptr->msock == -1) {
653                                 Text = "not closing again";
654                         }
655                         else {
656                                 Text = "Closing";
657                         }
658                         syslog(LOG_INFO, "sysdep: %s %d listener on port %d",
659                                Text,
660                                serviceptr->msock,
661                                serviceptr->tcp_port
662                         );
663                         serviceptr->tcp_port = 0;
664                 }
665                 
666                 if (serviceptr->sockpath != NULL)
667                 {
668                         if (serviceptr->msock == -1) {
669                                 Text = "not closing again";
670                         }
671                         else {
672                                 Text = "Closing";
673                         }
674                         syslog(LOG_INFO, "sysdep: %s %d listener on '%s'",
675                                Text,
676                                serviceptr->msock,
677                                serviceptr->sockpath
678                         );
679                 }
680
681                 if (serviceptr->msock != -1)
682                 {
683                         close(serviceptr->msock);
684                         serviceptr->msock = -1;
685                 }
686
687                 /* If it's a Unix domain socket, remove the file. */
688                 if (serviceptr->sockpath != NULL) {
689                         unlink(serviceptr->sockpath);
690                         serviceptr->sockpath = NULL;
691                 }
692         }
693 }
694
695
696 /*
697  * The system-dependent part of master_cleanup() - close the master socket.
698  */
699 void sysdep_master_cleanup(void) {
700         
701         close_masters();
702         
703         context_cleanup();
704         
705 #ifdef HAVE_OPENSSL
706         destruct_ssl();
707 #endif
708         CtdlDestroyProtoHooks();
709         CtdlDestroyDeleteHooks();
710         CtdlDestroyXmsgHooks();
711         CtdlDestroyUserHooks();
712         CtdlDestroyMessageHook();
713         CtdlDestroyCleanupHooks();
714         CtdlDestroyFixedOutputHooks();  
715         CtdlDestroySessionHooks();
716         CtdlDestroyServiceHook();
717         CtdlDestroyRoomHooks();
718         CtdlDestroySearchHooks();
719 }
720
721
722
723 pid_t current_child;
724 void graceful_shutdown(int signum) {
725         kill(current_child, signum);
726         unlink(file_pid_file);
727         exit(0);
728 }
729
730 int nFireUps = 0;
731 int nFireUpsNonRestart = 0;
732 pid_t ForkedPid = 1;
733
734 /*
735  * Start running as a daemon.
736  */
737 void start_daemon(int unused) {
738         int status = 0;
739         pid_t child = 0;
740         FILE *fp;
741         int do_restart = 0;
742         current_child = 0;
743
744         //if (chdir(ctdl_run_dir) != 0) {
745                 //syslog(LOG_ERR, "%s: %m", ctdl_run_dir);
746         //}
747
748         /* Close stdin/stdout/stderr and replace them with /dev/null.
749          * We don't just call close() because we don't want these fd's
750          * to be reused for other files.
751          */
752         child = fork();
753         if (child != 0) {
754                 exit(0);
755         }
756         
757         signal(SIGHUP, SIG_IGN);
758         signal(SIGINT, SIG_IGN);
759         signal(SIGQUIT, SIG_IGN);
760
761         setsid();
762         umask(0);
763         if (    (freopen("/dev/null", "r", stdin) != stdin) || 
764                 (freopen("/dev/null", "w", stdout) != stdout) || 
765                 (freopen("/dev/null", "w", stderr) != stderr)
766         ) {
767                 syslog(LOG_ERR, "sysdep: unable to reopen stdio: %m");
768         }
769
770         do {
771                 current_child = fork();
772                 signal(SIGTERM, graceful_shutdown);
773                 if (current_child < 0) {
774                         perror("fork");
775                         exit(errno);
776                 }
777                 else if (current_child == 0) {
778                         return; /* continue starting citadel. */
779                 }
780                 else {
781                         fp = fopen(file_pid_file, "w");
782                         if (fp != NULL) {
783                                 fprintf(fp, ""F_PID_T"\n", getpid());
784                                 fclose(fp);
785                         }
786                         waitpid(current_child, &status, 0);
787                 }
788                 nFireUpsNonRestart = nFireUps;
789                 
790                 /* Exit code 0 means the watcher should exit */
791                 if (WIFEXITED(status) && (WEXITSTATUS(status) == CTDLEXIT_SHUTDOWN)) {
792                         do_restart = 0;
793                 }
794
795                 /* Exit code 101-109 means the watcher should exit */
796                 else if (WIFEXITED(status) && (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109)) {
797                         do_restart = 0;
798                 }
799
800                 /* Any other exit code, or no exit code, means we should restart. */
801                 else {
802                         do_restart = 1;
803                         nFireUps++;
804                         ForkedPid = current_child;
805                 }
806
807         } while (do_restart);
808
809         unlink(file_pid_file);
810         exit(WEXITSTATUS(status));
811 }
812
813
814
815 void checkcrash(void)
816 {
817         if (nFireUpsNonRestart != nFireUps)
818         {
819                 StrBuf *CrashMail;
820                 CrashMail = NewStrBuf();
821                 syslog(LOG_ALERT, "sysdep: posting crash message");
822                 StrBufPrintf(CrashMail, 
823                         " \n"
824                         " The Citadel server process (citserver) terminated unexpectedly."
825                         "\n \n"
826                         " This could be the result of a bug in the server program, or some external "
827                         "factor.\n \n"
828                         " You can obtain more information about this by enabling core dumps.\n \n"
829                         " For more information, please see:\n \n"
830                         " http://citadel.org/doku.php?id=faq:mastering_your_os:gdb#how.do.i.make.my.system.produce.core-files"
831                         "\n \n"
832
833                         " If you have already done this, the core dump is likely to be found at %score.%d\n"
834                         ,
835                         ctdl_run_dir, ForkedPid);
836                 CtdlAideMessage(ChrPtr(CrashMail), "Citadel server process terminated unexpectedly");
837                 FreeStrBuf(&CrashMail);
838         }
839 }
840
841
842 /*
843  * Generic routine to convert a login name to a full name (gecos)
844  * Returns nonzero if a conversion took place
845  */
846 int convert_login(char NameToConvert[]) {
847         struct passwd *pw;
848         unsigned int a;
849
850         pw = getpwnam(NameToConvert);
851         if (pw == NULL) {
852                 return(0);
853         }
854         else {
855                 strcpy(NameToConvert, pw->pw_gecos);
856                 for (a=0; a<strlen(NameToConvert); ++a) {
857                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
858                 }
859                 return(1);
860         }
861 }
862
863
864
865 void HuntBadSession(void)
866 {
867         int highest;
868         CitContext *ptr;
869         fd_set readfds;
870         struct timeval tv;
871         struct ServiceFunctionHook *serviceptr;
872
873         /* Next, add all of the client sockets. */
874         begin_critical_section(S_SESSION_TABLE);
875         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
876                 if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
877                         continue;
878                 /* Initialize the fdset. */
879                 FD_ZERO(&readfds);
880                 highest = 0;
881                 tv.tv_sec = 0;          /* wake up every second if no input */
882                 tv.tv_usec = 0;
883
884                 /* Don't select on dead sessions, only truly idle ones */
885                 if (    (ptr->state == CON_IDLE)
886                         && (ptr->kill_me == 0)
887                         && (ptr->client_socket > 0)
888                 ) {
889                         FD_SET(ptr->client_socket, &readfds);
890                         if (ptr->client_socket > highest)
891                                 highest = ptr->client_socket;
892                         
893                         if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) && (errno == EBADF))
894                         {
895                                 /* Gotcha! */
896                                 syslog(LOG_ERR,
897                                        "sysdep: killing session CC[%d] bad FD: [%d] User[%s] Host[%s:%s]",
898                                         ptr->cs_pid,
899                                         ptr->client_socket,
900                                         ptr->curr_user,
901                                         ptr->cs_host,
902                                         ptr->cs_addr
903                                 );
904                                 ptr->kill_me = 1;
905                                 ptr->client_socket = -1;
906                                 break;
907                         }
908                 }
909         }
910         end_critical_section(S_SESSION_TABLE);
911
912         /* First, add the various master sockets to the fdset. */
913         for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
914
915                 /* Initialize the fdset. */
916                 highest = 0;
917                 tv.tv_sec = 0;          /* wake up every second if no input */
918                 tv.tv_usec = 0;
919
920                 FD_SET(serviceptr->msock, &readfds);
921                 if (serviceptr->msock > highest) {
922                         highest = serviceptr->msock;
923                 }
924                 if ((select(highest + 1, &readfds, NULL, NULL, &tv) < 0) &&
925                     (errno == EBADF))
926                 {
927                         /* Gotcha! server socket dead? commit suicide! */
928                         syslog(LOG_ERR, "sysdep: found bad FD: %d and its a server socket! Shutting Down!", serviceptr->msock);
929                         server_shutting_down = 1;
930                         break;
931                 }
932         }
933 }
934
935
936 /* 
937  * This loop just keeps going and going and going...
938  */
939 void *worker_thread(void *blah) {
940         int highest;
941         CitContext *ptr;
942         CitContext *bind_me = NULL;
943         fd_set readfds;
944         int retval = 0;
945         struct timeval tv;
946         int force_purge = 0;
947         struct ServiceFunctionHook *serviceptr;
948         int ssock;                      /* Descriptor for client socket */
949         CitContext *con = NULL;         /* Temporary context pointer */
950         int i;
951
952         pthread_mutex_lock(&ThreadCountMutex);
953         ++num_workers;
954         pthread_mutex_unlock(&ThreadCountMutex);
955
956         while (!server_shutting_down) {
957
958                 /* make doubly sure we're not holding any stale db handles * which might cause a deadlock */
959                 cdb_check_handles();
960 do_select:      force_purge = 0;
961                 bind_me = NULL;         /* Which session shall we handle? */
962
963                 /* Initialize the fdset. */
964                 FD_ZERO(&readfds);
965                 highest = 0;
966
967                 /* First, add the various master sockets to the fdset. */
968                 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
969                         FD_SET(serviceptr->msock, &readfds);
970                         if (serviceptr->msock > highest) {
971                                 highest = serviceptr->msock;
972                         }
973                 }
974
975                 /* Next, add all of the client sockets. */
976                 begin_critical_section(S_SESSION_TABLE);
977                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
978                         if ((ptr->state == CON_SYS) && (ptr->client_socket == 0))
979                             continue;
980
981                         /* Don't select on dead sessions, only truly idle ones */
982                         if (    (ptr->state == CON_IDLE)
983                                 && (ptr->kill_me == 0)
984                                 && (ptr->client_socket > 0)
985                         ) {
986                                 FD_SET(ptr->client_socket, &readfds);
987                                 if (ptr->client_socket > highest)
988                                         highest = ptr->client_socket;
989                         }
990                         if ((bind_me == NULL) && (ptr->state == CON_READY)) {
991                                 bind_me = ptr;
992                                 ptr->state = CON_EXECUTING;
993                                 break;
994                         }
995                         if ((bind_me == NULL) && (ptr->state == CON_GREETING)) {
996                                 bind_me = ptr;
997                                 ptr->state = CON_STARTING;
998                                 break;
999                         }
1000                 }
1001                 end_critical_section(S_SESSION_TABLE);
1002
1003                 if (bind_me) {
1004                         goto SKIP_SELECT;
1005                 }
1006
1007                 /* If we got this far, it means that there are no sessions
1008                  * which a previous thread marked for attention, so we go
1009                  * ahead and get ready to select().
1010                  */
1011
1012                 if (!server_shutting_down) {
1013                         tv.tv_sec = 1;          /* wake up every second if no input */
1014                         tv.tv_usec = 0;
1015                         retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1016                 }
1017                 else {
1018                         --num_workers;
1019                         return NULL;
1020                 }
1021
1022                 /* Now figure out who made this select() unblock.
1023                  * First, check for an error or exit condition.
1024                  */
1025                 if (retval < 0) {
1026                         if (errno == EBADF) {
1027                                 syslog(LOG_ERR, "sysdep: select() failed: %m");
1028                                 HuntBadSession();
1029                                 goto do_select;
1030                         }
1031                         if (errno != EINTR) {
1032                                 syslog(LOG_ERR, "sysdep: exiting: %m");
1033                                 server_shutting_down = 1;
1034                                 continue;
1035                         } else {
1036                                 if (server_shutting_down) {
1037                                         --num_workers;
1038                                         return(NULL);
1039                                 }
1040                                 goto do_select;
1041                         }
1042                 }
1043                 else if (retval == 0) {
1044                         if (server_shutting_down) {
1045                                 --num_workers;
1046                                 return(NULL);
1047                         }
1048                 }
1049
1050                 /* Next, check to see if it's a new client connecting on a master socket. */
1051
1052                 else if ((retval > 0) && (!server_shutting_down)) for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next) {
1053
1054                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1055                                 ssock = accept(serviceptr->msock, NULL, 0);
1056                                 if (ssock >= 0) {
1057                                         syslog(LOG_DEBUG, "sysdep: new client socket %d", ssock);
1058
1059                                         /* The master socket is non-blocking but the client
1060                                          * sockets need to be blocking, otherwise certain
1061                                          * operations barf on FreeBSD.  Not a fatal error.
1062                                          */
1063                                         if (fcntl(ssock, F_SETFL, 0) < 0) {
1064                                                 syslog(LOG_ERR, "sysdep: Can't set socket to blocking: %m");
1065                                         }
1066
1067                                         /* New context will be created already
1068                                          * set up in the CON_EXECUTING state.
1069                                          */
1070                                         con = CreateNewContext();
1071
1072                                         /* Assign our new socket number to it. */
1073                                         con->tcp_port = serviceptr->tcp_port;
1074                                         con->client_socket = ssock;
1075                                         con->h_command_function = serviceptr->h_command_function;
1076                                         con->h_async_function = serviceptr->h_async_function;
1077                                         con->h_greeting_function = serviceptr->h_greeting_function;
1078                                         con->ServiceName = serviceptr->ServiceName;
1079                                         
1080                                         /* Connections on a local client are always from the same host */
1081                                         if (serviceptr->sockpath != NULL) {
1082                                                 con->is_local_client = 1;
1083                                         }
1084         
1085                                         /* Set the SO_REUSEADDR socket option */
1086                                         i = 1;
1087                                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1088                                         con->state = CON_GREETING;
1089                                         retval--;
1090                                         if (retval == 0)
1091                                                 break;
1092                                 }
1093                         }
1094                 }
1095
1096                 /* It must be a client socket.  Find a context that has data
1097                  * waiting on its socket *and* is in the CON_IDLE state.  Any
1098                  * active sockets other than our chosen one are marked as
1099                  * CON_READY so the next thread that comes around can just bind
1100                  * to one without having to select() again.
1101                  */
1102                 begin_critical_section(S_SESSION_TABLE);
1103                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1104                         int checkfd = ptr->client_socket;
1105                         if ((checkfd != -1) && (ptr->state == CON_IDLE) ){
1106                                 if (FD_ISSET(checkfd, &readfds)) {
1107                                         ptr->input_waiting = 1;
1108                                         if (!bind_me) {
1109                                                 bind_me = ptr;  /* I choose you! */
1110                                                 bind_me->state = CON_EXECUTING;
1111                                         }
1112                                         else {
1113                                                 ptr->state = CON_READY;
1114                                         }
1115                                 } else if ((ptr->is_async) && (ptr->async_waiting) && (ptr->h_async_function)) {
1116                                         if (!bind_me) {
1117                                                 bind_me = ptr;  /* I choose you! */
1118                                                 bind_me->state = CON_EXECUTING;
1119                                         }
1120                                         else {
1121                                                 ptr->state = CON_READY;
1122                                         }
1123                                 }
1124                         }
1125                 }
1126                 end_critical_section(S_SESSION_TABLE);
1127
1128 SKIP_SELECT:
1129                 /* We're bound to a session */
1130                 pthread_mutex_lock(&ThreadCountMutex);
1131                 ++active_workers;
1132                 pthread_mutex_unlock(&ThreadCountMutex);
1133
1134                 if (bind_me != NULL) {
1135                         become_session(bind_me);
1136
1137                         if (bind_me->state == CON_STARTING) {
1138                                 bind_me->state = CON_EXECUTING;
1139                                 begin_session(bind_me);
1140                                 bind_me->h_greeting_function();
1141                         }
1142                         /* If the client has sent a command, execute it. */
1143                         if (CC->input_waiting) {
1144                                 CC->h_command_function();
1145
1146                                 while (HaveMoreLinesWaiting(CC))
1147                                        CC->h_command_function();
1148
1149                                 CC->input_waiting = 0;
1150                         }
1151
1152                         /* If there are asynchronous messages waiting and the client supports it, do those now */
1153                         if ((CC->is_async) && (CC->async_waiting) && (CC->h_async_function != NULL)) {
1154                                 CC->h_async_function();
1155                                 CC->async_waiting = 0;
1156                         }
1157
1158                         force_purge = CC->kill_me;
1159                         become_session(NULL);
1160                         bind_me->state = CON_IDLE;
1161                 }
1162
1163                 dead_session_purge(force_purge);
1164                 do_housekeeping();
1165
1166                 pthread_mutex_lock(&ThreadCountMutex);
1167                 --active_workers;
1168                 if ((active_workers + CtdlGetConfigInt("c_min_workers") < num_workers) &&
1169                     (num_workers > CtdlGetConfigInt("c_min_workers")))
1170                 {
1171                         num_workers--;
1172                         pthread_mutex_unlock(&ThreadCountMutex);
1173                         return (NULL);
1174                 }
1175                 pthread_mutex_unlock(&ThreadCountMutex);
1176         }
1177
1178         /* If control reaches this point, the server is shutting down */
1179         pthread_mutex_lock(&ThreadCountMutex);
1180         --num_workers;
1181         pthread_mutex_unlock(&ThreadCountMutex);
1182         return(NULL);
1183 }
1184
1185
1186 /*
1187  * SyslogFacility()
1188  * Translate text facility name to syslog.h defined value.
1189  */
1190 int SyslogFacility(char *name)
1191 {
1192         int i;
1193         struct
1194         {
1195                 int facility;
1196                 char *name;
1197         }   facTbl[] =
1198         {
1199                 {   LOG_KERN,   "kern"          },
1200                 {   LOG_USER,   "user"          },
1201                 {   LOG_MAIL,   "mail"          },
1202                 {   LOG_DAEMON, "daemon"        },
1203                 {   LOG_AUTH,   "auth"          },
1204                 {   LOG_SYSLOG, "syslog"        },
1205                 {   LOG_LPR,    "lpr"           },
1206                 {   LOG_NEWS,   "news"          },
1207                 {   LOG_UUCP,   "uucp"          },
1208                 {   LOG_LOCAL0, "local0"        },
1209                 {   LOG_LOCAL1, "local1"        },
1210                 {   LOG_LOCAL2, "local2"        },
1211                 {   LOG_LOCAL3, "local3"        },
1212                 {   LOG_LOCAL4, "local4"        },
1213                 {   LOG_LOCAL5, "local5"        },
1214                 {   LOG_LOCAL6, "local6"        },
1215                 {   LOG_LOCAL7, "local7"        },
1216                 {   0,            NULL          }
1217         };
1218         for(i = 0; facTbl[i].name != NULL; i++) {
1219                 if(!strcasecmp(name, facTbl[i].name))
1220                         return facTbl[i].facility;
1221         }
1222         return LOG_DAEMON;
1223 }