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