Merge branch 'master' of ssh://git.citadel.org/appl/gitroot/citadel
[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                 cprintf("%d\n", config.c_disable_newu);
284         }
285         else {
286                 cprintf("1\n"); /* "create new user" does not work with non-native auth modes */
287         }
288
289         cprintf("%s\n", config.c_default_cal_zone);
290
291         /* thread load averages -- temporarily disabled during refactoring of this code */
292         cprintf("0\n");         /* load average */
293         cprintf("0\n");         /* worker average */
294         cprintf("0\n");         /* thread count */
295
296         cprintf("1\n");         /* yes, Sieve mail filtering is supported */
297         cprintf("%d\n", config.c_enable_fulltext);
298         cprintf("%s\n", svn_revision());
299
300         if (config.c_auth_mode == AUTHMODE_NATIVE) {
301                 cprintf("%d\n", openid_level_supported); /* OpenID is enabled when using native auth */
302         }
303         else {
304                 cprintf("0\n"); /* OpenID is disabled when using non-native auth */
305         }
306
307         cprintf("%d\n", config.c_guest_logins);
308         
309         cprintf("000\n");
310 }
311
312
313 /*
314  * returns an asterisk if there are any instant messages waiting,
315  * space otherwise.
316  */
317 char CtdlCheckExpress(void) {
318         if (CC->FirstExpressMessage == NULL) {
319                 return(' ');
320         }
321         else {
322                 return('*');
323         }
324 }
325
326 void cmd_time(char *argbuf)
327 {
328    time_t tv;
329    struct tm tmp;
330    
331    tv = time(NULL);
332    localtime_r(&tv, &tmp);
333    
334    /* timezone and daylight global variables are not portable. */
335 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
336    cprintf("%d %ld|%ld|%d|%ld\n", CIT_OK, (long)tv, tmp.tm_gmtoff, tmp.tm_isdst, server_startup_time);
337 #else
338    cprintf("%d %ld|%ld|%d|%ld\n", CIT_OK, (long)tv, timezone, tmp.tm_isdst, server_startup_time);
339 #endif
340 }
341
342
343 /*
344  * Check originating host against the public_clients file.  This determines
345  * whether the client is allowed to change the hostname for this session
346  * (for example, to show the location of the user rather than the location
347  * of the client).
348  */
349 int is_public_client(void)
350 {
351         char buf[1024];
352         char addrbuf[1024];
353         FILE *fp;
354         int i;
355         char *public_clientspos;
356         char *public_clientsend;
357         char *paddr = NULL;
358         struct stat statbuf;
359         static time_t pc_timestamp = 0;
360         static char public_clients[SIZ];
361         static char public_clients_file[SIZ];
362
363 #define LOCALHOSTSTR "127.0.0.1"
364
365         snprintf(public_clients_file, sizeof public_clients_file, "%s/public_clients", ctdl_etc_dir);
366
367         /*
368          * Check the time stamp on the public_clients file.  If it's been
369          * updated since the last time we were here (or if this is the first
370          * time we've been through the loop), read its contents and learn
371          * the IP addresses of the listed hosts.
372          */
373         if (stat(public_clients_file, &statbuf) != 0) {
374                 /* No public_clients file exists, so bail out */
375                 syslog(LOG_WARNING, "Warning: '%s' does not exist\n", 
376                                 public_clients_file);
377                 return(0);
378         }
379
380         if (statbuf.st_mtime > pc_timestamp) {
381                 begin_critical_section(S_PUBLIC_CLIENTS);
382                 syslog(LOG_INFO, "Loading %s\n", public_clients_file);
383
384                 public_clientspos = &public_clients[0];
385                 public_clientsend = public_clientspos + SIZ;
386                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
387                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
388                 
389                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
390                         *(public_clientspos++) = '|';
391                         paddr = &addrbuf[0];
392                         while (!IsEmptyStr (paddr) && 
393                                (public_clientspos < public_clientsend))
394                                 *(public_clientspos++) = *(paddr++);
395                 }
396
397                 fp = fopen(public_clients_file, "r");
398                 if (fp != NULL) 
399                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
400                                (public_clientspos < public_clientsend)){
401                                 char *ptr;
402                                 ptr = buf;
403                                 while (!IsEmptyStr(ptr)) {
404                                         if (*ptr == '#') {
405                                                 *ptr = 0;
406                                                 break;
407                                         }
408                                 else ptr++;
409                                 }
410                                 ptr--;
411                                 while (ptr>buf && isspace(*ptr)) {
412                                         *(ptr--) = 0;
413                                 }
414                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
415                                         *(public_clientspos++) = '|';
416                                         paddr = addrbuf;
417                                         while (!IsEmptyStr(paddr) && 
418                                                (public_clientspos < public_clientsend)){
419                                                 *(public_clientspos++) = *(paddr++);
420                                         }
421                                 }
422                         }
423                 if (fp != NULL) fclose(fp);
424                 pc_timestamp = time(NULL);
425                 end_critical_section(S_PUBLIC_CLIENTS);
426         }
427
428         syslog(LOG_DEBUG, "Checking whether %s is a local or public client\n",
429                 CC->cs_addr);
430         for (i=0; i<num_parms(public_clients); ++i) {
431                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
432                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
433                         syslog(LOG_DEBUG, "... yes its local.\n");
434                         return(1);
435                 }
436         }
437
438         /* No hits.  This is not a public client. */
439         syslog(LOG_DEBUG, "... no it isn't.\n");
440         return(0);
441 }
442
443
444 /*
445  * the client is identifying itself to the server
446  */
447 void cmd_iden(char *argbuf)
448 {
449         int dev_code;
450         int cli_code;
451         int rev_level;
452         char desc[128];
453         char from_host[128];
454
455         if (num_parms(argbuf)<4) {
456                 cprintf("%d usage error\n", ERROR + ILLEGAL_VALUE);
457                 return;
458         }
459
460         dev_code = extract_int(argbuf,0);
461         cli_code = extract_int(argbuf,1);
462         rev_level = extract_int(argbuf,2);
463         extract_token(desc, argbuf, 3, '|', sizeof desc);
464
465         safestrncpy(from_host, config.c_fqdn, sizeof from_host);
466         from_host[sizeof from_host - 1] = 0;
467         if (num_parms(argbuf)>=5) extract_token(from_host, argbuf, 4, '|', sizeof from_host);
468
469         CC->cs_clientdev = dev_code;
470         CC->cs_clienttyp = cli_code;
471         CC->cs_clientver = rev_level;
472         safestrncpy(CC->cs_clientname, desc, sizeof CC->cs_clientname);
473         CC->cs_clientname[31] = 0;
474
475         /* For local sockets and public clients, trust the hostname supplied by the client */
476         if ( (CC->is_local_socket) || (is_public_client()) ) {
477                 safestrncpy(CC->cs_host, from_host, sizeof CC->cs_host);
478                 CC->cs_host[sizeof CC->cs_host - 1] = 0;
479                 CC->cs_addr[0] = 0;
480         }
481
482         syslog(LOG_NOTICE, "Client %d/%d/%01d.%02d (%s) from %s\n",
483                 dev_code,
484                 cli_code,
485                 (rev_level / 100),
486                 (rev_level % 100),
487                 desc,
488                 CC->cs_host
489         );
490         cprintf("%d Ok\n",CIT_OK);
491 }
492
493 typedef const char *ccharp;
494 /*
495  * display system messages or help
496  */
497 void cmd_mesg(char *mname)
498 {
499         FILE *mfp;
500         char targ[256];
501         char buf[256];
502         char buf2[256];
503         char *dirs[2];
504         DIR *dp;
505         struct dirent *d;
506
507         extract_token(buf, mname, 0, '|', sizeof buf);
508
509         dirs[0] = strdup(ctdl_message_dir);
510         dirs[1] = strdup(ctdl_hlp_dir);
511
512         snprintf(buf2, sizeof buf2, "%s.%d.%d",
513                 buf, CC->cs_clientdev, CC->cs_clienttyp);
514
515         /* If the client requested "?" then produce a listing */
516         if (!strcmp(buf, "?")) {
517                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
518                 dp = opendir(dirs[1]);
519                 if (dp != NULL) {
520                         while (d = readdir(dp), d != NULL) {
521                                 if (d->d_name[0] != '.') {
522                                         cprintf(" %s\n", d->d_name);
523                                 }
524                         }
525                         closedir(dp);
526                 }
527                 cprintf("000\n");
528                 free(dirs[0]);
529                 free(dirs[1]);
530                 return;
531         }
532
533         /* Otherwise, look for the requested file by name. */
534         else {
535                 mesg_locate(targ, sizeof targ, buf2, 2, (const ccharp*)dirs);
536                 if (IsEmptyStr(targ)) {
537                         snprintf(buf2, sizeof buf2, "%s.%d",
538                                                         buf, CC->cs_clientdev);
539                         mesg_locate(targ, sizeof targ, buf2, 2,
540                                     (const ccharp*)dirs);
541                         if (IsEmptyStr(targ)) {
542                                 mesg_locate(targ, sizeof targ, buf, 2,
543                                             (const ccharp*)dirs);
544                         }       
545                 }
546         }
547
548         free(dirs[0]);
549         free(dirs[1]);
550
551         if (IsEmptyStr(targ)) {
552                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
553                         ERROR + FILE_NOT_FOUND,
554                         mname,
555                         ctdl_message_dir,
556                         ctdl_hlp_dir
557                 );
558                 return;
559         }
560
561         mfp = fopen(targ, "r");
562         if (mfp==NULL) {
563                 cprintf("%d Cannot open '%s': %s\n",
564                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
565                 return;
566         }
567         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
568
569         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
570                 buf[strlen(buf)-1] = 0;
571                 do_help_subst(buf);
572                 cprintf("%s\n",buf);
573         }
574
575         fclose(mfp);
576         cprintf("000\n");
577 }
578
579
580 /*
581  * enter system messages or help
582  */
583 void cmd_emsg(char *mname)
584 {
585         FILE *mfp;
586         char targ[256];
587         char buf[256];
588         char *dirs[2];
589         int a;
590
591         unbuffer_output();
592
593         if (CtdlAccessCheck(ac_aide)) return;
594
595         extract_token(buf, mname, 0, '|', sizeof buf);
596         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
597                 if (buf[a] == '/') buf[a] = '.';
598         }
599
600         dirs[0] = strdup(ctdl_message_dir);
601         dirs[1] = strdup(ctdl_hlp_dir);
602
603         mesg_locate(targ, sizeof targ, buf, 2, (const ccharp*)dirs);
604         free(dirs[0]);
605         free(dirs[1]);
606
607         if (IsEmptyStr(targ)) {
608                 snprintf(targ, sizeof targ, 
609                                  "%s/%s",
610                                  ctdl_hlp_dir, buf);
611         }
612
613         mfp = fopen(targ,"w");
614         if (mfp==NULL) {
615                 cprintf("%d Cannot open '%s': %s\n",
616                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
617                 return;
618         }
619         cprintf("%d %s\n", SEND_LISTING, targ);
620
621         while (client_getln(buf, sizeof buf) >=0 && strcmp(buf, "000")) {
622                 fprintf(mfp, "%s\n", buf);
623         }
624
625         fclose(mfp);
626 }
627
628
629 /* Don't show the names of private rooms unless the viewing
630  * user also knows the rooms.
631  */
632 void GenerateRoomDisplay(char *real_room,
633                         CitContext *viewed,
634                         CitContext *viewer) {
635
636         int ra;
637
638         strcpy(real_room, viewed->room.QRname);
639         if (viewed->room.QRflags & QR_MAILBOX) {
640                 strcpy(real_room, &real_room[11]);
641         }
642         if (viewed->room.QRflags & QR_PRIVATE) {
643                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
644                 if ( (ra & UA_KNOWN) == 0) {
645                         strcpy(real_room, " ");
646                 }
647         }
648
649         if (viewed->cs_flags & CS_CHAT) {
650                 while (strlen(real_room) < 14) {
651                         strcat(real_room, " ");
652                 }
653                 strcpy(&real_room[14], "<chat>");
654         }
655
656 }
657
658 /*
659  * Convenience function.
660  */
661 int CtdlAccessCheck(int required_level) {
662
663         if (CC->internal_pgm) return(0);
664         if (required_level >= ac_internal) {
665                 cprintf("%d This is not a user-level command.\n",
666                         ERROR + HIGHER_ACCESS_REQUIRED);
667                 return(-1);
668         }
669
670         if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (!config.c_guest_logins)) {
671                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
672                 return(-1);
673         }
674
675         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
676                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
677                 return(-1);
678         }
679
680         if (CC->user.axlevel >= AxAideU) return(0);
681         if (required_level >= ac_aide) {
682                 cprintf("%d This command requires Admin access.\n",
683                         ERROR + HIGHER_ACCESS_REQUIRED);
684                 return(-1);
685         }
686
687         if (is_room_aide()) return(0);
688         if (required_level >= ac_room_aide) {
689                 cprintf("%d This command requires Admin or Room Admin access.\n",
690                         ERROR + HIGHER_ACCESS_REQUIRED);
691                 return(-1);
692         }
693
694         /* shhh ... succeed quietly */
695         return(0);
696 }
697
698
699
700 /*
701  * Terminate another running session
702  */
703 void cmd_term(char *cmdbuf)
704 {
705         int session_num;
706         int terminated = 0;
707
708         session_num = extract_int(cmdbuf, 0);
709
710         terminated = CtdlTerminateOtherSession(session_num);
711
712         if (terminated < 0) {
713                 cprintf("%d You can't kill your own session.\n", ERROR + ILLEGAL_VALUE);
714                 return;
715         }
716
717         if (terminated & TERM_FOUND) {
718                 if (terminated == TERM_KILLED) {
719                         cprintf("%d Session terminated.\n", CIT_OK);
720                 }
721                 else {
722                         cprintf("%d You are not allowed to do that.\n",
723                                 ERROR + HIGHER_ACCESS_REQUIRED);
724                 }
725         }
726         else {
727                 cprintf("%d No such session.\n", ERROR + ILLEGAL_VALUE);
728         }
729 }
730
731
732 /* 
733  * get the paginator prompt
734  */
735 void cmd_more(char *argbuf) {
736         cprintf("%d %s\n", CIT_OK, config.c_moreprompt);
737 }
738
739
740 /*
741  * echo 
742  */
743 void cmd_echo(char *etext)
744 {
745         cprintf("%d %s\n", CIT_OK, etext);
746 }
747
748
749
750 /*
751  * Shut down the server
752  */
753 void cmd_down(char *argbuf) {
754         char *Reply ="%d Shutting down server.  Goodbye.\n";
755
756         if (CtdlAccessCheck(ac_aide)) return;
757
758         if (!IsEmptyStr(argbuf))
759         {
760                 int state = CIT_OK;
761                 restart_server = extract_int(argbuf, 0);
762                 
763                 if (restart_server > 0)
764                 {
765                         Reply = "%d citserver will now shut down and automatically restart.\n";
766                 }
767                 if ((restart_server > 0) && !running_as_daemon)
768                 {
769                         syslog(LOG_ERR, "The user requested restart, but not running as daemon! Geronimooooooo!\n");
770                         Reply = "%d Warning: citserver is not running in daemon mode and is therefore unlikely to restart automatically.\n";
771                         state = ERROR;
772                 }
773                 cprintf(Reply, state);
774         }
775         else
776         {
777                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN); 
778         }
779         CC->kill_me = KILLME_SERVER_SHUTTING_DOWN;
780         server_shutting_down = 1;
781 }
782
783
784 /*
785  * Halt the server without exiting the server process.
786  */
787 void cmd_halt(char *argbuf) {
788
789         if (CtdlAccessCheck(ac_aide)) return;
790
791         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
792         server_shutting_down = 1;
793         shutdown_and_halt = 1;
794 }
795
796
797 /*
798  * Schedule or cancel a server shutdown
799  */
800 void cmd_scdn(char *argbuf)
801 {
802         int new_state;
803         int state = CIT_OK;
804         char *Reply = "%d %d\n";
805
806         if (CtdlAccessCheck(ac_aide)) return;
807
808         new_state = extract_int(argbuf, 0);
809         if ((new_state == 2) || (new_state == 3))
810         {
811                 restart_server = 1;
812                 if (!running_as_daemon)
813                 {
814                         syslog(LOG_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
815                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
816                         state = ERROR;
817                 }
818
819                 restart_server = extract_int(argbuf, 0);
820                 new_state -= 2;
821         }
822         if ((new_state == 0) || (new_state == 1)) {
823                 ScheduledShutdown = new_state;
824         }
825         cprintf(Reply, state, ScheduledShutdown);
826 }
827
828
829 /*
830  * Set or unset asynchronous protocol mode
831  */
832 void cmd_asyn(char *argbuf)
833 {
834         int new_state;
835
836         new_state = extract_int(argbuf, 0);
837         if ((new_state == 0) || (new_state == 1)) {
838                 CC->is_async = new_state;
839         }
840         cprintf("%d %d\n", CIT_OK, CC->is_async);
841 }
842
843
844
845 /*
846  * Back-end function for starting a session
847  */
848 void begin_session(CitContext *con)
849 {
850         /* 
851          * Initialize some variables specific to our context.
852          */
853         con->logged_in = 0;
854         con->internal_pgm = 0;
855         con->download_fp = NULL;
856         con->upload_fp = NULL;
857         con->cached_msglist = NULL;
858         con->cached_num_msgs = 0;
859         con->FirstExpressMessage = NULL;
860         time(&con->lastcmd);
861         time(&con->lastidle);
862         strcpy(con->lastcmdname, "    ");
863         strcpy(con->cs_clientname, "(unknown)");
864         strcpy(con->curr_user, NLI);
865         *con->net_node = '\0';
866         *con->fake_username = '\0';
867         *con->fake_hostname = '\0';
868         *con->fake_roomname = '\0';
869         *con->cs_clientinfo = '\0';
870         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
871         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
872         con->cs_UDSclientUID = -1;
873         con->cs_host[sizeof con->cs_host - 1] = 0;
874         if (!CC->is_local_socket) {
875                 locate_host(con->cs_host, sizeof con->cs_host,
876                         con->cs_addr, sizeof con->cs_addr,
877                         con->client_socket
878                 );
879         }
880         else {
881                 con->cs_host[0] = 0;
882                 con->cs_addr[0] = 0;
883 #ifdef HAVE_STRUCT_UCRED
884                 {
885                         /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
886                         struct ucred credentials;
887                         socklen_t ucred_length = sizeof(struct ucred);
888                         
889                         /*fill in the user data structure */
890                         if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
891                                 syslog(LOG_NOTICE, "could obtain credentials from unix domain socket");
892                                 
893                         }
894                         else {          
895                                 /* the process ID of the process on the other side of the socket */
896                                 /* credentials.pid; */
897                                 
898                                 /* the effective UID of the process on the other side of the socket  */
899                                 con->cs_UDSclientUID = credentials.uid;
900                                 
901                                 /* the effective primary GID of the process on the other side of the socket */
902                                 /* credentials.gid; */
903                                 
904                                 /* To get supplemental groups, we will have to look them up in our account
905                                    database, after a reverse lookup on the UID to get the account name.
906                                    We can take this opportunity to check to see if this is a legit account.
907                                 */
908                                 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
909                                          "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ", 
910                                          credentials.pid,
911                                          credentials.uid,
912                                          credentials.gid);
913                         }
914                 }
915 #endif
916         }
917         con->cs_flags = 0;
918         con->upload_type = UPL_FILE;
919         con->dl_is_net = 0;
920
921         con->nologin = 0;
922         if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
923                 con->nologin = 1;
924         }
925
926         if (!CC->is_local_socket) {
927                 syslog(LOG_NOTICE, "Session (%s) started from %s (%s).\n", con->ServiceName, con->cs_host, con->cs_addr);
928         }
929         else {
930                 syslog(LOG_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
931         }
932
933         /* Run any session startup routines registered by loadable modules */
934         PerformSessionHooks(EVT_START);
935 }
936
937
938 void citproto_begin_session() {
939         if (CC->nologin==1) {
940                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
941                         ERROR + MAX_SESSIONS_EXCEEDED,
942                         config.c_nodename, config.c_maxsessions
943                 );
944                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
945         }
946         else {
947                 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
948                 CC->can_receive_im = 1;
949         }
950 }
951
952
953 void citproto_begin_admin_session() {
954         CC->internal_pgm = 1;
955         cprintf("%d %s Citadel server ADMIN CONNECTION ready.\n", CIT_OK, config.c_nodename);
956 }
957
958
959 void cmd_noop(char *argbuf)
960 {
961         cprintf("%d%cok\n", CIT_OK, CtdlCheckExpress() );
962 }
963
964
965 void cmd_qnop(char *argbuf)
966 {
967         /* do nothing, this command returns no response */
968 }
969
970
971 void cmd_quit(char *argbuf)
972 {
973         cprintf("%d Goodbye.\n", CIT_OK);
974         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
975 }
976
977
978 void cmd_lout(char *argbuf)
979 {
980         if (CC->logged_in) 
981                 CtdlUserLogout();
982         cprintf("%d logged out.\n", CIT_OK);
983 }
984
985
986 /*
987  * This loop recognizes all server commands.
988  */
989 void do_command_loop(void) {
990         char cmdbuf[SIZ];
991         
992         time(&CC->lastcmd);
993         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
994         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
995                 syslog(LOG_ERR, "Citadel client disconnected: ending session.\n");
996                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
997                 return;
998         }
999
1000         /* Log the server command, but don't show passwords... */
1001         if ( (strncasecmp(cmdbuf, "PASS", 4)) && (strncasecmp(cmdbuf, "SETP", 4)) ) {
1002                 syslog(LOG_INFO, "[%d][%s(%ld)] %s",
1003                         CC->cs_pid, CC->curr_user, CC->user.usernum, cmdbuf
1004                 );
1005         }
1006         else {
1007                 syslog(LOG_INFO, "[%d][%s(%ld)] <password command hidden from log>",
1008                         CC->cs_pid, CC->curr_user, CC->user.usernum
1009                 );
1010         }
1011
1012         buffer_output();
1013
1014         /*
1015          * Let other clients see the last command we executed, and
1016          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
1017          */
1018         if ( (strncasecmp(cmdbuf, "NOOP", 4))
1019            && (strncasecmp(cmdbuf, "QNOP", 4))
1020            && (strncasecmp(cmdbuf, "PEXP", 4))
1021            && (strncasecmp(cmdbuf, "GEXP", 4))
1022            && (strncasecmp(cmdbuf, "RWHO", 4))
1023            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
1024                 strcpy(CC->lastcmdname, "    ");
1025                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
1026                 time(&CC->lastidle);
1027         }
1028         
1029         if ((strncasecmp(cmdbuf, "ENT0", 4))
1030            && (strncasecmp(cmdbuf, "MESG", 4))
1031            && (strncasecmp(cmdbuf, "MSGS", 4)))
1032         {
1033            CC->cs_flags &= ~CS_POSTING;
1034         }
1035                    
1036         if (!DLoader_Exec_Cmd(cmdbuf)) {
1037                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
1038         }       
1039
1040         unbuffer_output();
1041
1042         /* Run any after-each-command routines registered by modules */
1043         PerformSessionHooks(EVT_CMD);
1044 }
1045
1046
1047 /*
1048  * This loop performs all asynchronous functions.
1049  */
1050 void do_async_loop(void) {
1051         PerformSessionHooks(EVT_ASYNC);
1052 }
1053
1054
1055 /*****************************************************************************/
1056 /*                      MODULE INITIALIZATION STUFF                          */
1057 /*****************************************************************************/
1058
1059 CTDL_MODULE_INIT(citserver)
1060 {
1061         if (!threading) {
1062                 CtdlRegisterProtoHook(cmd_noop, "NOOP", "no operation");
1063                 CtdlRegisterProtoHook(cmd_qnop, "QNOP", "no operation with no response");
1064                 CtdlRegisterProtoHook(cmd_quit, "QUIT", "log out and disconnect from server");
1065                 CtdlRegisterProtoHook(cmd_lout, "LOUT", "log out but do not disconnect from server");
1066                 CtdlRegisterProtoHook(cmd_asyn, "ASYN", "enable asynchronous server responses");
1067                 CtdlRegisterProtoHook(cmd_info, "INFO", "fetch server capabilities and configuration");
1068                 CtdlRegisterProtoHook(cmd_mesg, "MESG", "fetch system banners");
1069                 CtdlRegisterProtoHook(cmd_emsg, "EMSG", "submit system banners");
1070                 CtdlRegisterProtoHook(cmd_echo, "ECHO", "echo text back to the client");
1071                 CtdlRegisterProtoHook(cmd_more, "MORE", "fetch the paginator prompt");
1072                 CtdlRegisterProtoHook(cmd_iden, "IDEN", "identify the client software and location");
1073                 CtdlRegisterProtoHook(cmd_term, "TERM", "terminate another running session");
1074                 CtdlRegisterProtoHook(cmd_down, "DOWN", "perform a server shutdown");
1075                 CtdlRegisterProtoHook(cmd_halt, "HALT", "halt the server without exiting the server process");
1076                 CtdlRegisterProtoHook(cmd_scdn, "SCDN", "schedule or cancel a server shutdown");
1077                 CtdlRegisterProtoHook(cmd_time, "TIME", "fetch the date and time from the server");
1078         }
1079         /* return our id for the Log */
1080         return "citserver";
1081 }