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