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