Move simple subtstitution functions to the message functions
[citadel.git] / citadel / citserver.c
1 /* 
2  * Main source module for the Citadel server
3  *
4  * Copyright (c) 1987-2011 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
26 # include <time.h>
27 #else
28 # if HAVE_SYS_TIME_H
29 #  include <sys/time.h>
30 # else
31 #  include <time.h>
32 # endif
33 #endif
34
35 #if HAVE_BACKTRACE
36 #include <execinfo.h>
37 #endif
38
39 #include <ctype.h>
40 #include <string.h>
41 #include <dirent.h>
42 #include <errno.h>
43 #include <limits.h>
44 #include <netdb.h>
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <libcitadel.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "sysdep_decls.h"
53 #include "threads.h"
54 #include "citserver.h"
55 #include "config.h"
56 #include "database.h"
57 #include "housekeeping.h"
58 #include "user_ops.h"
59 #include "msgbase.h"
60 #include "support.h"
61 #include "locate_host.h"
62 #include "room_ops.h"
63 #include "file_ops.h"
64 #include "control.h"
65 #include "euidindex.h"
66 #include "context.h"
67 #include "svn_revision.h"
68 #include "ctdl_module.h"
69
70 char *unique_session_numbers;
71 int ScheduledShutdown = 0;
72 time_t server_startup_time;
73 int panic_fd;
74 int openid_level_supported = 0;
75
76 /*
77  * print the actual stack frame.
78  */
79 void cit_backtrace(void)
80 {
81 #ifdef HAVE_BACKTRACE
82         void *stack_frames[50];
83         size_t size, i;
84         char **strings;
85
86
87         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
88         strings = backtrace_symbols(stack_frames, size);
89         for (i = 0; i < size; i++) {
90                 if (strings != NULL)
91                         syslog(LOG_ALERT, "%s\n", strings[i]);
92                 else
93                         syslog(LOG_ALERT, "%p\n", stack_frames[i]);
94         }
95         free(strings);
96 #endif
97 }
98
99 void cit_oneline_backtrace(void)
100 {
101 #ifdef HAVE_BACKTRACE
102         void *stack_frames[50];
103         size_t size, i;
104         char **strings;
105         StrBuf *Buf;
106
107         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
108         strings = backtrace_symbols(stack_frames, size);
109         if (size > 0)
110         {
111                 Buf = NewStrBuf();
112                 for (i = 1; i < size; i++) {
113                         if (strings != NULL)
114                                 StrBufAppendPrintf(Buf, "%s : ", strings[i]);
115                         else
116                                 StrBufAppendPrintf(Buf, "%p : ", stack_frames[i]);
117                 }
118                 free(strings);
119                 syslog(LOG_ALERT, "%s\n", ChrPtr(Buf));
120                 FreeStrBuf(&Buf);
121         }
122 #endif
123 }
124
125 /*
126  * print the actual stack frame.
127  */
128 void cit_panic_backtrace(int SigNum)
129 {
130 #ifdef HAVE_BACKTRACE
131         void *stack_frames[10];
132         size_t size, i;
133         char **strings;
134
135         printf("caught signal 11\n");
136         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
137         strings = backtrace_symbols(stack_frames, size);
138         for (i = 0; i < size; i++) {
139                 if (strings != NULL)
140                         syslog(LOG_ALERT, "%s\n", strings[i]);
141                 else
142                         syslog(LOG_ALERT, "%p\n", stack_frames[i]);
143         }
144         free(strings);
145 #endif
146         exit(-1);
147 }
148
149 /*
150  * Various things that need to be initialized at startup
151  */
152 void master_startup(void) {
153         struct timeval tv;
154         unsigned int seed;
155         FILE *urandom;
156         struct ctdlroom qrbuf;
157         int rv;
158         
159         syslog(LOG_DEBUG, "master_startup() started\n");
160         time(&server_startup_time);
161         get_config();
162
163         syslog(LOG_INFO, "Opening databases\n");
164         open_databases();
165         check_ref_counts();
166
167         syslog(LOG_INFO, "Creating base rooms (if necessary)\n");
168         CtdlCreateRoom(config.c_baseroom,       0, "", 0, 1, 0, VIEW_BBS);
169         CtdlCreateRoom(AIDEROOM,                3, "", 0, 1, 0, VIEW_BBS);
170         CtdlCreateRoom(SYSCONFIGROOM,           3, "", 0, 1, 0, VIEW_BBS);
171         CtdlCreateRoom(config.c_twitroom,       0, "", 0, 1, 0, VIEW_BBS);
172
173         /* The "Local System Configuration" room doesn't need to be visible */
174         if (CtdlGetRoomLock(&qrbuf, SYSCONFIGROOM) == 0) {
175                 qrbuf.QRflags2 |= QR2_SYSTEM;
176                 CtdlPutRoomLock(&qrbuf);
177         }
178
179         /* Aide needs to be public postable, else we're not RFC conformant. */
180         if (CtdlGetRoomLock(&qrbuf, AIDEROOM) == 0) {
181                 qrbuf.QRflags2 |= QR2_SMTP_PUBLIC;
182                 CtdlPutRoomLock(&qrbuf);
183         }
184
185         syslog(LOG_INFO, "Seeding the pseudo-random number generator...\n");
186         urandom = fopen("/dev/urandom", "r");
187         if (urandom != NULL) {
188                 rv = fread(&seed, sizeof seed, 1, urandom);
189                 if (rv == -1)
190                         syslog(LOG_EMERG, "failed to read random seed: %s\n", 
191                                strerror(errno));
192                 fclose(urandom);
193         }
194         else {
195                 gettimeofday(&tv, NULL);
196                 seed = tv.tv_usec;
197         }
198         srand(seed);
199         srandom(seed);
200
201         put_config();
202
203         syslog(LOG_DEBUG, "master_startup() finished\n");
204 }
205
206
207 /*
208  * Cleanup routine to be called when the server is shutting down.
209  */
210 void master_cleanup(int exitcode) {
211         struct CleanupFunctionHook *fcn;
212         static int already_cleaning_up = 0;
213
214         if (already_cleaning_up) while(1) usleep(1000000);
215         already_cleaning_up = 1;
216
217         /* Run any cleanup routines registered by loadable modules */
218         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
219                 (*fcn->h_function_pointer)();
220         }
221
222         /* Close the AdjRefCount queue file */
223         AdjRefCount(-1, 0);
224
225         /* Do system-dependent stuff */
226         sysdep_master_cleanup();
227         
228         /* Close databases */
229         syslog(LOG_INFO, "Closing databases\n");
230         close_databases();
231
232         /* If the operator requested a halt but not an exit, halt here. */
233         if (shutdown_and_halt) {
234                 syslog(LOG_NOTICE, "citserver: Halting server without exiting.\n");
235                 fflush(stdout); fflush(stderr);
236                 while(1) {
237                         sleep(32767);
238                 }
239         }
240         
241         release_control();
242
243         /* Now go away. */
244         syslog(LOG_NOTICE, "citserver: Exiting with status %d\n", exitcode);
245         fflush(stdout); fflush(stderr);
246         
247         if (restart_server != 0)
248                 exit(1);
249         if ((running_as_daemon != 0) && ((exitcode == 0) ))
250                 exitcode = CTDLEXIT_SHUTDOWN;
251         exit(exitcode);
252 }
253
254
255
256 /*
257  * cmd_info()  -  tell the client about this server
258  */
259 void cmd_info(char *cmdbuf) {
260         cprintf("%d Server info:\n", LISTING_FOLLOWS);
261         cprintf("%d\n", CC->cs_pid);
262         cprintf("%s\n", config.c_nodename);
263         cprintf("%s\n", config.c_humannode);
264         cprintf("%s\n", config.c_fqdn);
265         cprintf("%s\n", CITADEL);
266         cprintf("%d\n", REV_LEVEL);
267         cprintf("%s\n", config.c_site_location);
268         cprintf("%s\n", config.c_sysadm);
269         cprintf("%d\n", SERVER_TYPE);
270         cprintf("%s\n", config.c_moreprompt);
271         cprintf("1\n"); /* 1 = yes, this system supports floors */
272         cprintf("1\n"); /* 1 = we support the extended paging options */
273         cprintf("\n");  /* nonce no longer supported */
274         cprintf("1\n"); /* 1 = yes, this system supports the QNOP command */
275
276 #ifdef HAVE_LDAP
277         cprintf("1\n"); /* 1 = yes, this server is LDAP-enabled */
278 #else
279         cprintf("0\n"); /* 1 = no, this server is not LDAP-enabled */
280 #endif
281
282         if ((config.c_auth_mode == AUTHMODE_NATIVE) &&
283             (config.c_disable_newu == 0))
284         {
285                 cprintf("%d\n", config.c_disable_newu);
286         }
287         else {
288                 cprintf("1\n"); /* "create new user" does not work with non-native auth modes */
289         }
290
291         cprintf("%s\n", config.c_default_cal_zone);
292
293         /* thread load averages -- temporarily disabled during refactoring of this code */
294         cprintf("0\n");         /* load average */
295         cprintf("0\n");         /* worker average */
296         cprintf("0\n");         /* thread count */
297
298         cprintf("1\n");         /* yes, Sieve mail filtering is supported */
299         cprintf("%d\n", config.c_enable_fulltext);
300         cprintf("%s\n", svn_revision());
301
302         if (config.c_auth_mode == AUTHMODE_NATIVE) {
303                 cprintf("%d\n", openid_level_supported); /* OpenID is enabled when using native auth */
304         }
305         else {
306                 cprintf("0\n"); /* OpenID is disabled when using non-native auth */
307         }
308
309         cprintf("%d\n", config.c_guest_logins);
310         
311         cprintf("000\n");
312 }
313
314
315 /*
316  * returns an asterisk if there are any instant messages waiting,
317  * space otherwise.
318  */
319 char CtdlCheckExpress(void) {
320         if (CC->FirstExpressMessage == NULL) {
321                 return(' ');
322         }
323         else {
324                 return('*');
325         }
326 }
327
328 void cmd_time(char *argbuf)
329 {
330    time_t tv;
331    struct tm tmp;
332    
333    tv = time(NULL);
334    localtime_r(&tv, &tmp);
335    
336    /* timezone and daylight global variables are not portable. */
337 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
338    cprintf("%d %ld|%ld|%d|%ld\n", CIT_OK, (long)tv, tmp.tm_gmtoff, tmp.tm_isdst, server_startup_time);
339 #else
340    cprintf("%d %ld|%ld|%d|%ld\n", CIT_OK, (long)tv, timezone, tmp.tm_isdst, server_startup_time);
341 #endif
342 }
343
344
345 /*
346  * Check originating host against the public_clients file.  This determines
347  * whether the client is allowed to change the hostname for this session
348  * (for example, to show the location of the user rather than the location
349  * of the client).
350  */
351 int is_public_client(void)
352 {
353         char buf[1024];
354         char addrbuf[1024];
355         FILE *fp;
356         int i;
357         char *public_clientspos;
358         char *public_clientsend;
359         char *paddr = NULL;
360         struct stat statbuf;
361         static time_t pc_timestamp = 0;
362         static char public_clients[SIZ];
363         static char public_clients_file[SIZ];
364
365 #define LOCALHOSTSTR "127.0.0.1"
366
367         snprintf(public_clients_file, sizeof public_clients_file, "%s/public_clients", ctdl_etc_dir);
368
369         /*
370          * Check the time stamp on the public_clients file.  If it's been
371          * updated since the last time we were here (or if this is the first
372          * time we've been through the loop), read its contents and learn
373          * the IP addresses of the listed hosts.
374          */
375         if (stat(public_clients_file, &statbuf) != 0) {
376                 /* No public_clients file exists, so bail out */
377                 syslog(LOG_WARNING, "Warning: '%s' does not exist\n", 
378                                 public_clients_file);
379                 return(0);
380         }
381
382         if (statbuf.st_mtime > pc_timestamp) {
383                 begin_critical_section(S_PUBLIC_CLIENTS);
384                 syslog(LOG_INFO, "Loading %s\n", public_clients_file);
385
386                 public_clientspos = &public_clients[0];
387                 public_clientsend = public_clientspos + SIZ;
388                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
389                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
390                 
391                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
392                         *(public_clientspos++) = '|';
393                         paddr = &addrbuf[0];
394                         while (!IsEmptyStr (paddr) && 
395                                (public_clientspos < public_clientsend))
396                                 *(public_clientspos++) = *(paddr++);
397                 }
398
399                 fp = fopen(public_clients_file, "r");
400                 if (fp != NULL) 
401                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
402                                (public_clientspos < public_clientsend)){
403                                 char *ptr;
404                                 ptr = buf;
405                                 while (!IsEmptyStr(ptr)) {
406                                         if (*ptr == '#') {
407                                                 *ptr = 0;
408                                                 break;
409                                         }
410                                 else ptr++;
411                                 }
412                                 ptr--;
413                                 while (ptr>buf && isspace(*ptr)) {
414                                         *(ptr--) = 0;
415                                 }
416                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
417                                         *(public_clientspos++) = '|';
418                                         paddr = addrbuf;
419                                         while (!IsEmptyStr(paddr) && 
420                                                (public_clientspos < public_clientsend)){
421                                                 *(public_clientspos++) = *(paddr++);
422                                         }
423                                 }
424                         }
425                 if (fp != NULL) fclose(fp);
426                 pc_timestamp = time(NULL);
427                 end_critical_section(S_PUBLIC_CLIENTS);
428         }
429
430         syslog(LOG_DEBUG, "Checking whether %s is a local or public client\n",
431                 CC->cs_addr);
432         for (i=0; i<num_parms(public_clients); ++i) {
433                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
434                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
435                         syslog(LOG_DEBUG, "... yes its local.\n");
436                         return(1);
437                 }
438         }
439
440         /* No hits.  This is not a public client. */
441         syslog(LOG_DEBUG, "... no it isn't.\n");
442         return(0);
443 }
444
445
446 /*
447  * the client is identifying itself to the server
448  */
449 void cmd_iden(char *argbuf)
450 {
451         int dev_code;
452         int cli_code;
453         int rev_level;
454         char desc[128];
455         char from_host[128];
456
457         if (num_parms(argbuf)<4) {
458                 cprintf("%d usage error\n", ERROR + ILLEGAL_VALUE);
459                 return;
460         }
461
462         dev_code = extract_int(argbuf,0);
463         cli_code = extract_int(argbuf,1);
464         rev_level = extract_int(argbuf,2);
465         extract_token(desc, argbuf, 3, '|', sizeof desc);
466
467         safestrncpy(from_host, config.c_fqdn, sizeof from_host);
468         from_host[sizeof from_host - 1] = 0;
469         if (num_parms(argbuf)>=5) extract_token(from_host, argbuf, 4, '|', sizeof from_host);
470
471         CC->cs_clientdev = dev_code;
472         CC->cs_clienttyp = cli_code;
473         CC->cs_clientver = rev_level;
474         safestrncpy(CC->cs_clientname, desc, sizeof CC->cs_clientname);
475         CC->cs_clientname[31] = 0;
476
477         /* For local sockets and public clients, trust the hostname supplied by the client */
478         if ( (CC->is_local_socket) || (is_public_client()) ) {
479                 safestrncpy(CC->cs_host, from_host, sizeof CC->cs_host);
480                 CC->cs_host[sizeof CC->cs_host - 1] = 0;
481                 CC->cs_addr[0] = 0;
482         }
483
484         syslog(LOG_NOTICE, "Client %d/%d/%01d.%02d (%s) from %s\n",
485                 dev_code,
486                 cli_code,
487                 (rev_level / 100),
488                 (rev_level % 100),
489                 desc,
490                 CC->cs_host
491         );
492         cprintf("%d Ok\n",CIT_OK);
493 }
494
495
496 /* 
497  * help_subst()  -  support routine for help file viewer
498  */
499 void help_subst(char *strbuf, char *source, char *dest)
500 {
501         char workbuf[SIZ];
502         int p;
503
504         while (p = pattern2(strbuf, source), (p >= 0)) {
505                 strcpy(workbuf, &strbuf[p + strlen(source)]);
506                 strcpy(&strbuf[p], dest);
507                 strcat(strbuf, workbuf);
508         }
509 }
510
511 void do_help_subst(char *buffer)
512 {
513         char buf2[16];
514
515         help_subst(buffer, "^nodename", config.c_nodename);
516         help_subst(buffer, "^humannode", config.c_humannode);
517         help_subst(buffer, "^fqdn", config.c_fqdn);
518         help_subst(buffer, "^username", CC->user.fullname);
519         snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
520         help_subst(buffer, "^usernum", buf2);
521         help_subst(buffer, "^sysadm", config.c_sysadm);
522         help_subst(buffer, "^variantname", CITADEL);
523         snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
524         help_subst(buffer, "^maxsessions", buf2);
525         help_subst(buffer, "^bbsdir", ctdl_message_dir);
526 }
527
528
529 typedef const char *ccharp;
530 /*
531  * display system messages or help
532  */
533 void cmd_mesg(char *mname)
534 {
535         FILE *mfp;
536         char targ[256];
537         char buf[256];
538         char buf2[256];
539         char *dirs[2];
540         DIR *dp;
541         struct dirent *d;
542
543         extract_token(buf, mname, 0, '|', sizeof buf);
544
545         dirs[0] = strdup(ctdl_message_dir);
546         dirs[1] = strdup(ctdl_hlp_dir);
547
548         snprintf(buf2, sizeof buf2, "%s.%d.%d",
549                 buf, CC->cs_clientdev, CC->cs_clienttyp);
550
551         /* If the client requested "?" then produce a listing */
552         if (!strcmp(buf, "?")) {
553                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
554                 dp = opendir(dirs[1]);
555                 if (dp != NULL) {
556                         while (d = readdir(dp), d != NULL) {
557                                 if (d->d_name[0] != '.') {
558                                         cprintf(" %s\n", d->d_name);
559                                 }
560                         }
561                         closedir(dp);
562                 }
563                 cprintf("000\n");
564                 free(dirs[0]);
565                 free(dirs[1]);
566                 return;
567         }
568
569         /* Otherwise, look for the requested file by name. */
570         else {
571                 mesg_locate(targ, sizeof targ, buf2, 2, (const ccharp*)dirs);
572                 if (IsEmptyStr(targ)) {
573                         snprintf(buf2, sizeof buf2, "%s.%d",
574                                                         buf, CC->cs_clientdev);
575                         mesg_locate(targ, sizeof targ, buf2, 2,
576                                     (const ccharp*)dirs);
577                         if (IsEmptyStr(targ)) {
578                                 mesg_locate(targ, sizeof targ, buf, 2,
579                                             (const ccharp*)dirs);
580                         }       
581                 }
582         }
583
584         free(dirs[0]);
585         free(dirs[1]);
586
587         if (IsEmptyStr(targ)) {
588                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
589                         ERROR + FILE_NOT_FOUND,
590                         mname,
591                         ctdl_message_dir,
592                         ctdl_hlp_dir
593                 );
594                 return;
595         }
596
597         mfp = fopen(targ, "r");
598         if (mfp==NULL) {
599                 cprintf("%d Cannot open '%s': %s\n",
600                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
601                 return;
602         }
603         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
604
605         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
606                 buf[strlen(buf)-1] = 0;
607                 do_help_subst(buf);
608                 cprintf("%s\n",buf);
609         }
610
611         fclose(mfp);
612         cprintf("000\n");
613 }
614
615
616 /*
617  * enter system messages or help
618  */
619 void cmd_emsg(char *mname)
620 {
621         FILE *mfp;
622         char targ[256];
623         char buf[256];
624         char *dirs[2];
625         int a;
626
627         unbuffer_output();
628
629         if (CtdlAccessCheck(ac_aide)) return;
630
631         extract_token(buf, mname, 0, '|', sizeof buf);
632         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
633                 if (buf[a] == '/') buf[a] = '.';
634         }
635
636         dirs[0] = strdup(ctdl_message_dir);
637         dirs[1] = strdup(ctdl_hlp_dir);
638
639         mesg_locate(targ, sizeof targ, buf, 2, (const ccharp*)dirs);
640         free(dirs[0]);
641         free(dirs[1]);
642
643         if (IsEmptyStr(targ)) {
644                 snprintf(targ, sizeof targ, 
645                                  "%s/%s",
646                                  ctdl_hlp_dir, buf);
647         }
648
649         mfp = fopen(targ,"w");
650         if (mfp==NULL) {
651                 cprintf("%d Cannot open '%s': %s\n",
652                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
653                 return;
654         }
655         cprintf("%d %s\n", SEND_LISTING, targ);
656
657         while (client_getln(buf, sizeof buf) >=0 && strcmp(buf, "000")) {
658                 fprintf(mfp, "%s\n", buf);
659         }
660
661         fclose(mfp);
662 }
663
664
665 /* Don't show the names of private rooms unless the viewing
666  * user also knows the rooms.
667  */
668 void GenerateRoomDisplay(char *real_room,
669                         CitContext *viewed,
670                         CitContext *viewer) {
671
672         int ra;
673
674         strcpy(real_room, viewed->room.QRname);
675         if (viewed->room.QRflags & QR_MAILBOX) {
676                 strcpy(real_room, &real_room[11]);
677         }
678         if (viewed->room.QRflags & QR_PRIVATE) {
679                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
680                 if ( (ra & UA_KNOWN) == 0) {
681                         strcpy(real_room, " ");
682                 }
683         }
684
685         if (viewed->cs_flags & CS_CHAT) {
686                 while (strlen(real_room) < 14) {
687                         strcat(real_room, " ");
688                 }
689                 strcpy(&real_room[14], "<chat>");
690         }
691
692 }
693
694 /*
695  * Convenience function.
696  */
697 int CtdlAccessCheck(int required_level) {
698
699         if (CC->internal_pgm) return(0);
700         if (required_level >= ac_internal) {
701                 cprintf("%d This is not a user-level command.\n",
702                         ERROR + HIGHER_ACCESS_REQUIRED);
703                 return(-1);
704         }
705
706         if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (!config.c_guest_logins)) {
707                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
708                 return(-1);
709         }
710
711         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
712                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
713                 return(-1);
714         }
715
716         if (CC->user.axlevel >= AxAideU) return(0);
717         if (required_level >= ac_aide) {
718                 cprintf("%d This command requires Admin access.\n",
719                         ERROR + HIGHER_ACCESS_REQUIRED);
720                 return(-1);
721         }
722
723         if (is_room_aide()) return(0);
724         if (required_level >= ac_room_aide) {
725                 cprintf("%d This command requires Admin or Room Admin access.\n",
726                         ERROR + HIGHER_ACCESS_REQUIRED);
727                 return(-1);
728         }
729
730         /* shhh ... succeed quietly */
731         return(0);
732 }
733
734
735
736 /*
737  * Terminate another running session
738  */
739 void cmd_term(char *cmdbuf)
740 {
741         int session_num;
742         int terminated = 0;
743
744         session_num = extract_int(cmdbuf, 0);
745
746         terminated = CtdlTerminateOtherSession(session_num);
747
748         if (terminated < 0) {
749                 cprintf("%d You can't kill your own session.\n", ERROR + ILLEGAL_VALUE);
750                 return;
751         }
752
753         if (terminated & TERM_FOUND) {
754                 if (terminated == TERM_KILLED) {
755                         cprintf("%d Session terminated.\n", CIT_OK);
756                 }
757                 else {
758                         cprintf("%d You are not allowed to do that.\n",
759                                 ERROR + HIGHER_ACCESS_REQUIRED);
760                 }
761         }
762         else {
763                 cprintf("%d No such session.\n", ERROR + ILLEGAL_VALUE);
764         }
765 }
766
767
768 /* 
769  * get the paginator prompt
770  */
771 void cmd_more(char *argbuf) {
772         cprintf("%d %s\n", CIT_OK, config.c_moreprompt);
773 }
774
775
776 /*
777  * echo 
778  */
779 void cmd_echo(char *etext)
780 {
781         cprintf("%d %s\n", CIT_OK, etext);
782 }
783
784
785
786 /*
787  * Shut down the server
788  */
789 void cmd_down(char *argbuf) {
790         char *Reply ="%d Shutting down server.  Goodbye.\n";
791
792         if (CtdlAccessCheck(ac_aide)) return;
793
794         if (!IsEmptyStr(argbuf))
795         {
796                 int state = CIT_OK;
797                 restart_server = extract_int(argbuf, 0);
798                 
799                 if (restart_server > 0)
800                 {
801                         Reply = "%d citserver will now shut down and automatically restart.\n";
802                 }
803                 if ((restart_server > 0) && !running_as_daemon)
804                 {
805                         syslog(LOG_ERR, "The user requested restart, but not running as daemon! Geronimooooooo!\n");
806                         Reply = "%d Warning: citserver is not running in daemon mode and is therefore unlikely to restart automatically.\n";
807                         state = ERROR;
808                 }
809                 cprintf(Reply, state);
810         }
811         else
812         {
813                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN); 
814         }
815         CC->kill_me = KILLME_SERVER_SHUTTING_DOWN;
816         server_shutting_down = 1;
817 }
818
819
820 /*
821  * Halt the server without exiting the server process.
822  */
823 void cmd_halt(char *argbuf) {
824
825         if (CtdlAccessCheck(ac_aide)) return;
826
827         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
828         server_shutting_down = 1;
829         shutdown_and_halt = 1;
830 }
831
832
833 /*
834  * Schedule or cancel a server shutdown
835  */
836 void cmd_scdn(char *argbuf)
837 {
838         int new_state;
839         int state = CIT_OK;
840         char *Reply = "%d %d\n";
841
842         if (CtdlAccessCheck(ac_aide)) return;
843
844         new_state = extract_int(argbuf, 0);
845         if ((new_state == 2) || (new_state == 3))
846         {
847                 restart_server = 1;
848                 if (!running_as_daemon)
849                 {
850                         syslog(LOG_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
851                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
852                         state = ERROR;
853                 }
854
855                 restart_server = extract_int(argbuf, 0);
856                 new_state -= 2;
857         }
858         if ((new_state == 0) || (new_state == 1)) {
859                 ScheduledShutdown = new_state;
860         }
861         cprintf(Reply, state, ScheduledShutdown);
862 }
863
864
865 /*
866  * Set or unset asynchronous protocol mode
867  */
868 void cmd_asyn(char *argbuf)
869 {
870         int new_state;
871
872         new_state = extract_int(argbuf, 0);
873         if ((new_state == 0) || (new_state == 1)) {
874                 CC->is_async = new_state;
875         }
876         cprintf("%d %d\n", CIT_OK, CC->is_async);
877 }
878
879
880
881 /*
882  * Back-end function for starting a session
883  */
884 void begin_session(CitContext *con)
885 {
886         /* 
887          * Initialize some variables specific to our context.
888          */
889         con->logged_in = 0;
890         con->internal_pgm = 0;
891         con->download_fp = NULL;
892         con->upload_fp = NULL;
893         con->cached_msglist = NULL;
894         con->cached_num_msgs = 0;
895         con->FirstExpressMessage = NULL;
896         time(&con->lastcmd);
897         time(&con->lastidle);
898         strcpy(con->lastcmdname, "    ");
899         strcpy(con->cs_clientname, "(unknown)");
900         strcpy(con->curr_user, NLI);
901         *con->net_node = '\0';
902         *con->fake_username = '\0';
903         *con->fake_hostname = '\0';
904         *con->fake_roomname = '\0';
905         *con->cs_clientinfo = '\0';
906         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
907         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
908         con->cs_UDSclientUID = -1;
909         con->cs_host[sizeof con->cs_host - 1] = 0;
910         if (!CC->is_local_socket) {
911                 locate_host(con->cs_host, sizeof con->cs_host,
912                         con->cs_addr, sizeof con->cs_addr,
913                         con->client_socket
914                 );
915         }
916         else {
917                 con->cs_host[0] = 0;
918                 con->cs_addr[0] = 0;
919 #ifdef HAVE_STRUCT_UCRED
920                 {
921                         /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
922                         struct ucred credentials;
923                         socklen_t ucred_length = sizeof(struct ucred);
924                         
925                         /*fill in the user data structure */
926                         if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
927                                 syslog(LOG_NOTICE, "could obtain credentials from unix domain socket");
928                                 
929                         }
930                         else {          
931                                 /* the process ID of the process on the other side of the socket */
932                                 /* credentials.pid; */
933                                 
934                                 /* the effective UID of the process on the other side of the socket  */
935                                 con->cs_UDSclientUID = credentials.uid;
936                                 
937                                 /* the effective primary GID of the process on the other side of the socket */
938                                 /* credentials.gid; */
939                                 
940                                 /* To get supplemental groups, we will have to look them up in our account
941                                    database, after a reverse lookup on the UID to get the account name.
942                                    We can take this opportunity to check to see if this is a legit account.
943                                 */
944                                 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
945                                          "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ", 
946                                          credentials.pid,
947                                          credentials.uid,
948                                          credentials.gid);
949                         }
950                 }
951 #endif
952         }
953         con->cs_flags = 0;
954         con->upload_type = UPL_FILE;
955         con->dl_is_net = 0;
956
957         con->nologin = 0;
958         if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
959                 con->nologin = 1;
960         }
961
962         if (!CC->is_local_socket) {
963                 syslog(LOG_NOTICE, "Session (%s) started from %s (%s).\n", con->ServiceName, con->cs_host, con->cs_addr);
964         }
965         else {
966                 syslog(LOG_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
967         }
968
969         /* Run any session startup routines registered by loadable modules */
970         PerformSessionHooks(EVT_START);
971 }
972
973
974 void citproto_begin_session() {
975         if (CC->nologin==1) {
976                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
977                         ERROR + MAX_SESSIONS_EXCEEDED,
978                         config.c_nodename, config.c_maxsessions
979                 );
980                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
981         }
982         else {
983                 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
984                 CC->can_receive_im = 1;
985         }
986 }
987
988
989 void citproto_begin_admin_session() {
990         CC->internal_pgm = 1;
991         cprintf("%d %s Citadel server ADMIN CONNECTION ready.\n", CIT_OK, config.c_nodename);
992 }
993
994
995 void cmd_noop(char *argbuf)
996 {
997         cprintf("%d%cok\n", CIT_OK, CtdlCheckExpress() );
998 }
999
1000
1001 void cmd_qnop(char *argbuf)
1002 {
1003         /* do nothing, this command returns no response */
1004 }
1005
1006
1007 void cmd_quit(char *argbuf)
1008 {
1009         cprintf("%d Goodbye.\n", CIT_OK);
1010         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
1011 }
1012
1013
1014 void cmd_lout(char *argbuf)
1015 {
1016         if (CC->logged_in) 
1017                 CtdlUserLogout();
1018         cprintf("%d logged out.\n", CIT_OK);
1019 }
1020
1021
1022 /*
1023  * This loop recognizes all server commands.
1024  */
1025 void do_command_loop(void) {
1026         char cmdbuf[SIZ];
1027         
1028         time(&CC->lastcmd);
1029         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1030         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1031                 syslog(LOG_ERR, "Citadel client disconnected: ending session.\n");
1032                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
1033                 return;
1034         }
1035
1036         /* Log the server command, but don't show passwords... */
1037         if ( (strncasecmp(cmdbuf, "PASS", 4)) && (strncasecmp(cmdbuf, "SETP", 4)) ) {
1038                 syslog(LOG_INFO, "[%d][%s(%ld)] %s",
1039                         CC->cs_pid, CC->curr_user, CC->user.usernum, cmdbuf
1040                 );
1041         }
1042         else {
1043                 syslog(LOG_INFO, "[%d][%s(%ld)] <password command hidden from log>",
1044                         CC->cs_pid, CC->curr_user, CC->user.usernum
1045                 );
1046         }
1047
1048         buffer_output();
1049
1050         /*
1051          * Let other clients see the last command we executed, and
1052          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
1053          */
1054         if ( (strncasecmp(cmdbuf, "NOOP", 4))
1055            && (strncasecmp(cmdbuf, "QNOP", 4))
1056            && (strncasecmp(cmdbuf, "PEXP", 4))
1057            && (strncasecmp(cmdbuf, "GEXP", 4))
1058            && (strncasecmp(cmdbuf, "RWHO", 4))
1059            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
1060                 strcpy(CC->lastcmdname, "    ");
1061                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
1062                 time(&CC->lastidle);
1063         }
1064         
1065         if ((strncasecmp(cmdbuf, "ENT0", 4))
1066            && (strncasecmp(cmdbuf, "MESG", 4))
1067            && (strncasecmp(cmdbuf, "MSGS", 4)))
1068         {
1069            CC->cs_flags &= ~CS_POSTING;
1070         }
1071                    
1072         if (!DLoader_Exec_Cmd(cmdbuf)) {
1073                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
1074         }       
1075
1076         unbuffer_output();
1077
1078         /* Run any after-each-command routines registered by modules */
1079         PerformSessionHooks(EVT_CMD);
1080 }
1081
1082
1083 /*
1084  * This loop performs all asynchronous functions.
1085  */
1086 void do_async_loop(void) {
1087         PerformSessionHooks(EVT_ASYNC);
1088 }
1089
1090
1091 /*****************************************************************************/
1092 /*                      MODULE INITIALIZATION STUFF                          */
1093 /*****************************************************************************/
1094
1095 CTDL_MODULE_INIT(citserver)
1096 {
1097         if (!threading) {
1098                 CtdlRegisterProtoHook(cmd_noop, "NOOP", "no operation");
1099                 CtdlRegisterProtoHook(cmd_qnop, "QNOP", "no operation with no response");
1100                 CtdlRegisterProtoHook(cmd_quit, "QUIT", "log out and disconnect from server");
1101                 CtdlRegisterProtoHook(cmd_lout, "LOUT", "log out but do not disconnect from server");
1102                 CtdlRegisterProtoHook(cmd_asyn, "ASYN", "enable asynchronous server responses");
1103                 CtdlRegisterProtoHook(cmd_info, "INFO", "fetch server capabilities and configuration");
1104                 CtdlRegisterProtoHook(cmd_mesg, "MESG", "fetch system banners");
1105                 CtdlRegisterProtoHook(cmd_emsg, "EMSG", "submit system banners");
1106                 CtdlRegisterProtoHook(cmd_echo, "ECHO", "echo text back to the client");
1107                 CtdlRegisterProtoHook(cmd_more, "MORE", "fetch the paginator prompt");
1108                 CtdlRegisterProtoHook(cmd_iden, "IDEN", "identify the client software and location");
1109                 CtdlRegisterProtoHook(cmd_term, "TERM", "terminate another running session");
1110                 CtdlRegisterProtoHook(cmd_down, "DOWN", "perform a server shutdown");
1111                 CtdlRegisterProtoHook(cmd_halt, "HALT", "halt the server without exiting the server process");
1112                 CtdlRegisterProtoHook(cmd_scdn, "SCDN", "schedule or cancel a server shutdown");
1113                 CtdlRegisterProtoHook(cmd_time, "TIME", "fetch the date and time from the server");
1114         }
1115         /* return our id for the Log */
1116         return "citserver";
1117 }