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