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