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