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