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