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