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