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