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