fixes for BSDI. see ChangeLog.
[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  * Wherever possible, we use function wrappers and type definitions to create
10  * abstractions that are platform-independent from the calling side.
11  * 
12  * Eventually we'll try porting to a different platform and either have
13  * multiple variants of this file or simply load it up with #ifdefs.
14  */
15
16
17 #include "sysdep.h"
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <fcntl.h>
22 #include <ctype.h>
23 #include <signal.h>
24 #include <sys/types.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 <string.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <stdarg.h>
35 #include <syslog.h>
36 #ifdef HAVE_PTHREAD_H
37 #include <pthread.h>
38 #endif
39 #include "citadel.h"
40 #include "server.h"
41 #include "sysdep_decls.h"
42 #include "citserver.h"
43 #include "support.h"
44 #include "config.h"
45 #include "database.h"
46 #include "housekeeping.h"
47 #include "dynloader.h"
48 #include "tools.h"
49
50 #ifdef HAVE_SYS_SELECT_H
51 #include <sys/select.h>
52 #endif
53
54 #ifndef HAVE_SNPRINTF
55 #include "snprintf.h"
56 #endif
57
58 #ifdef DEBUG_MEMORY_LEAKS
59 struct TheHeap *heap = NULL;
60 #endif
61
62 pthread_mutex_t Critters[MAX_SEMAPHORES];       /* Things needing locking */
63 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
64
65 int msock;                                      /* master listening socket */
66 int verbosity = 3;                              /* Logging level */
67
68 struct CitContext masterCC;
69
70
71 /*
72  * lprintf()  ...   Write logging information
73  */
74 void lprintf(int loglevel, const char *format, ...) {   
75         va_list arg_ptr;
76         char buf[512];
77   
78         va_start(arg_ptr, format);   
79         vsprintf(buf, format, arg_ptr);   
80         va_end(arg_ptr);   
81
82         if (loglevel <= verbosity) { 
83                 fprintf(stderr, "%s", buf);
84                 fflush(stderr);
85                 }
86
87         PerformLogHooks(loglevel, buf);
88         }   
89
90
91
92 #ifdef DEBUG_MEMORY_LEAKS
93 void *tracked_malloc(size_t tsize, char *tfile, int tline) {
94         void *ptr;
95         struct TheHeap *hptr;
96
97         ptr = malloc(tsize);
98         if (ptr == NULL) return(NULL);
99
100         hptr = (struct TheHeap *) malloc(sizeof(struct TheHeap));
101         strcpy(hptr->h_file, tfile);
102         hptr->h_line = tline;
103         hptr->next = heap;
104         hptr->h_ptr = ptr;
105         heap = hptr;
106         return ptr;
107         }
108
109
110 void tracked_free(void *ptr) {
111         struct TheHeap *hptr, *freeme;
112
113         if (heap->h_ptr == ptr) {
114                 hptr = heap->next;
115                 free(heap);
116                 heap = hptr;
117                 }
118         else {
119                 for (hptr=heap; hptr->next!=NULL; hptr=hptr->next) {
120                         if (hptr->next->h_ptr == ptr) {
121                                 freeme = hptr->next;
122                                 hptr->next = hptr->next->next;
123                                 free(freeme);
124                                 }
125                         }
126                 }
127
128         free(ptr);
129         }
130
131 void *tracked_realloc(void *ptr, size_t size) {
132         void *newptr;
133         struct TheHeap *hptr;
134         
135         newptr = realloc(ptr, size);
136
137         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
138                 if (hptr->h_ptr == ptr) hptr->h_ptr = newptr;
139                 }
140
141         return newptr;
142         }
143
144
145 void dump_tracked() {
146         struct TheHeap *hptr;
147
148         cprintf("%d Here's what's allocated...\n", LISTING_FOLLOWS);    
149         for (hptr=heap; hptr!=NULL; hptr=hptr->next) {
150                 cprintf("%20s %5d\n",
151                         hptr->h_file, hptr->h_line);
152                 }
153         cprintf("000\n");
154         }
155 #endif
156
157 #ifndef HAVE_PTHREAD_CANCEL
158 /*
159  * signal handler to fake thread cancellation; only required on BSDI as far
160  * as I know.
161  */
162
163 static pthread_t main_thread_id;
164
165 static RETSIGTYPE cancel_thread(int signum) {
166         pthread_exit(NULL);
167         }
168 #endif
169
170 /*
171  * we used to use master_cleanup() as a signal handler to shut down the server.
172  * however, master_cleanup() and the functions it calls do some things that
173  * aren't such a good idea to do from a signal handler: acquiring mutexes,
174  * playing with signal masks on BSDI systems, etc. so instead we install the
175  * following signal handler to set a global variable to inform the main loop
176  * that it's time to call master_cleanup() and exit.
177  */
178
179 static volatile int time_to_die = 0;
180
181 static RETSIGTYPE signal_cleanup(int signum) {
182         time_to_die = 1;
183         }
184
185
186 /*
187  * Some initialization stuff...
188  */
189 void init_sysdep(void) {
190         int a;
191
192         /* Set up a bunch of semaphores to be used for critical sections */
193         for (a=0; a<MAX_SEMAPHORES; ++a) {
194                 pthread_mutex_init(&Critters[a], NULL);
195                 }
196
197         /*
198          * Set up a place to put thread-specific data.
199          * We only need a single pointer per thread - it points to the
200          * thread's CitContext structure in the ContextList linked list.
201          */
202         if (pthread_key_create(&MyConKey, NULL) != 0) {
203                 lprintf(1, "Can't create TSD key!!  %s\n", strerror(errno));
204                 }
205
206         /*
207          * The action for unexpected signals and exceptions should be to
208          * call signal_cleanup() to gracefully shut down the server.
209          */
210         signal(SIGINT, signal_cleanup);
211         signal(SIGQUIT, signal_cleanup);
212         signal(SIGHUP, signal_cleanup);
213         signal(SIGTERM, signal_cleanup);
214         signal(SIGPIPE, SIG_IGN);
215 #ifndef HAVE_PTHREAD_CANCEL /* fake it - only BSDI afaik */
216         main_thread_id = pthread_self();
217         signal(SIGUSR1, cancel_thread);
218 #endif
219         }
220
221
222 /*
223  * Obtain a semaphore lock to begin a critical section.
224  */
225 void begin_critical_section(int which_one)
226 {
227 #ifdef HAVE_PTHREAD_CANCEL
228         int oldval;
229 #else
230         sigset_t set;
231 #endif
232
233         /* lprintf(8, "begin_critical_section(%d)\n", which_one); */
234
235 #ifdef HAVE_PTHREAD_CANCEL
236         /* Don't get interrupted during the critical section */
237         pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldval);
238 #else
239         /* We're faking cancellation with signals. Block SIGUSR1 while we're in
240          * the critical section. */
241         if (!pthread_equal(pthread_self(), main_thread_id)) {
242                 sigemptyset(&set);
243                 sigaddset(&set, SIGUSR1);
244                 pthread_sigmask(SIG_BLOCK, &set, NULL);
245                 }
246 #endif
247
248         /* Obtain a semaphore */
249         pthread_mutex_lock(&Critters[which_one]);
250
251         }
252
253 /*
254  * Release a semaphore lock to end a critical section.
255  */
256 void end_critical_section(int which_one)
257 {
258 #ifdef HAVE_PTHREAD_CANCEL
259         int oldval;
260 #else
261         sigset_t set;
262 #endif
263
264         /* lprintf(8, "  end_critical_section(%d)\n", which_one); */
265
266         /* Let go of the semaphore */
267         pthread_mutex_unlock(&Critters[which_one]);
268
269 #ifdef HAVE_PTHREAD_CANCEL
270         /* If a cancel was sent during the critical section, do it now.
271          * Then re-enable thread cancellation.
272          */
273         pthread_testcancel();
274         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
275         pthread_testcancel();
276 #else
277         /* We're faking it. Unblock SIGUSR1; signals sent during the critical
278          * section should now be able to kill us. */
279         if (!pthread_equal(pthread_self(), main_thread_id)) {
280                 sigemptyset(&set);
281                 sigaddset(&set, SIGUSR1);
282                 pthread_sigmask(SIG_UNBLOCK, &set, NULL);
283                 }
284 #endif
285
286         }
287
288
289
290 /*
291  * This is a generic function to set up a master socket for listening on
292  * a TCP port.  The server shuts down if the bind fails.
293  */
294 int ig_tcp_server(int port_number, int queue_len)
295 {
296         struct sockaddr_in sin;
297         int s, i;
298
299         memset(&sin, 0, sizeof(sin));
300         sin.sin_family = AF_INET;
301         sin.sin_addr.s_addr = INADDR_ANY;
302
303         if (port_number == 0) {
304                 lprintf(1,
305                         "citserver: No port number specified.  Run setup.\n");
306                 exit(1);
307                 }
308         
309         sin.sin_port = htons((u_short)port_number);
310
311         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
312         if (s < 0) {
313                 lprintf(1, "citserver: Can't create a socket: %s\n",
314                         strerror(errno));
315                 exit(errno);
316                 }
317
318         /* Set the SO_REUSEADDR socket option, because it makes sense. */
319         i = 1;
320         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
321
322         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
323                 lprintf(1, "citserver: Can't bind: %s\n", strerror(errno));
324                 exit(errno);
325                 }
326
327         if (listen(s, queue_len) < 0) {
328                 lprintf(1, "citserver: Can't listen: %s\n", strerror(errno));
329                 exit(errno);
330                 }
331
332         return(s);
333         }
334
335
336 /*
337  * Return a pointer to a thread's own CitContext structure (old)
338  * NOTE: this version of MyContext() is commented out because it is no longer
339  * in use.  It was written before I discovered TSD keys.  This
340  * version pounds through the context list until it finds the one matching
341  * the currently running thread.  It remains here, commented out, in case it
342  * is needed for future ports to threading libraries which have the equivalent
343  * of pthread_self() but not pthread_key_create() and its ilk.
344  *
345  * struct CitContext *MyContext() {
346  *      struct CitContext *ptr;
347  *      THREAD me;
348  *
349  *      me = pthread_self();
350  *      for (ptr=ContextList; ptr!=NULL; ptr=ptr->next) {
351  *              if (ptr->mythread == me) return(ptr);
352  *              }
353  *      return(NULL);
354  *      }
355  */
356
357 /*
358  * Return a pointer to a thread's own CitContext structure (new)
359  */
360 struct CitContext *MyContext(void) {
361         struct CitContext *retCC;
362         retCC = (struct CitContext *) pthread_getspecific(MyConKey);
363         if (retCC == NULL) retCC = &masterCC;
364         return(retCC);
365         }
366
367
368 /*
369  * Wedge our way into the context list.
370  */
371 struct CitContext *CreateNewContext(void) {
372         struct CitContext *me;
373
374         lprintf(9, "CreateNewContext: calling malloc()\n");
375         me = (struct CitContext *) mallok(sizeof(struct CitContext));
376         if (me == NULL) {
377                 lprintf(1, "citserver: can't allocate memory!!\n");
378                 pthread_exit(NULL);
379                 }
380         memset(me, 0, sizeof(struct CitContext));
381
382         begin_critical_section(S_SESSION_TABLE);
383         me->next = ContextList;
384         ContextList = me;
385         end_critical_section(S_SESSION_TABLE);
386         return(me);
387         }
388
389 /*
390  * Add a thread's thread ID to the context
391  */
392 void InitMyContext(struct CitContext *con)
393 {
394 #ifdef HAVE_PTHREAD_CANCEL
395         int oldval;
396 #endif
397
398         con->mythread = pthread_self();
399 #ifdef HAVE_PTHREAD_CANCEL
400         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldval);
401         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldval);
402 #endif
403         if (pthread_setspecific(MyConKey, (void *)con) != 0) {
404                 lprintf(1, "ERROR!  pthread_setspecific() failed: %s\n",
405                         strerror(errno));
406                 }
407         }
408
409 /*
410  * Remove a context from the context list.
411  */
412 void RemoveContext(struct CitContext *con)
413 {
414         struct CitContext *ptr;
415
416         lprintf(7, "Starting RemoveContext()\n");
417         lprintf(9, "Session count before RemoveContext is %d\n",
418                 session_count());
419         if (con==NULL) {
420                 lprintf(7, "WARNING: RemoveContext() called with null!\n");
421                 return;
422                 }
423
424         /*
425          * session_count() starts its own S_SESSION_TABLE critical section;
426          * so do not call it from within this loop.
427          */
428         begin_critical_section(S_SESSION_TABLE);
429         lprintf(7, "Closing socket %d\n", con->client_socket);
430         close(con->client_socket);
431
432         lprintf(9, "Dereferencing session context\n");
433         if (ContextList==con) {
434                 ContextList = ContextList->next;
435                 }
436         else {
437                 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
438                         if (ptr->next == con) {
439                                 ptr->next = con->next;
440                                 }
441                         }
442                 }
443
444         lprintf(9, "Freeing session context...\n");     
445         phree(con);
446         lprintf(9, "...done.\n");
447         end_critical_section(S_SESSION_TABLE);
448
449         lprintf(9, "Session count after RemoveContext is %d\n",
450                 session_count());
451
452         lprintf(7, "Done with RemoveContext\n");
453         }
454
455
456 /*
457  * Return the number of sessions currently running.
458  * (This should probably be moved out of sysdep.c)
459  */
460 int session_count(void) {
461         struct CitContext *ptr;
462         int TheCount = 0;
463
464         lprintf(9, "session_count() starting\n");
465         begin_critical_section(S_SESSION_TABLE);
466         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
467                 ++TheCount;
468                 lprintf(9, "Counted session %3d (%d)\n", ptr->cs_pid, TheCount);
469                 }
470         end_critical_section(S_SESSION_TABLE);
471
472         lprintf(9, "session_count() finishing\n");
473         return(TheCount);
474         }
475
476
477 /*
478  * client_write()   ...    Send binary data to the client.
479  */
480 void client_write(char *buf, int nbytes)
481 {
482         int bytes_written = 0;
483         int retval;
484         while (bytes_written < nbytes) {
485                 retval = write(CC->client_socket, &buf[bytes_written],
486                         nbytes - bytes_written);
487                 if (retval < 1) {
488                         lprintf(2, "client_write() failed: %s\n",
489                                 strerror(errno));
490                         cleanup(errno);
491                         }
492                 bytes_written = bytes_written + retval;
493                 }
494         }
495
496
497 /*
498  * cprintf()  ...   Send formatted printable data to the client.   It is
499  *                  implemented in terms of client_write() but remains in
500  *                  sysdep.c in case we port to somewhere without va_args...
501  */
502 void cprintf(const char *format, ...) {   
503         va_list arg_ptr;   
504         char buf[256];   
505    
506         va_start(arg_ptr, format);   
507         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
508                 buf[sizeof buf - 2] = '\n';
509         client_write(buf, strlen(buf)); 
510         va_end(arg_ptr);
511         }   
512
513
514 /*
515  * Read data from the client socket.
516  * Return values are:
517  *      1       Requested number of bytes has been read.
518  *      0       Request timed out.
519  * If the socket breaks, the session is immediately terminated.
520  */
521 int client_read_to(char *buf, int bytes, int timeout)
522 {
523         int len,rlen;
524         fd_set rfds;
525         struct timeval tv;
526         int retval;
527
528         len = 0;
529         while(len<bytes) {
530                 FD_ZERO(&rfds);
531                 FD_SET(CC->client_socket, &rfds);
532                 tv.tv_sec = timeout;
533                 tv.tv_usec = 0;
534
535                 retval = select( (CC->client_socket)+1, 
536                                         &rfds, NULL, NULL, &tv);
537                 if (FD_ISSET(CC->client_socket, &rfds) == 0) {
538                         return(0);
539                         }
540
541                 rlen = read(CC->client_socket, &buf[len], bytes-len);
542                 if (rlen<1) {
543                         lprintf(2, "client_read() failed: %s\n",
544                                 strerror(errno));
545                         cleanup(errno);
546                         }
547                 len = len + rlen;
548                 }
549         return(1);
550         }
551
552 /*
553  * Read data from the client socket with default timeout.
554  * (This is implemented in terms of client_read_to() and could be
555  * justifiably moved out of sysdep.c)
556  */
557 int client_read(char *buf, int bytes)
558 {
559         return(client_read_to(buf, bytes, config.c_sleeping));
560         }
561
562
563 /*
564  * client_gets()   ...   Get a LF-terminated line of text from the client.
565  * (This is implemented in terms of client_read() and could be
566  * justifiably moved out of sysdep.c)
567  */
568 int client_gets(char *buf)
569 {
570         int i, retval;
571
572         /* Read one character at a time.
573          */
574         for (i = 0;;i++) {
575                 retval = client_read(&buf[i], 1);
576                 if (retval != 1 || buf[i] == '\n' || i == 255)
577                         break;
578                 }
579
580         /* If we got a long line, discard characters until the newline.
581          */
582         if (i == 255)
583                 while (buf[i] != '\n' && retval == 1)
584                         retval = client_read(&buf[i], 1);
585
586         /* Strip the trailing newline and any trailing nonprintables (cr's)
587          */
588         buf[i] = 0;
589         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1])))
590                 buf[strlen(buf)-1] = 0;
591         return(retval);
592         }
593
594
595
596 /*
597  * The system-dependent part of master_cleanup() - close the master socket.
598  */
599 void sysdep_master_cleanup(void) {
600         lprintf(7, "Closing master socket %d\n", msock);
601         close(msock);
602         }
603
604 /*
605  * Cleanup routine to be called when one thread is shutting down.
606  */
607 void cleanup(int exit_code)
608 {
609         /* Terminate the thread.
610          * Its cleanup handler will call cleanup_stuff()
611          */
612         lprintf(7, "Calling pthread_exit()\n");
613         pthread_exit(NULL);
614         }
615
616 /*
617  * Terminate another session.
618  */
619 void kill_session(int session_to_kill) {
620         struct CitContext *ptr;
621         THREAD killme = 0;
622
623         lprintf(9, "kill_session() scanning for thread to cancel...\n");
624         begin_critical_section(S_SESSION_TABLE);
625         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
626                 if (ptr->cs_pid == session_to_kill) {
627                         killme = ptr->mythread;
628                         }
629                 }
630         end_critical_section(S_SESSION_TABLE);
631         lprintf(9, "kill_session() finished scanning.\n");
632
633         if (killme != 0) {
634 #ifdef HAVE_PTHREAD_CANCEL
635                 lprintf(9, "calling pthread_cancel()\n");
636                 pthread_cancel(killme);
637 #else
638                 pthread_kill(killme, SIGUSR1);
639 #endif
640                 }
641         }
642
643
644 /*
645  * The system-dependent wrapper around the main context loop.
646  */
647 void *sd_context_loop(struct CitContext *con) {
648         pthread_cleanup_push(*cleanup_stuff, NULL);
649         context_loop(con);
650         pthread_cleanup_pop(0);
651         return NULL;
652         }
653
654
655 /*
656  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
657  */
658 void start_daemon(int do_close_stdio) {
659         if (do_close_stdio) {
660                 /* close(0); */
661                 close(1);
662                 close(2);
663                 }
664         signal(SIGHUP,SIG_IGN);
665         signal(SIGINT,SIG_IGN);
666         signal(SIGQUIT,SIG_IGN);
667         if (fork()!=0) exit(0);
668         }
669
670
671
672 /*
673  * Tie in to the 'netsetup' program.
674  *
675  * (We're going to hope that netsetup never feeds more than 4096 bytes back.)
676  */
677 void cmd_nset(char *cmdbuf)
678 {
679         int retcode;
680         char fbuf[4096];
681         FILE *netsetup;
682         int ch;
683         int a, b;
684         char netsetup_args[3][256];
685
686         if (CC->usersupp.axlevel < 6) {
687                 cprintf("%d Higher access required.\n", 
688                         ERROR + HIGHER_ACCESS_REQUIRED);
689                 return;
690                 }
691
692         for (a=1; a<=3; ++a) {
693                 if (num_parms(cmdbuf) >= a) {
694                         extract(netsetup_args[a-1], cmdbuf, a-1);
695                         for (b=0; b<strlen(netsetup_args[a-1]); ++b) {
696                                 if (netsetup_args[a-1][b] == 34) {
697                                         netsetup_args[a-1][b] = '_';
698                                         }
699                                 }
700                         }
701                 else {
702                         netsetup_args[a-1][0] = 0;
703                         }
704                 }
705
706         sprintf(fbuf, "./netsetup \"%s\" \"%s\" \"%s\" </dev/null 2>&1",
707                 netsetup_args[0], netsetup_args[1], netsetup_args[2]);
708         netsetup = popen(fbuf, "r");
709         if (netsetup == NULL) {
710                 cprintf("%d %s\n", ERROR, strerror(errno));
711                 return;
712                 }
713
714         fbuf[0] = 0;
715         while (ch = getc(netsetup), (ch > 0)) {
716                 fbuf[strlen(fbuf)+1] = 0;
717                 fbuf[strlen(fbuf)] = ch;
718                 }
719
720         retcode = pclose(netsetup);
721
722         if (retcode != 0) {
723                 for (a=0; a<strlen(fbuf); ++a) {
724                         if (fbuf[a] < 32) fbuf[a] = 32;
725                         }
726                 fbuf[245] = 0;
727                 cprintf("%d %s\n", ERROR, fbuf);
728                 return;
729                 }
730
731         cprintf("%d Command succeeded.  Output follows:\n", LISTING_FOLLOWS);
732         cprintf("%s", fbuf);
733         if (fbuf[strlen(fbuf)-1] != 10) cprintf("\n");
734         cprintf("000\n");
735         }
736
737
738
739 /*
740  * Generic routine to convert a login name to a full name (gecos)
741  * Returns nonzero if a conversion took place
742  */
743 int convert_login(char NameToConvert[]) {
744         struct passwd *pw;
745         int a;
746
747         pw = getpwnam(NameToConvert);
748         if (pw == NULL) {
749                 return(0);
750                 }
751         else {
752                 strcpy(NameToConvert, pw->pw_gecos);
753                 for (a=0; a<strlen(NameToConvert); ++a) {
754                         if (NameToConvert[a] == ',') NameToConvert[a] = 0;
755                         }
756                 return(1);
757                 }
758         }
759
760
761
762
763         
764
765 /*
766  * Here's where it all begins.
767  */
768 int main(int argc, char **argv)
769 {
770         struct sockaddr_in fsin;        /* Data for master socket */
771         int alen;                       /* Data for master socket */
772         int ssock;                      /* Descriptor for master socket */
773         THREAD SessThread;              /* Thread descriptor */
774         pthread_attr_t attr;            /* Thread attributes */
775         struct CitContext *con;         /* Temporary context pointer */
776         char tracefile[128];            /* Name of file to log traces to */
777         int a, i;                       /* General-purpose variables */
778         char convbuf[128];
779         fd_set readfds;
780         struct timeval tv;
781         
782         /* specify default port name and trace file */
783         strcpy(tracefile, "");
784
785         /* parse command-line arguments */
786         for (a=1; a<argc; ++a) {
787
788                 /* -t specifies where to log trace messages to */
789                 if (!strncmp(argv[a], "-t", 2)) {
790                         strcpy(tracefile, argv[a]);
791                         strcpy(tracefile, &tracefile[2]);
792                         freopen(tracefile, "r", stdin);
793                         freopen(tracefile, "w", stdout);
794                         freopen(tracefile, "w", stderr);
795                         }
796
797                 /* run in the background if -d was specified */
798                 else if (!strcmp(argv[a], "-d")) {
799                         start_daemon( (strlen(tracefile) > 0) ? 0 : 1 ) ;
800                         }
801
802                 /* -x specifies the desired logging level */
803                 else if (!strncmp(argv[a], "-x", 2)) {
804                         strcpy(convbuf, argv[a]);
805                         verbosity = atoi(&convbuf[2]);
806                         }
807
808                 else if (!strncmp(argv[a], "-h", 2)) {
809                         strcpy(convbuf, argv[a]);
810                         strcpy(bbs_home_directory, &convbuf[2]);
811                         home_specified = 1;
812                         }
813
814                 /* any other parameter makes it crash and burn */
815                 else {
816                         lprintf(1, "citserver: usage: ");
817                         lprintf(1, "citserver [-tTraceFile]");
818                         lprintf(1, " [-d] [-xLogLevel] [-hHomeDir]\n");
819                         exit(1);
820                         }
821
822                 }
823
824         /* Tell 'em who's in da house */
825         lprintf(1, "Multithreaded message server for %s\n", CITADEL);
826         lprintf(1, "Copyright (C) 1987-1998 by Art Cancro.  ");
827         lprintf(1, "All rights reserved.\n\n");
828
829         /* Initialize... */
830         init_sysdep();
831         openlog("citserver",LOG_PID,LOG_USER);
832         /* Load site-specific parameters */
833         lprintf(7, "Loading citadel.config\n");
834         get_config();
835
836         lprintf(7, "Initializing loadable modules\n");
837         DLoader_Init("./modules");
838         lprintf(9, "Modules done initializing.\n");
839
840         /* Do non system dependent startup functions */
841         master_startup();
842
843         /*
844          * Bind the server to our favourite port.
845          * There is no need to check for errors, because ig_tcp_server()
846          * exits if it doesn't succeed.
847          */
848         lprintf(7, "Attempting to bind to port %d...\n", config.c_port_number);
849         msock = ig_tcp_server(config.c_port_number, 5);
850         lprintf(7, "Listening on socket %d\n", msock);
851
852         /*
853          * Now that we've bound the socket, change to the BBS user id
854         lprintf(7, "Changing uid to %d\n", BBSUID);
855         if (setuid(BBSUID) != 0) {
856                 lprintf(3, "setuid() failed: %s", strerror(errno));
857                 }
858          */
859
860         /* 
861          * Endless loop.  Listen on the master socket.  When a connection
862          * comes in, create a socket, a context, and a thread.
863          */     
864         while (!time_to_die) {
865                 /* we need to check if a signal has been delivered. because
866                  * syscalls may be restartable across signals, we call
867                  * select with a timeout of 1 second and repeatedly check for
868                  * time_to_die... */
869                 FD_ZERO(&readfds);
870                 FD_SET(msock, &readfds);
871                 tv.tv_sec = 1;
872                 tv.tv_usec = 0;
873                 if (select(msock + 1, &readfds, NULL, NULL, &tv) <= 0)
874                         continue;
875                 alen = sizeof fsin;
876                 ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
877                 if (ssock < 0) {
878                         lprintf(2, "citserver: accept() failed: %s\n",
879                                 strerror(errno));
880                         }
881                 else {
882                         lprintf(7, "citserver: Client socket %d\n", ssock);
883                         lprintf(9, "creating context\n");
884                         con = CreateNewContext();
885                         con->client_socket = ssock;
886
887                         /* Set the SO_REUSEADDR socket option */
888                         lprintf(9, "setting socket options\n");
889                         i = 1;
890                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
891                                 &i, sizeof(i));
892
893                         /* set attributes for the new thread */
894                         lprintf(9, "setting thread attributes\n");
895                         pthread_attr_init(&attr);
896                         pthread_attr_setdetachstate(&attr,
897                                 PTHREAD_CREATE_DETACHED);
898
899                         /* now create the thread */
900                         lprintf(9, "creating thread\n");
901                         if (pthread_create(&SessThread, &attr,
902                                            (void* (*)(void*)) sd_context_loop,
903                                            con)
904                             != 0) {
905                                 lprintf(1,
906                                         "citserver: can't create thread: %s\n",
907                                         strerror(errno));
908                                 }
909
910                         /* detach the thread 
911                          * (defunct -- now done at thread creation time)
912                          * if (pthread_detach(&SessThread) != 0) {
913                          *      lprintf(1,
914                          *              "citserver: can't detach thread: %s\n",
915                          *              strerror(errno));
916                          *      }
917                          */
918                         lprintf(9, "done!\n");
919                         }
920                 }
921         master_cleanup();
922         return 0;
923         }
924