* Finished (mostly) the Sleepycat DB backend ... added transaction logging
[citadel.git] / citadel / sysdep.c
1 /*
2  * $Id$
3  *
4  * Citadel/UX "system dependent" stuff.
5  * See copyright.txt for copyright information.
6  *
7  * Here's where we (hopefully) have most parts of the Citadel server that
8  * would need to be altered to run the server in a non-POSIX environment.
9  * 
10  * If we ever port to a different platform and either have multiple
11  * variants of this file or simply load it up with #ifdefs.
12  *
13  */
14
15
16 #include "sysdep.h"
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <signal.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28 #include <limits.h>
29 #include <netinet/in.h>
30 #include <netdb.h>
31 #include <sys/un.h>
32 #include <string.h>
33 #include <pwd.h>
34 #include <errno.h>
35 #include <stdarg.h>
36 #include <syslog.h>
37 #include <grp.h>
38 #ifdef __GNUC__
39 #include <malloc.h>
40 #endif
41 #ifdef HAVE_PTHREAD_H
42 #include <pthread.h>
43 #endif
44 #include "citadel.h"
45 #include "server.h"
46 #include "sysdep_decls.h"
47 #include "citserver.h"
48 #include "support.h"
49 #include "config.h"
50 #include "database.h"
51 #include "housekeeping.h"
52 #include "dynloader.h"
53 #include "tools.h"
54
55 #ifdef HAVE_SYS_SELECT_H
56 #include <sys/select.h>
57 #endif
58
59 #ifndef HAVE_SNPRINTF
60 #include "snprintf.h"
61 #endif
62
63 #ifdef DEBUG_MEMORY_LEAKS
64 struct TheHeap *heap = NULL;
65 #endif
66
67 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
68 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
69
70 int verbosity = DEFAULT_VERBOSITY;              /* Logging level */
71
72 struct CitContext masterCC;
73 int rescan[2];                                  /* The Rescan Pipe */
74 time_t last_purge = 0;                          /* Last dead session purge */
75 int num_threads = 0;                            /* Current number of threads */
76 int num_sessions = 0;                           /* Current number of sessions */
77
78 fd_set masterfds;                               /* Master sockets etc. */
79 int masterhighest;
80
81 time_t last_timer = 0L;                         /* Last timer hook processing */
82
83
84 /*
85  * lprintf()  ...   Write logging information
86  */
87 void lprintf(int loglevel, const char *format, ...) {   
88         va_list arg_ptr;
89         char buf[512];
90   
91         va_start(arg_ptr, format);   
92         vsprintf(buf, format, arg_ptr);   
93         va_end(arg_ptr);   
94
95         if (loglevel <= verbosity) { 
96                 fprintf(stderr, "%s", buf);
97                 fflush(stderr);
98         }
99
100         PerformLogHooks(loglevel, buf);
101 }   
102
103
104
105 #ifdef DEBUG_MEMORY_LEAKS
106 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
107         void *ptr;
108         struct TheHeap *hptr;
109
110         ptr = malloc(tsize);
111         if (ptr == NULL) {
112                 lprintf(3, "DANGER!  mallok(%d) at %s:%d failed!\n",
113                         tsize, tfile, tline);
114                 return(NULL);
115         }
116
117         hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
118         strcpy(hptr->h_file, tfile);
119         hptr->h_line = tline;
120         hptr->next = heap;
121         hptr->h_ptr = ptr;
122         heap = hptr;
123         return ptr;
124 }
125
126 char *tracked_strdup(const char *orig, char *tfile, int tline) {
127         char *s;
128
129         s = tracked_malloc( (strlen(orig)+1), tfile, tline);
130         if (s == NULL) return NULL;
131
132         strcpy(s, orig);
133         return s;
134 }
135
136 void tracked_free(void *ptr) {
137         struct TheHeap *hptr, *freeme;
138
139         if (heap->h_ptr == ptr) {
140                 hptr = heap->next;
141                 free(heap);
142                 heap = hptr;
143         }
144         else {
145                 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
146                         if (hptr->next->h_ptr == ptr) {
147                                 freeme = hptr->next;
148                                 hptr->next = hptr->next->next;
149                                 free(freeme);
150                         }
151                 }
152         }
153
154         free(ptr);
155 }
156
157 void *tracked_realloc(void *ptr, size_t size) {
158         void *newptr;
159         struct TheHeap *hptr;
160         
161         newptr = realloc(ptr, size);
162
163         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
164                 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
165         }
166
167         return newptr;
168 }
169
170
171 void dump_tracked() {
172         struct TheHeap *hptr;
173
174         cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);    
175         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
176                 cprintf("%20s %5d\n",
177                         hptr->h_file, hptr->h_line);
178         }
179 #ifdef __GNUC__
180         malloc_stats();
181 #endif
182
183         cprintf("000\n");
184 }
185 #endif
186
187
188 /*
189  * We used to use master_cleanup() as a signal handler to shut down the server.
190  * however, master_cleanup() and the functions it calls do some things that
191  * aren't such a good idea to do from a signal handler: acquiring mutexes,
192  * playing with signal masks on BSDI systems, etc. so instead we install the
193  * following signal handler to set a global variable to inform the main loop
194  * that it's time to call master_cleanup() and exit.
195  */
196
197 static volatile int time_to_die = 0;
198
199 static RETSIGTYPE signal_cleanup(int signum) {
200         time_to_die = 1;
201 }
202
203
204 /*
205  * Some initialization stuff...
206  */
207 void init_sysdep(void) {
208         int a;
209
210         /* Set up a bunch of semaphores to be used for critical sections */
211         for (a=0; a<MAX_SEMAPHORES; ++a) {
212                 pthread_mutex_init(&Critters[a], NULL);
213         }
214
215         /*
216          * Set up a place to put thread-specific data.
217          * We only need a single pointer per thread - it points to the
218          * CitContext structure (in the ContextList linked list) of the
219          * session to which the calling thread is currently bound.
220          */
221         if (pthread_key_create(&MyConKey, NULL) != 0) {
222                 lprintf(1, "Can't create TSD key!!  %s\n", strerror(errno));
223         }
224
225         /*
226          * The action for unexpected signals and exceptions should be to
227          * call signal_cleanup() to gracefully shut down the server.
228          */
229         signal(SIGINT, signal_cleanup);
230         signal(SIGQUIT, signal_cleanup);
231         signal(SIGHUP, signal_cleanup);
232         signal(SIGTERM, signal_cleanup);
233
234         /*
235          * Do not shut down the server on broken pipe signals, otherwise the
236          * whole Citadel service would come down whenever a single client
237          * socket breaks.
238          */
239         signal(SIGPIPE, SIG_IGN);
240 }
241
242
243 /*
244  * Obtain a semaphore lock to begin a critical section.
245  */
246 void begin_critical_section(int which_one)
247 {
248         /* lprintf(9, "begin_critical_section(%d)\n", which_one); */
249         pthread_mutex_lock(&Critters[which_one]);
250 }
251
252 /*
253  * Release a semaphore lock to end a critical section.
254  */
255 void end_critical_section(int which_one)
256 {
257         /* lprintf(9, "end_critical_section(%d)\n", which_one); */
258         pthread_mutex_unlock(&Critters[which_one]);
259 }
260
261
262
263 /*
264  * This is a generic function to set up a master socket for listening on
265  * a TCP port.  The server shuts down if the bind fails.
266  *
267  */
268 int ig_tcp_server(int port_number, int queue_len)
269 {
270         struct sockaddr_in sin;
271         int s, i;
272         int actual_queue_len;
273
274         actual_queue_len = queue_len;
275         if (actual_queue_len < 5) actual_queue_len = 5;
276
277         memset(&sin, 0, sizeof(sin));
278         sin.sin_family = AF_INET;
279         sin.sin_addr.s_addr = INADDR_ANY;
280         sin.sin_port = htons((u_short)port_number);
281
282         s = socket(PF_INET, SOCK_STREAM,
283                 (getprotobyname("tcp")->p_proto));
284
285         if (s < 0) {
286                 lprintf(1, "citserver: Can't create a socket: %s\n",
287                         strerror(errno));
288                 return(-1);
289         }
290
291         i = 1;
292         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
293
294         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
295                 lprintf(1, "citserver: Can't bind: %s\n",
296                         strerror(errno));
297                 close(s);
298                 return(-1);
299         }
300
301         if (listen(s, actual_queue_len) < 0) {
302                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
303                 close(s);
304                 return(-1);
305         }
306
307         return(s);
308 }
309
310
311
312 /*
313  * Create a Unix domain socket and listen on it
314  */
315 int ig_uds_server(char *sockpath, int queue_len)
316 {
317         struct sockaddr_un addr;
318         int s;
319         int i;
320         int actual_queue_len;
321
322         actual_queue_len = queue_len;
323         if (actual_queue_len < 5) actual_queue_len = 5;
324
325         i = unlink(sockpath);
326         if (i != 0) if (errno != ENOENT) {
327                 lprintf(1, "citserver: can't unlink %s: %s\n",
328                         sockpath, strerror(errno));
329                 return(-1);
330         }
331
332         memset(&addr, 0, sizeof(addr));
333         addr.sun_family = AF_UNIX;
334         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
335
336         s = socket(AF_UNIX, SOCK_STREAM, 0);
337         if (s < 0) {
338                 lprintf(1, "citserver: Can't create a socket: %s\n",
339                         strerror(errno));
340                 return(-1);
341         }
342
343         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
344                 lprintf(1, "citserver: Can't bind: %s\n",
345                         strerror(errno));
346                 return(-1);
347         }
348
349         if (listen(s, actual_queue_len) < 0) {
350                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
351                 return(-1);
352         }
353
354         chmod(sockpath, 0777);
355         return(s);
356 }
357
358
359
360 /*
361  * Return a pointer to the CitContext structure bound to the thread which
362  * called this function.  If there's no such binding (for example, if it's
363  * called by the housekeeper thread) then a generic 'master' CC is returned.
364  */
365 struct CitContext *MyContext(void) {
366         struct CitContext *retCC;
367         retCC = (struct CitContext *) pthread_getspecific(MyConKey);
368         if (retCC == NULL) retCC = &masterCC;
369         return(retCC);
370 }
371
372
373 /*
374  * Initialize a new context and place it in the list.  The session number
375  * used to be the PID (which is why it's called cs_pid), but that was when we
376  * had one process per session.  Now we just assign them sequentially, starting
377  * at 1 (don't change it to 0 because masterCC uses 0) and re-using them when
378  * sessions terminate.
379  */
380 struct CitContext *CreateNewContext(void) {
381         struct CitContext *me, *ptr;
382         int num = 1;
383         int startover = 0;
384
385         me = (struct CitContext *) mallok(sizeof(struct CitContext));
386         if (me == NULL) {
387                 lprintf(1, "citserver: can't allocate memory!!\n");
388                 return NULL;
389         }
390         memset(me, 0, sizeof(struct CitContext));
391
392         /* The new context will be created already in the CON_EXECUTING state
393          * in order to prevent another thread from grabbing it while it's
394          * being set up.
395          */
396         me->state = CON_EXECUTING;
397
398         begin_critical_section(S_SESSION_TABLE);
399
400         /* obtain a unique session number */
401         do {
402                 startover = 0;
403                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
404                         if (ptr->cs_pid == num) {
405                                 ++num;
406                                 startover = 1;
407                         }
408                 }
409         } while (startover == 1);
410
411         me->cs_pid = num;
412         me->next = ContextList;
413         ContextList = me;
414         ++num_sessions;
415
416         end_critical_section(S_SESSION_TABLE);
417         return(me);
418 }
419
420
421
422 /*
423  * client_write()   ...    Send binary data to the client.
424  */
425 void client_write(char *buf, int nbytes)
426 {
427         int bytes_written = 0;
428         int retval;
429         int sock;
430
431         if (CC->redirect_fp != NULL) {
432                 fwrite(buf, nbytes, 1, CC->redirect_fp);
433                 return;
434         }
435
436         if (CC->redirect_sock > 0) {
437                 sock = CC->redirect_sock;       /* and continue below... */
438         }
439         else {
440                 sock = CC->client_socket;
441         }
442
443         while (bytes_written < nbytes) {
444                 retval = write(sock, &buf[bytes_written],
445                         nbytes - bytes_written);
446                 if (retval < 1) {
447                         lprintf(2, "client_write() failed: %s\n",
448                                 strerror(errno));
449                         if (sock == CC->client_socket) CC->kill_me = 1;
450                         return;
451                 }
452                 bytes_written = bytes_written + retval;
453         }
454 }
455
456
457 /*
458  * cprintf()  ...   Send formatted printable data to the client.   It is
459  *                  implemented in terms of client_write() but remains in
460  *                  sysdep.c in case we port to somewhere without va_args...
461  */
462 void cprintf(const char *format, ...) {   
463         va_list arg_ptr;   
464         char buf[256];   
465    
466         va_start(arg_ptr, format);   
467         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
468                 buf[sizeof buf - 2] = '\n';
469         client_write(buf, strlen(buf)); 
470         va_end(arg_ptr);
471 }   
472
473
474 /*
475  * Read data from the client socket.
476  * Return values are:
477  *      1       Requested number of bytes has been read.
478  *      0       Request timed out.
479  *      -1      The socket is broken.
480  * If the socket breaks, the session will be terminated.
481  */
482 int client_read_to(char *buf, int bytes, int timeout)
483 {
484         int len,rlen;
485         fd_set rfds;
486         struct timeval tv;
487         int retval;
488
489         len = 0;
490         while(len<bytes) {
491                 FD_ZERO(&rfds);
492                 FD_SET(CC->client_socket, &rfds);
493                 tv.tv_sec = timeout;
494                 tv.tv_usec = 0;
495
496                 retval = select( (CC->client_socket)+1, 
497                                         &rfds, NULL, NULL, &tv);
498
499                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
500                         return(0);
501                 }
502
503                 rlen = read(CC->client_socket, &buf[len], bytes-len);
504                 if (rlen<1) {
505                         lprintf(2, "client_read() failed: %s\n",
506                                 strerror(errno));
507                         CC->kill_me = 1;
508                         return(-1);
509                 }
510                 len = len + rlen;
511         }
512         return(1);
513 }
514
515 /*
516  * Read data from the client socket with default timeout.
517  * (This is implemented in terms of client_read_to() and could be
518  * justifiably moved out of sysdep.c)
519  */
520 int client_read(char *buf, int bytes)
521 {
522         return(client_read_to(buf, bytes, config.c_sleeping));
523 }
524
525
526 /*
527  * client_gets()   ...   Get a LF-terminated line of text from the client.
528  * (This is implemented in terms of client_read() and could be
529  * justifiably moved out of sysdep.c)
530  */
531 int client_gets(char *buf)
532 {
533         int i, retval;
534
535         /* Read one character at a time.
536          */
537         for (i = 0;;i++) {
538                 retval = client_read(&buf[i], 1);
539                 if (retval != 1 || buf[i] == '\n' || i == 255)
540                         break;
541         }
542
543         /* If we got a long line, discard characters until the newline.
544          */
545         if (i == 255)
546                 while (buf[i] != '\n' && retval == 1)
547                         retval = client_read(&buf[i], 1);
548
549         /* Strip the trailing newline and any trailing nonprintables (cr's)
550          */
551         buf[i] = 0;
552         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
553                 buf[strlen(buf)-1] = 0;
554         if (retval < 0) strcpy(buf, "000");
555         return(retval);
556 }
557
558
559
560 /*
561  * The system-dependent part of master_cleanup() - close the master socket.
562  */
563 void sysdep_master_cleanup(void) {
564         struct ServiceFunctionHook *serviceptr;
565
566         /*
567          * close all protocol master sockets
568          */
569         for (serviceptr = ServiceHookTable; serviceptr != NULL;
570             serviceptr = serviceptr->next ) {
571
572                 if (serviceptr->tcp_port > 0)
573                         lprintf(3, "Closing listener on port %d\n",
574                                 serviceptr->tcp_port);
575
576                 if (serviceptr->sockpath != NULL)
577                         lprintf(3, "Closing listener on '%s'\n",
578                                 serviceptr->sockpath);
579
580                 close(serviceptr->msock);
581
582                 /* If it's a Unix domain socket, remove the file. */
583                 if (serviceptr->sockpath != NULL) {
584                         unlink(serviceptr->sockpath);
585                 }
586         }
587 }
588
589
590 /*
591  * Terminate another session.
592  * (This could justifiably be moved out of sysdep.c because it
593  * no longer does anything that is system-dependent.)
594  */
595 void kill_session(int session_to_kill) {
596         struct CitContext *ptr;
597
598         begin_critical_section(S_SESSION_TABLE);
599         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
600                 if (ptr->cs_pid == session_to_kill) {
601                         ptr->kill_me = 1;
602                 }
603         }
604         end_critical_section(S_SESSION_TABLE);
605 }
606
607
608
609
610 /*
611  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
612  */
613 void start_daemon(int do_close_stdio) {
614         if (do_close_stdio) {
615                 /* close(0); */
616                 close(1);
617                 close(2);
618         }
619         signal(SIGHUP,SIG_IGN);
620         signal(SIGINT,SIG_IGN);
621         signal(SIGQUIT,SIG_IGN);
622         if (fork()!=0) exit(0);
623 }
624
625
626
627 /*
628  * Tie in to the 'netsetup' program.
629  *
630  * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
631  */
632 void cmd_nset(char *cmdbuf)
633 {
634         int retcode;
635         char fbuf[4096];
636         FILE *netsetup;
637         int ch;
638         int a, b;
639         char netsetup_args[3][256];
640
641         if (CC->usersupp.axlevel < 6) {
642                 cprintf("%d Higher access required.\n", 
643                         ERROR + HIGHER_ACCESS_REQUIRED);
644                 return;
645         }
646
647         for (a=1; a<=3; ++a) {
648                 if (num_parms(cmdbuf) >= a) {
649                         extract(netsetup_args[a-1], cmdbuf, a-1);
650                         for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
651                                 if (netsetup_args[a-1][b] == 34) {
652                                         netsetup_args[a-1][b] = '_';
653                                 }
654                         }
655                 }
656                 else {
657                         netsetup_args[a-1][0] = 0;
658                 }
659         }
660
661         sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
662                 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
663         netsetup = popen(fbuf, "r");
664         if (netsetup == NULL) {
665                 cprintf("%d %s\n", ERROR, strerror(errno));
666                 return;
667         }
668
669         fbuf[0] = 0;
670         while (ch = getc(netsetup), (ch > 0)) {
671                 fbuf[strlen(fbuf)+1] = 0;
672                 fbuf[strlen(fbuf)] = ch;
673         }
674
675         retcode = pclose(netsetup);
676
677         if (retcode != 0) {
678                 for (a=0; a<strlen(fbuf); ++a) {
679                         if (fbuf[a] < 32) fbuf[a] = 32;
680                 }
681                 fbuf[245] = 0;
682                 cprintf("%d %s\n", ERROR, fbuf);
683                 return;
684         }
685
686         cprintf("%d Command succeeded.  Output follows:\n", LISTING_FOLLOWS);
687         cprintf("%s", fbuf);
688         if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
689         cprintf("000\n");
690 }
691
692
693
694 /*
695  * Generic routine to convert a login name to a full name (gecos)
696  * Returns nonzero if a conversion took place
697  */
698 int convert_login(char NameToConvert[]) {
699         struct passwd *pw;
700         int a;
701
702         pw = getpwnam(NameToConvert);
703         if (pw == NULL) {
704                 return(0);
705         }
706         else {
707                 strcpy(NameToConvert, pw->pw_gecos);
708                 for (a=0; a<strlen(NameToConvert); ++a) {
709                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
710                 }
711                 return(1);
712         }
713 }
714
715
716
717 /*
718  * Purge all sessions which have the 'kill_me' flag set.
719  * This function has code to prevent it from running more than once every
720  * few seconds, because running it after every single unbind would waste a lot
721  * of CPU time and keep the context list locked too much.
722  *
723  * After that's done, we raise or lower the size of the worker thread pool
724  * if such an action is appropriate.
725  */
726 void dead_session_purge(void) {
727         struct CitContext *ptr, *rem;
728         pthread_attr_t attr;
729         pthread_t newthread;
730
731         if ( (time(NULL) - last_purge) < 5 ) return;    /* Too soon, go away */
732         time(&last_purge);
733
734         do {
735                 rem = NULL;
736                 begin_critical_section(S_SESSION_TABLE);
737                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
738                         if ( (ptr->state == CON_IDLE) && (ptr->kill_me) ) {
739                                 rem = ptr;
740                         }
741                 }
742                 end_critical_section(S_SESSION_TABLE);
743
744                 /* RemoveContext() enters its own S_SESSION_TABLE critical
745                  * section, so we have to do it like this.
746                  */     
747                 if (rem != NULL) {
748                         lprintf(9, "Purging session %d\n", rem->cs_pid);
749                         RemoveContext(rem);
750                 }
751
752         } while (rem != NULL);
753
754
755         /* Raise or lower the size of the worker thread pool if such
756          * an action is appropriate.
757          */
758
759         if ( (num_sessions > num_threads)
760            && (num_threads < config.c_max_workers) ) {
761
762                 pthread_attr_init(&attr);
763                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
764                 if (pthread_create(&newthread, &attr,
765                    (void* (*)(void*)) worker_thread, NULL) != 0) {
766                         lprintf(1, "Can't create worker thead: %s\n",
767                         strerror(errno));
768                 }
769
770         }
771         
772         else if ( (num_sessions < num_threads)
773            && (num_threads > config.c_min_workers) ) {
774                 --num_threads;
775                 pthread_exit(NULL);
776         }
777
778 }
779
780
781
782
783
784 /*
785  * Redirect a session's output to a file or socket.
786  * This function may be called with a file handle *or* a socket (but not
787  * both).  Call with neither to return output to its normal client socket.
788  */
789 void CtdlRedirectOutput(FILE *fp, int sock) {
790
791         if (fp != NULL) CC->redirect_fp = fp;
792         else CC->redirect_fp = NULL;
793
794         if (sock > 0) CC->redirect_sock = sock;
795         else CC->redirect_sock = (-1);
796
797 }
798
799
800 /*
801  * masterCC is the context we use when not attached to a session.  This
802  * function initializes it.
803  */
804 void InitializeMasterCC(void) {
805         memset(&masterCC, 0, sizeof(struct CitContext));
806         masterCC.internal_pgm = 1;
807         masterCC.cs_pid = 0;
808 }
809
810
811
812 /*
813  * Set up a fd_set containing all the master sockets to which we
814  * always listen.  It's computationally less expensive to just copy
815  * this to a local fd_set when starting a new select() and then add
816  * the client sockets than it is to initialize a new one and then
817  * figure out what to put there.
818  */
819 void init_master_fdset(void) {
820         struct ServiceFunctionHook *serviceptr;
821         int m;
822
823         lprintf(9, "Initializing master fdset\n");
824
825         FD_ZERO(&masterfds);
826         masterhighest = 0;
827
828         lprintf(9, "Will listen on rescan pipe %d\n", rescan[0]);
829         FD_SET(rescan[0], &masterfds);
830         if (rescan[0] > masterhighest) masterhighest = rescan[0];
831
832         for (serviceptr = ServiceHookTable; serviceptr != NULL;
833             serviceptr = serviceptr->next ) {
834                 m = serviceptr->msock;
835                 lprintf(9, "Will listen on master socket %d\n", m);
836                 FD_SET(m, &masterfds);
837                 if (m > masterhighest) {
838                         masterhighest = m;
839                 }
840         }
841         lprintf(9, "masterhighest = %d\n", masterhighest);
842 }
843
844
845
846 /*
847  * Here's where it all begins.
848  */
849 int main(int argc, char **argv)
850 {
851         pthread_t HousekeepingThread;   /* Thread descriptor */
852         pthread_attr_t attr;            /* Thread attributes */
853         char tracefile[128];            /* Name of file to log traces to */
854         int a, i;                       /* General-purpose variables */
855         struct passwd *pw;
856         int drop_root_perms = 1;
857         char *moddir;
858         
859         /* specify default port name and trace file */
860         strcpy(tracefile, "");
861
862         /* initialize the master context */
863         InitializeMasterCC();
864
865         /* parse command-line arguments */
866         for (a=1; a<argc; ++a) {
867
868                 /* -t specifies where to log trace messages to */
869                 if (!strncmp(argv[a], "-t", 2)) {
870                         strcpy(tracefile, argv[a]);
871                         strcpy(tracefile, &tracefile[2]);
872                         freopen(tracefile, "r", stdin);
873                         freopen(tracefile, "w", stdout);
874                         freopen(tracefile, "w", stderr);
875                 }
876
877                 /* run in the background if -d was specified */
878                 else if (!strcmp(argv[a], "-d")) {
879                         start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
880                 }
881
882                 /* -x specifies the desired logging level */
883                 else if (!strncmp(argv[a], "-x", 2)) {
884                         verbosity = atoi(&argv[a][2]);
885                 }
886
887                 else if (!strncmp(argv[a], "-h", 2)) {
888                         safestrncpy(bbs_home_directory, &argv[a][2],
889                                     sizeof bbs_home_directory);
890                         home_specified = 1;
891                 }
892
893                 else if (!strncmp(argv[a], "-f", 2)) {
894                         do_defrag = 1;
895                 }
896
897                 /* -r tells the server not to drop root permissions. don't use
898                  * this unless you know what you're doing. this should be
899                  * removed in the next release if it proves unnecessary. */
900                 else if (!strcmp(argv[a], "-r"))
901                         drop_root_perms = 0;
902
903                 /* any other parameter makes it crash and burn */
904                 else {
905                         lprintf(1,      "citserver: usage: "
906                                         "citserver [-tTraceFile] [-d] [-f]"
907                                         " [-xLogLevel] [-hHomeDir]\n");
908                         exit(1);
909                 }
910
911         }
912
913         /* Tell 'em who's in da house */
914         lprintf(1,
915 "\nMultithreaded message server for Citadel/UX\n"
916 "Copyright (C) 1987-2000 by the Citadel/UX development team.\n"
917 "Citadel/UX is free software, covered by the GNU General Public License, and\n"
918 "you are welcome to change it and/or distribute copies of it under certain\n"
919 "conditions.  There is absolutely no warranty for this software.  Please\n"
920 "read the 'COPYING.txt' file for details.\n\n");
921
922         /* Initialize... */
923         init_sysdep();
924         openlog("citserver", LOG_PID, LOG_USER);
925
926         /* Load site-specific parameters */
927         lprintf(7, "Loading citadel.config\n");
928         get_config();
929
930         /*
931          * Do non system dependent startup functions.
932          */
933         master_startup();
934
935         /*
936          * Bind the server to a Unix-domain socket.
937          */
938         CtdlRegisterServiceHook(0,
939                                 "citadel.socket",
940                                 citproto_begin_session,
941                                 do_command_loop);
942
943         /*
944          * Bind the server to our favorite TCP port (usually 504).
945          */
946         CtdlRegisterServiceHook(config.c_port_number,
947                                 NULL,
948                                 citproto_begin_session,
949                                 do_command_loop);
950
951         /*
952          * Load any server-side modules (plugins) available here.
953          */
954         lprintf(7, "Initializing loadable modules\n");
955         if ((moddir = malloc(strlen(bbs_home_directory) + 9)) != NULL) {
956                 sprintf(moddir, "%s/modules", bbs_home_directory);
957                 DLoader_Init(moddir);
958                 free(moddir);
959         }
960
961         /*
962          * The rescan pipe exists so that worker threads can be woken up and
963          * told to re-scan the context list for fd's to listen on.  This is
964          * necessary, for example, when a context is about to go idle and needs
965          * to get back on that list.
966          */
967         if (pipe(rescan)) {
968                 lprintf(1, "Can't create rescan pipe!\n");
969                 exit(errno);
970         }
971
972         init_master_fdset();
973
974         /*
975          * Now that we've bound the sockets, change to the BBS user id and its
976          * corresponding group ids
977          */
978         if (drop_root_perms) {
979                 if ((pw = getpwuid(BBSUID)) == NULL)
980                         lprintf(1, "WARNING: getpwuid(%d): %s\n"
981                                    "Group IDs will be incorrect.\n", BBSUID,
982                                 strerror(errno));
983                 else {
984                         initgroups(pw->pw_name, pw->pw_gid);
985                         if (setgid(pw->pw_gid))
986                                 lprintf(3, "setgid(%d): %s\n", pw->pw_gid,
987                                         strerror(errno));
988                 }
989                 lprintf(7, "Changing uid to %d\n", BBSUID);
990                 if (setuid(BBSUID) != 0) {
991                         lprintf(3, "setuid() failed: %s\n", strerror(errno));
992                 }
993         }
994
995         /*
996          * Create the housekeeper thread
997          */
998         lprintf(7, "Starting housekeeper thread\n");
999         pthread_attr_init(&attr);
1000         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1001         if (pthread_create(&HousekeepingThread, &attr,
1002            (void* (*)(void*)) housekeeping_loop, NULL) != 0) {
1003                 lprintf(1, "Can't create housekeeping thead: %s\n",
1004                         strerror(errno));
1005         }
1006
1007
1008         /*
1009          * Now create a bunch of worker threads.
1010          */
1011         for (i=0; i<(config.c_min_workers-1); ++i) {
1012                 pthread_attr_init(&attr);
1013                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1014                 if (pthread_create(&HousekeepingThread, &attr,
1015                    (void* (*)(void*)) worker_thread, NULL) != 0) {
1016                         lprintf(1, "Can't create worker thead: %s\n",
1017                         strerror(errno));
1018                 }
1019         }
1020
1021         /* Now this thread can become a worker as well. */
1022         worker_thread();
1023
1024         return(0);
1025 }
1026
1027
1028 /*
1029  * Bind a thread to a context.  (It's inline merely to speed things up.)
1030  */
1031 inline void become_session(struct CitContext *which_con) {
1032         pthread_setspecific(MyConKey, (void *)which_con );
1033 }
1034
1035
1036
1037 /* 
1038  * This loop just keeps going and going and going...
1039  */     
1040 void worker_thread(void) {
1041         int i;
1042         char junk;
1043         int highest;
1044         struct CitContext *ptr;
1045         struct CitContext *bind_me = NULL;
1046         fd_set readfds;
1047         int retval;
1048         struct CitContext *con= NULL;   /* Temporary context pointer */
1049         struct ServiceFunctionHook *serviceptr;
1050         struct sockaddr_in fsin;        /* Data for master socket */
1051         int alen;                       /* Data for master socket */
1052         int ssock;                      /* Descriptor for client socket */
1053         struct timeval tv;
1054
1055         ++num_threads;
1056
1057         while (!time_to_die) {
1058
1059                 /* 
1060                  * A naive implementation would have all idle threads
1061                  * calling select() and then they'd all wake up at once.  We
1062                  * solve this problem by putting the select() in a critical
1063                  * section, so only one thread has the opportunity to wake
1064                  * up.  If we wake up on a master socket, create a new
1065                  * session context; otherwise, just bind the thread to the
1066                  * context we want and go on our merry way.
1067                  */
1068
1069                 begin_critical_section(S_I_WANNA_SELECT);
1070 SETUP_FD:       memcpy(&readfds, &masterfds, sizeof masterfds);
1071                 highest = masterhighest;
1072                 begin_critical_section(S_SESSION_TABLE);
1073                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
1074                         if (ptr->state == CON_IDLE) {
1075                                 FD_SET(ptr->client_socket, &readfds);
1076                                 if (ptr->client_socket > highest)
1077                                         highest = ptr->client_socket;
1078                         }
1079                 }
1080                 end_critical_section(S_SESSION_TABLE);
1081
1082                 tv.tv_sec = 60;         /* wake up every minute if no input */
1083                 tv.tv_usec = 0;
1084                 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1085
1086                 /* Now figure out who made this select() unblock.
1087                  * First, check for an error or exit condition.
1088                  */
1089                 if (retval < 0) {
1090                         end_critical_section(S_I_WANNA_SELECT);
1091                         lprintf(9, "Exiting (%s)\n", strerror(errno));
1092                         time_to_die = 1;
1093                 }
1094
1095                 /* Next, check to see if it's a new client connecting
1096                  * on a master socket.
1097                  */
1098                 else for (serviceptr = ServiceHookTable; serviceptr != NULL;
1099                      serviceptr = serviceptr->next ) {
1100
1101                         if (FD_ISSET(serviceptr->msock, &readfds)) {
1102                                 alen = sizeof fsin;
1103                                 ssock = accept(serviceptr->msock,
1104                                         (struct sockaddr *)&fsin, &alen);
1105                                 if (ssock < 0) {
1106                                         lprintf(2, "citserver: accept(): %s\n",
1107                                                 strerror(errno));
1108                                 }
1109                                 else {
1110                                         lprintf(7, "citserver: "
1111                                                 "New client socket %d\n",
1112                                                 ssock);
1113
1114                                         /* New context will be created already
1115                                         * set up in the CON_EXECUTING state.
1116                                         */
1117                                         con = CreateNewContext();
1118
1119                                         /* Assign new socket number to it. */
1120                                         con->client_socket = ssock;
1121                                         con->h_command_function =
1122                                                 serviceptr->h_command_function;
1123
1124                                         /* Determine whether local socket */
1125                                         if (serviceptr->sockpath != NULL)
1126                                                 con->is_local_socket = 1;
1127         
1128                                         /* Set the SO_REUSEADDR socket option */
1129                                         i = 1;
1130                                         setsockopt(ssock, SOL_SOCKET,
1131                                                 SO_REUSEADDR,
1132                                                 &i, sizeof(i));
1133
1134                                         become_session(con);
1135                                         begin_session(con);
1136                                         serviceptr->h_greeting_function();
1137                                         become_session(NULL);
1138                                         con->state = CON_IDLE;
1139                                         goto SETUP_FD;
1140                                 }
1141                         }
1142                 }
1143
1144                 /* If the rescan pipe went active, someone is telling this
1145                  * thread that the &readfds needs to be refreshed with more
1146                  * current data.
1147                  */
1148                 if (time_to_die)
1149                         break;
1150
1151                 if (FD_ISSET(rescan[0], &readfds)) {
1152                         read(rescan[0], &junk, 1);
1153                         goto SETUP_FD;
1154                 }
1155
1156                 /* It must be a client socket.  Find a context that has data
1157                  * waiting on its socket *and* is in the CON_IDLE state.
1158                  */
1159                 else {
1160                         bind_me = NULL;
1161                         begin_critical_section(S_SESSION_TABLE);
1162                         for (ptr = ContextList;
1163                             ( (ptr != NULL) && (bind_me == NULL) );
1164                             ptr = ptr->next) {
1165                                 if ( (FD_ISSET(ptr->client_socket, &readfds))
1166                                    && (ptr->state == CON_IDLE) ) {
1167                                         bind_me = ptr;
1168                                 }
1169                         }
1170                         if (bind_me != NULL) {
1171                                 /* Found one.  Stake a claim to it before
1172                                  * letting anyone else touch the context list.
1173                                  */
1174                                 bind_me->state = CON_EXECUTING;
1175                         }
1176
1177                         end_critical_section(S_SESSION_TABLE);
1178                         end_critical_section(S_I_WANNA_SELECT);
1179
1180                         /* We're bound to a session, now do *one* command */
1181                         if (bind_me != NULL) {
1182                                 become_session(bind_me);
1183                                 cdb_begin_transaction();
1184                                 CC->h_command_function();
1185                                 cdb_end_transaction();
1186                                 become_session(NULL);
1187                                 bind_me->state = CON_IDLE;
1188                                 if (bind_me->kill_me == 1) {
1189                                         RemoveContext(bind_me);
1190                                 } 
1191                                 write(rescan[1], &junk, 1);
1192                         }
1193
1194                 }
1195                 dead_session_purge();
1196                 if ((time(NULL) - last_timer) > 60L) {
1197                         last_timer = time(NULL);
1198                         PerformSessionHooks(EVT_TIMER);
1199                 }
1200         }
1201
1202         /* If control reaches this point, the server is shutting down */        
1203         master_cleanup();
1204         --num_threads;
1205         pthread_exit(NULL);
1206 }
1207