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