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