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