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