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