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