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