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