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