EVT_LOGOUT hooks are now called with the thread's current
[citadel.git] / citadel / citserver.c
1 /* 
2  * $Id$
3  *
4  * Main source module for the Citadel server
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #if HAVE_BACKTRACE
30 #include <execinfo.h>
31 #endif
32
33 #include <ctype.h>
34 #include <string.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <limits.h>
38 #include <netdb.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <libcitadel.h>
44 #include "citadel.h"
45 #include "server.h"
46 #include "sysdep_decls.h"
47 #include "threads.h"
48 #include "citserver.h"
49 #include "config.h"
50 #include "database.h"
51 #include "housekeeping.h"
52 #include "user_ops.h"
53 #include "msgbase.h"
54 #include "support.h"
55 #include "locate_host.h"
56 #include "room_ops.h"
57 #include "file_ops.h"
58 #include "policy.h"
59 #include "control.h"
60 #include "euidindex.h"
61
62 #ifndef HAVE_SNPRINTF
63 #include "snprintf.h"
64 #endif
65
66 #include "ctdl_module.h"
67
68
69 struct CitContext *ContextList = NULL;
70 struct CitContext* next_session = NULL;
71 char *unique_session_numbers;
72 int ScheduledShutdown = 0;
73 time_t server_startup_time;
74 int panic_fd;
75
76 /**
77  * \brief print the actual stack frame.
78  */
79 void cit_backtrace(void)
80 {
81 #ifdef HAVE_BACKTRACE
82         void *stack_frames[50];
83         size_t size, i;
84         char **strings;
85
86
87         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
88         strings = backtrace_symbols(stack_frames, size);
89         for (i = 0; i < size; i++) {
90                 if (strings != NULL)
91                         lprintf(1, "%s\n", strings[i]);
92                 else
93                         lprintf(1, "%p\n", stack_frames[i]);
94         }
95         free(strings);
96 #endif
97 }
98
99 /**
100  * \brief print the actual stack frame.
101  */
102 void cit_panic_backtrace(int SigNum)
103 {
104 #ifdef HAVE_BACKTRACE
105         void *stack_frames[10];
106         size_t size, i;
107         char **strings;
108
109         printf("caught signal 11\n");
110         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
111         strings = backtrace_symbols(stack_frames, size);
112         for (i = 0; i < size; i++) {
113                 if (strings != NULL)
114                         lprintf(1, "%s\n", strings[i]);
115                 else
116                         lprintf(1, "%p\n", stack_frames[i]);
117         }
118         free(strings);
119 #endif
120         exit(-1);
121 }
122
123 /*
124  * Various things that need to be initialized at startup
125  */
126 void master_startup(void) {
127         struct timeval tv;
128         unsigned int seed;
129         FILE *urandom;
130         struct ctdlroom qrbuf;
131         
132         lprintf(CTDL_DEBUG, "master_startup() started\n");
133         time(&server_startup_time);
134
135         lprintf(CTDL_INFO, "Opening databases\n");
136         open_databases();
137
138         ctdl_thread_internal_init_tsd();
139         
140         CtdlThreadAllocTSD();
141         
142         check_ref_counts();
143
144         lprintf(CTDL_INFO, "Creating base rooms (if necessary)\n");
145         create_room(config.c_baseroom,  0, "", 0, 1, 0, VIEW_BBS);
146         create_room(AIDEROOM,           3, "", 0, 1, 0, VIEW_BBS);
147         create_room(SYSCONFIGROOM,      3, "", 0, 1, 0, VIEW_BBS);
148         create_room(config.c_twitroom,  0, "", 0, 1, 0, VIEW_BBS);
149
150         /* The "Local System Configuration" room doesn't need to be visible */
151         if (lgetroom(&qrbuf, SYSCONFIGROOM) == 0) {
152                 qrbuf.QRflags2 |= QR2_SYSTEM;
153                 lputroom(&qrbuf);
154         }
155
156         /* Aide needs to be public postable, else we're not RFC conformant. */
157         if (lgetroom(&qrbuf, AIDEROOM) == 0) {
158                 qrbuf.QRflags2 |= QR2_SMTP_PUBLIC;
159                 lputroom(&qrbuf);
160         }
161
162         lprintf(CTDL_INFO, "Seeding the pseudo-random number generator...\n");
163         urandom = fopen("/dev/urandom", "r");
164         if (urandom != NULL) {
165                 fread(&seed, sizeof seed, 1, urandom);
166                 fclose(urandom);
167         }
168         else {
169                 gettimeofday(&tv, NULL);
170                 seed = tv.tv_usec;
171         }
172         srandom(seed);
173
174         lprintf(CTDL_INFO, "Initializing ipgm secret\n");
175         get_config();
176         config.c_ipgm_secret = rand();
177         put_config();
178
179         lprintf(CTDL_DEBUG, "master_startup() finished\n");
180 }
181
182
183 /*
184  * Cleanup routine to be called when the server is shutting down.
185  */
186 void master_cleanup(int exitcode) {
187         struct CleanupFunctionHook *fcn;
188         static int already_cleaning_up = 0;
189
190         if (already_cleaning_up) while(1) sleep(1);
191         already_cleaning_up = 1;
192
193         /* Run any cleanup routines registered by loadable modules */
194         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
195                 (*fcn->h_function_pointer)();
196         }
197
198         /* Close the AdjRefCount queue file */
199         AdjRefCount(-1, 0);
200
201         /* Do system-dependent stuff */
202         sysdep_master_cleanup();
203         
204         /* Close databases */
205         lprintf(CTDL_INFO, "Closing databases\n");
206         close_databases();
207
208 #ifdef DEBUG_MEMORY_LEAKS
209         dump_heap();
210 #endif
211
212         /* If the operator requested a halt but not an exit, halt here. */
213         if (shutdown_and_halt) {
214                 lprintf(CTDL_NOTICE, "citserver: Halting server without exiting.\n");
215                 fflush(stdout); fflush(stderr);
216                 while(1) {
217                         sleep(32767);
218                 }
219         }
220         
221         release_control();
222
223         /* Now go away. */
224         lprintf(CTDL_NOTICE, "citserver: Exiting with status %d\n", exitcode);
225         fflush(stdout); fflush(stderr);
226         
227         if (restart_server != 0)
228                 exit(1);
229         exit(exitcode);
230 }
231
232
233
234 /*
235  * Terminate a session.
236  */
237 void RemoveContext (struct CitContext *con)
238 {
239         if (con==NULL) {
240                 lprintf(CTDL_ERR,
241                         "WARNING: RemoveContext() called with NULL!\n");
242                 return;
243         }
244         lprintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
245
246         /* Run any cleanup routines registered by loadable modules.
247          * Note: We have to "become_session()" because the cleanup functions
248          *       might make references to "CC" assuming it's the right one.
249          */
250         become_session(con);
251         logout();
252         PerformSessionHooks(EVT_STOP);
253         become_session(NULL);
254
255         lprintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
256
257         /* If the client is still connected, blow 'em away. */
258         lprintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
259         close(con->client_socket);
260
261         lprintf(CTDL_DEBUG, "Done with RemoveContext()\n");
262 }
263
264
265
266
267
268 /*
269  * cmd_info()  -  tell the client about this server
270  */
271 void cmd_info(void) {
272         cprintf("%d Server info:\n", LISTING_FOLLOWS);
273         cprintf("%d\n", CC->cs_pid);
274         cprintf("%s\n", config.c_nodename);
275         cprintf("%s\n", config.c_humannode);
276         cprintf("%s\n", config.c_fqdn);
277         cprintf("%s\n", CITADEL);
278         cprintf("%d\n", REV_LEVEL);
279         cprintf("%s\n", config.c_site_location);
280         cprintf("%s\n", config.c_sysadm);
281         cprintf("%d\n", SERVER_TYPE);
282         cprintf("%s\n", config.c_moreprompt);
283         cprintf("1\n"); /* 1 = yes, this system supports floors */
284         cprintf("1\n"); /* 1 = we support the extended paging options */
285         cprintf("%s\n", CC->cs_nonce);
286         cprintf("1\n"); /* 1 = yes, this system supports the QNOP command */
287
288 #ifdef HAVE_LDAP
289         cprintf("1\n"); /* 1 = yes, this server is LDAP-enabled */
290 #else
291         cprintf("0\n"); /* 1 = no, this server is not LDAP-enabled */
292 #endif
293
294         if (config.c_auth_mode == AUTHMODE_NATIVE) {
295                 cprintf("%d\n", config.c_disable_newu);
296         }
297         else {
298                 cprintf("1\n"); /* "create new user" does not work with non-native auth modes */
299         }
300
301         cprintf("%s\n", config.c_default_cal_zone);
302
303         /* Output load averages */
304         cprintf("%f\n", CtdlThreadLoadAvg);
305         cprintf("%f\n", CtdlThreadWorkerAvg);
306         cprintf("%d\n", CtdlThreadGetCount());
307
308         cprintf("1\n");         /* yes, Sieve mail filtering is supported */
309         cprintf("%d\n", config.c_enable_fulltext);
310         
311         cprintf("000\n");
312 }
313
314
315 /*
316  * returns an asterisk if there are any instant messages waiting,
317  * space otherwise.
318  */
319 char CtdlCheckExpress(void) {
320         if (CC->FirstExpressMessage == NULL) {
321                 return(' ');
322         }
323         else {
324                 return('*');
325         }
326 }
327
328 void cmd_time(void)
329 {
330    time_t tv;
331    struct tm tmp;
332    
333    tv = time(NULL);
334    localtime_r(&tv, &tmp);
335    
336    /* timezone and daylight global variables are not portable. */
337 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
338    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, tmp.tm_gmtoff, tmp.tm_isdst);
339 #else
340    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, timezone, tmp.tm_isdst);
341 #endif
342 }
343
344
345 /*
346  * Check originating host against the public_clients file.  This determines
347  * whether the client is allowed to change the hostname for this session
348  * (for example, to show the location of the user rather than the location
349  * of the client).
350  */
351 int is_public_client(void)
352 {
353         char buf[1024];
354         char addrbuf[1024];
355         FILE *fp;
356         int i;
357         char *public_clientspos;
358         char *public_clientsend;
359         char *paddr = NULL;
360         struct stat statbuf;
361         static time_t pc_timestamp = 0;
362         static char public_clients[SIZ];
363         static char public_clients_file[SIZ];
364
365 #define LOCALHOSTSTR "127.0.0.1"
366
367         snprintf(public_clients_file, 
368                          sizeof public_clients_file,
369                          "%s/public_clients",
370                          ctdl_etc_dir);
371
372         /*
373          * Check the time stamp on the public_clients file.  If it's been
374          * updated since the last time we were here (or if this is the first
375          * time we've been through the loop), read its contents and learn
376          * the IP addresses of the listed hosts.
377          */
378         if (stat(public_clients_file, &statbuf) != 0) {
379                 /* No public_clients file exists, so bail out */
380                 lprintf(CTDL_WARNING, "Warning: '%s' does not exist\n", 
381                                 public_clients_file);
382                 return(0);
383         }
384
385         if (statbuf.st_mtime > pc_timestamp) {
386                 begin_critical_section(S_PUBLIC_CLIENTS);
387                 lprintf(CTDL_INFO, "Loading %s\n", public_clients_file);
388
389                 public_clientspos = &public_clients[0];
390                 public_clientsend = public_clientspos + SIZ;
391                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
392                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
393                 
394                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
395                         *(public_clientspos++) = '|';
396                         paddr = &addrbuf[0];
397                         while (!IsEmptyStr (paddr) && 
398                                (public_clientspos < public_clientsend))
399                                 *(public_clientspos++) = *(paddr++);
400                 }
401
402                 fp = fopen(public_clients_file, "r");
403                 if (fp != NULL) 
404                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
405                                (public_clientspos < public_clientsend)){
406                                 char *ptr;
407                                 ptr = buf;
408                                 while (!IsEmptyStr(ptr)) {
409                                         if (*ptr == '#') {
410                                                 *ptr = 0;
411                                                 break;
412                                         }
413                                 else ptr++;
414                                 }
415                                 ptr--;
416                                 while (ptr>buf && isspace(*ptr)) {
417                                         *(ptr--) = 0;
418                                 }
419                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
420                                         *(public_clientspos++) = '|';
421                                         paddr = addrbuf;
422                                         while (!IsEmptyStr(paddr) && 
423                                                (public_clientspos < public_clientsend)){
424                                                 *(public_clientspos++) = *(paddr++);
425                                         }
426                                 }
427                         }
428                 fclose(fp);
429                 pc_timestamp = time(NULL);
430                 end_critical_section(S_PUBLIC_CLIENTS);
431         }
432
433         lprintf(CTDL_DEBUG, "Checking whether %s is a local or public client\n",
434                 CC->cs_addr);
435         for (i=0; i<num_parms(public_clients); ++i) {
436                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
437                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
438                         lprintf(CTDL_DEBUG, "... yes it is.\n");
439                         return(1);
440                 }
441         }
442
443         /* No hits.  This is not a public client. */
444         lprintf(CTDL_DEBUG, "... no it isn't.\n");
445         return(0);
446 }
447
448
449 /*
450  * the client is identifying itself to the server
451  */
452 void cmd_iden(char *argbuf)
453 {
454         int dev_code;
455         int cli_code;
456         int rev_level;
457         char desc[128];
458         char from_host[128];
459         struct in_addr addr;
460         int do_lookup = 0;
461
462         if (num_parms(argbuf)<4) {
463                 cprintf("%d usage error\n", ERROR + ILLEGAL_VALUE);
464                 return;
465         }
466
467         dev_code = extract_int(argbuf,0);
468         cli_code = extract_int(argbuf,1);
469         rev_level = extract_int(argbuf,2);
470         extract_token(desc, argbuf, 3, '|', sizeof desc);
471
472         safestrncpy(from_host, config.c_fqdn, sizeof from_host);
473         from_host[sizeof from_host - 1] = 0;
474         if (num_parms(argbuf)>=5) extract_token(from_host, argbuf, 4, '|', sizeof from_host);
475
476         CC->cs_clientdev = dev_code;
477         CC->cs_clienttyp = cli_code;
478         CC->cs_clientver = rev_level;
479         safestrncpy(CC->cs_clientname, desc, sizeof CC->cs_clientname);
480         CC->cs_clientname[31] = 0;
481
482         if (!IsEmptyStr(from_host)) {
483                 if (CC->is_local_socket) do_lookup = 1;
484                 else if (is_public_client()) do_lookup = 1;
485         }
486
487         if (do_lookup) {
488                 lprintf(CTDL_DEBUG, "Looking up hostname '%s'\n", from_host);
489                 if ((addr.s_addr = inet_addr(from_host)) != -1) {
490                         locate_host(CC->cs_host, sizeof CC->cs_host,
491                                 CC->cs_addr, sizeof CC->cs_addr,
492                                 &addr);
493                 }
494                 else {
495                         safestrncpy(CC->cs_host, from_host, sizeof CC->cs_host);
496                         CC->cs_host[sizeof CC->cs_host - 1] = 0;
497                 }
498         }
499
500         lprintf(CTDL_NOTICE, "Client %d/%d/%01d.%02d (%s) from %s\n",
501                 dev_code,
502                 cli_code,
503                 (rev_level / 100),
504                 (rev_level % 100),
505                 desc,
506                 CC->cs_host);
507         cprintf("%d Ok\n",CIT_OK);
508 }
509
510
511 /*
512  * display system messages or help
513  */
514 void cmd_mesg(char *mname)
515 {
516         FILE *mfp;
517         char targ[256];
518         char buf[256];
519         char buf2[256];
520         char *dirs[2];
521         DIR *dp;
522         struct dirent *d;
523
524         extract_token(buf, mname, 0, '|', sizeof buf);
525
526         dirs[0] = strdup(ctdl_message_dir);
527         dirs[1] = strdup(ctdl_hlp_dir);
528
529         snprintf(buf2, sizeof buf2, "%s.%d.%d",
530                 buf, CC->cs_clientdev, CC->cs_clienttyp);
531
532         /* If the client requested "?" then produce a listing */
533         if (!strcmp(buf, "?")) {
534                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
535                 dp = opendir(dirs[1]);
536                 if (dp != NULL) {
537                         while (d = readdir(dp), d != NULL) {
538                                 if (d->d_name[0] != '.') {
539                                         cprintf(" %s\n", d->d_name);
540                                 }
541                         }
542                         closedir(dp);
543                 }
544                 cprintf("000\n");
545                 free(dirs[0]);
546                 free(dirs[1]);
547                 return;
548         }
549
550         /* Otherwise, look for the requested file by name. */
551         else {
552                 mesg_locate(targ, sizeof targ, buf2, 2, (const char **)dirs);
553                 if (IsEmptyStr(targ)) {
554                         snprintf(buf2, sizeof buf2, "%s.%d",
555                                                         buf, CC->cs_clientdev);
556                         mesg_locate(targ, sizeof targ, buf2, 2,
557                                                         (const char **)dirs);
558                         if (IsEmptyStr(targ)) {
559                                 mesg_locate(targ, sizeof targ, buf, 2,
560                                                         (const char **)dirs);
561                         }       
562                 }
563         }
564
565         free(dirs[0]);
566         free(dirs[1]);
567
568         if (IsEmptyStr(targ)) {
569                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
570                         ERROR + FILE_NOT_FOUND,
571                         mname,
572                         ctdl_message_dir,
573                         ctdl_hlp_dir
574                 );
575                 return;
576         }
577
578         mfp = fopen(targ, "r");
579         if (mfp==NULL) {
580                 cprintf("%d Cannot open '%s': %s\n",
581                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
582                 return;
583         }
584         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
585
586         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
587                 buf[strlen(buf)-1] = 0;
588                 do_help_subst(buf);
589                 cprintf("%s\n",buf);
590         }
591
592         fclose(mfp);
593         cprintf("000\n");
594 }
595
596
597 /*
598  * enter system messages or help
599  */
600 void cmd_emsg(char *mname)
601 {
602         FILE *mfp;
603         char targ[256];
604         char buf[256];
605         char *dirs[2];
606         int a;
607
608         unbuffer_output();
609
610         if (CtdlAccessCheck(ac_aide)) return;
611
612         extract_token(buf, mname, 0, '|', sizeof buf);
613         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
614                 if (buf[a] == '/') buf[a] = '.';
615         }
616
617         dirs[0] = strdup(ctdl_message_dir);
618         dirs[1] = strdup(ctdl_hlp_dir);
619
620         mesg_locate(targ, sizeof targ, buf, 2, (const char**)dirs);
621         free(dirs[0]);
622         free(dirs[1]);
623
624         if (IsEmptyStr(targ)) {
625                 snprintf(targ, sizeof targ, 
626                                  "%s/%s",
627                                  ctdl_hlp_dir, buf);
628         }
629
630         mfp = fopen(targ,"w");
631         if (mfp==NULL) {
632                 cprintf("%d Cannot open '%s': %s\n",
633                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
634                 return;
635         }
636         cprintf("%d %s\n", SEND_LISTING, targ);
637
638         while (client_getln(buf, sizeof buf), strcmp(buf, "000")) {
639                 fprintf(mfp, "%s\n", buf);
640         }
641
642         fclose(mfp);
643 }
644
645
646 /* Don't show the names of private rooms unless the viewing
647  * user also knows the rooms.
648  */
649 void GenerateRoomDisplay(char *real_room,
650                         struct CitContext *viewed,
651                         struct CitContext *viewer) {
652
653         int ra;
654
655         strcpy(real_room, viewed->room.QRname);
656         if (viewed->room.QRflags & QR_MAILBOX) {
657                 strcpy(real_room, &real_room[11]);
658         }
659         if (viewed->room.QRflags & QR_PRIVATE) {
660                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
661                 if ( (ra & UA_KNOWN) == 0) {
662                         strcpy(real_room, "<private room>");
663                 }
664         }
665
666         if (viewed->cs_flags & CS_CHAT) {
667                 while (strlen(real_room) < 14) {
668                         strcat(real_room, " ");
669                 }
670                 strcpy(&real_room[14], "<chat>");
671         }
672
673 }
674
675 /*
676  * Convenience function.
677  */
678 int CtdlAccessCheck(int required_level) {
679
680         if (CC->internal_pgm) return(0);
681         if (required_level >= ac_internal) {
682                 cprintf("%d This is not a user-level command.\n",
683                         ERROR + HIGHER_ACCESS_REQUIRED);
684                 return(-1);
685         }
686
687         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
688                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
689                 return(-1);
690         }
691
692         if (CC->user.axlevel >= 6) return(0);
693         if (required_level >= ac_aide) {
694                 cprintf("%d This command requires Aide access.\n",
695                         ERROR + HIGHER_ACCESS_REQUIRED);
696                 return(-1);
697         }
698
699         if (is_room_aide()) return(0);
700         if (required_level >= ac_room_aide) {
701                 cprintf("%d This command requires Aide or Room Aide access.\n",
702                         ERROR + HIGHER_ACCESS_REQUIRED);
703                 return(-1);
704         }
705
706         /* shhh ... succeed quietly */
707         return(0);
708 }
709
710
711
712 /*
713  * Terminate another running session
714  */
715 void cmd_term(char *cmdbuf)
716 {
717         int session_num;
718         struct CitContext *ccptr;
719         int found_it = 0;
720         int allowed = 0;
721
722         session_num = extract_int(cmdbuf, 0);
723         if (session_num == CC->cs_pid) {
724                 cprintf("%d You can't kill your own session.\n", ERROR + ILLEGAL_VALUE);
725                 return;
726         }
727
728         lprintf(CTDL_DEBUG, "Locating session to kill\n");
729         begin_critical_section(S_SESSION_TABLE);
730         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
731                 if (session_num == ccptr->cs_pid) {
732                         found_it = 1;
733                         if ((ccptr->user.usernum == CC->user.usernum)
734                            || (CC->user.axlevel >= 6)) {
735                                 allowed = 1;
736                                 ccptr->kill_me = 1;
737                         }
738                         else {
739                                 allowed = 0;
740                         }
741                 }
742         }
743         end_critical_section(S_SESSION_TABLE);
744
745         if (found_it) {
746                 if (allowed) {
747                         cprintf("%d Session terminated.\n", CIT_OK);
748                 }
749                 else {
750                         cprintf("%d You are not allowed to do that.\n",
751                                 ERROR + HIGHER_ACCESS_REQUIRED);
752                 }
753         }
754         else {
755                 cprintf("%d No such session.\n", ERROR + ILLEGAL_VALUE);
756         }
757 }
758
759
760
761
762
763 /* 
764  * get the paginator prompt
765  */
766 void cmd_more(void) {
767         cprintf("%d %s\n", CIT_OK, config.c_moreprompt);
768 }
769
770 /*
771  * echo 
772  */
773 void cmd_echo(char *etext)
774 {
775         cprintf("%d %s\n", CIT_OK, etext);
776 }
777
778
779
780 /* 
781  * identify as internal program
782  */
783 void cmd_ipgm(char *argbuf)
784 {
785         int secret;
786
787         secret = extract_int(argbuf, 0);
788
789         /* For security reasons, we do NOT allow this command to run
790          * over the network.  Local sockets only.
791          */
792         if (!CC->is_local_socket) {
793                 sleep(5);
794                 cprintf("%d Authentication failed.\n",
795                         ERROR + PASSWORD_REQUIRED);
796         }
797         else if (secret == config.c_ipgm_secret) {
798                 CC->internal_pgm = 1;
799                 strcpy(CC->curr_user, "<internal program>");
800                 CC->cs_flags = CC->cs_flags|CS_STEALTH;
801                 cprintf("%d Authenticated as an internal program.\n", CIT_OK);
802         }
803         else {
804                 sleep(5);
805                 cprintf("%d Authentication failed.\n",
806                         ERROR + PASSWORD_REQUIRED);
807                 lprintf(CTDL_ERR, "Warning: ipgm authentication failed.\n");
808                 CC->kill_me = 1;
809         }
810
811         /* Now change the ipgm secret for the next round.
812          * (Disabled because it breaks concurrent scripts.  The fact that
813          * we no longer accept IPGM over the network should be sufficient
814          * to prevent brute-force attacks.  If you don't agree, uncomment
815          * this block.)
816         get_config();
817         config.c_ipgm_secret = rand();
818         put_config();
819         */
820 }
821
822
823 /*
824  * Shut down the server
825  */
826 void cmd_down(char *argbuf) {
827         char *Reply ="%d Shutting down server.  Goodbye.\n";
828
829         if (CtdlAccessCheck(ac_aide)) return;
830
831         if (!IsEmptyStr(argbuf))
832         {
833                 int state = CIT_OK;
834                 restart_server = extract_int(argbuf, 0);
835                 
836                 if (restart_server > 0)
837                         Reply = "%d Restarting server.  See you soon.\n";
838                 if ((restart_server > 0) && !running_as_daemon)
839                 {
840                         lprintf(CTDL_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
841                         Reply = "%d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
842                         state = ERROR;
843                 }
844                 cprintf(Reply, state);
845         }
846         else
847         {
848                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN);
849         }
850         CtdlThreadStopAll();
851 }
852
853 /*
854  * Halt the server without exiting the server process.
855  */
856 void cmd_halt(void) {
857
858         if (CtdlAccessCheck(ac_aide)) return;
859
860         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
861         CtdlThreadStopAll();
862         shutdown_and_halt = 1;
863 }
864
865 /*
866  * Schedule or cancel a server shutdown
867  */
868 void cmd_scdn(char *argbuf)
869 {
870         int new_state;
871         int state = CIT_OK;
872         char *Reply = "%d %d\n";
873
874         if (CtdlAccessCheck(ac_aide)) return;
875
876         new_state = extract_int(argbuf, 0);
877         if ((new_state == 2) || (new_state == 3))
878         {
879                 restart_server = 1;
880                 if (!running_as_daemon)
881                 {
882                         lprintf(CTDL_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
883                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
884                         state = ERROR;
885                 }
886
887                 restart_server = extract_int(argbuf, 0);
888                 new_state -= 2;
889         }
890         if ((new_state == 0) || (new_state == 1)) {
891                 ScheduledShutdown = new_state;
892         }
893         cprintf(Reply, state, ScheduledShutdown);
894 }
895
896
897 /*
898  * Set or unset asynchronous protocol mode
899  */
900 void cmd_asyn(char *argbuf)
901 {
902         int new_state;
903
904         new_state = extract_int(argbuf, 0);
905         if ((new_state == 0) || (new_state == 1)) {
906                 CC->is_async = new_state;
907         }
908         cprintf("%d %d\n", CIT_OK, CC->is_async);
909 }
910
911
912 /*
913  * Generate a "nonce" for APOP-style authentication.
914  *
915  * RFC 1725 et al specify a PID to be placed in front of the nonce.
916  * Quoth BTX: That would be stupid.
917  */
918 void generate_nonce(struct CitContext *con) {
919         struct timeval tv;
920
921         memset(con->cs_nonce, NONCE_SIZE, 0);
922         gettimeofday(&tv, NULL);
923         memset(con->cs_nonce, NONCE_SIZE, 0);
924         snprintf(con->cs_nonce, NONCE_SIZE, "<%d%ld@%s>",
925                 rand(), (long)tv.tv_usec, config.c_fqdn);
926 }
927
928
929
930
931 /*
932  * Back-end function for starting a session
933  */
934 void begin_session(struct CitContext *con)
935 {
936         socklen_t len;
937         struct sockaddr_in sin;
938
939         /* 
940          * Initialize some variables specific to our context.
941          */
942         con->logged_in = 0;
943         con->internal_pgm = 0;
944         con->download_fp = NULL;
945         con->upload_fp = NULL;
946         con->FirstExpressMessage = NULL;
947         time(&con->lastcmd);
948         time(&con->lastidle);
949         strcpy(con->lastcmdname, "    ");
950         strcpy(con->cs_clientname, "(unknown)");
951         strcpy(con->curr_user, NLI);
952         *con->net_node = '\0';
953         *con->fake_username = '\0';
954         *con->fake_hostname = '\0';
955         *con->fake_roomname = '\0';
956         generate_nonce(con);
957         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
958         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
959         con->cs_host[sizeof con->cs_host - 1] = 0;
960         len = sizeof sin;
961         if (!CC->is_local_socket) {
962                 if (!getpeername(con->client_socket, (struct sockaddr *) &sin, &len)) {
963                         locate_host(con->cs_host, sizeof con->cs_host,
964                                 con->cs_addr, sizeof con->cs_addr,
965                                 &sin.sin_addr
966                         );
967                 }
968         }
969         else {
970                 strcpy(con->cs_host, "");
971         }
972         con->cs_flags = 0;
973         con->upload_type = UPL_FILE;
974         con->dl_is_net = 0;
975
976         con->nologin = 0;
977         if ((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) {
978                 con->nologin = 1;
979         }
980
981         if (!CC->is_local_socket) {
982                 lprintf(CTDL_NOTICE, "Session started from %s [%s].\n", con->cs_host, con->cs_addr);
983         }
984         else {
985                 lprintf(CTDL_NOTICE, "Session started via local socket.\n");
986         }
987
988         /* Run any session startup routines registered by loadable modules */
989         PerformSessionHooks(EVT_START);
990 }
991
992
993 void citproto_begin_session() {
994         if (CC->nologin==1) {
995                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
996                         ERROR + MAX_SESSIONS_EXCEEDED,
997                         config.c_nodename, config.c_maxsessions
998                 );
999                 CC->kill_me = 1;
1000         }
1001         else {
1002                 cprintf("%d %s Citadel server ready.\n",
1003                         CIT_OK, config.c_nodename);
1004         }
1005 }
1006
1007
1008
1009
1010 /*
1011  * This loop recognizes all server commands.
1012  */
1013 void do_command_loop(void) {
1014         char cmdbuf[SIZ];
1015         const char *old_name = NULL;
1016         
1017         old_name = CtdlThreadName("do_command_loop");
1018         
1019         time(&CC->lastcmd);
1020         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1021         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1022                 lprintf(CTDL_ERR, "Client disconnected: ending session.\n");
1023                 CC->kill_me = 1;
1024                 CtdlThreadName(old_name);
1025                 return;
1026         }
1027
1028         /* Log the server command, but don't show passwords... */
1029         if ( (strncasecmp(cmdbuf, "PASS", 4))
1030            && (strncasecmp(cmdbuf, "SETP", 4)) ) {
1031                 lprintf(CTDL_INFO, "%s\n", cmdbuf);
1032         }
1033         else {
1034                 lprintf(CTDL_INFO, "<password command sent>\n");
1035         }
1036
1037         buffer_output();
1038
1039         /*
1040          * Let other clients see the last command we executed, and
1041          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
1042          */
1043         if ( (strncasecmp(cmdbuf, "NOOP", 4))
1044            && (strncasecmp(cmdbuf, "QNOP", 4))
1045            && (strncasecmp(cmdbuf, "PEXP", 4))
1046            && (strncasecmp(cmdbuf, "GEXP", 4))
1047            && (strncasecmp(cmdbuf, "RWHO", 4))
1048            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
1049                 strcpy(CC->lastcmdname, "    ");
1050                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
1051                 time(&CC->lastidle);
1052         }
1053         
1054         CtdlThreadName(cmdbuf);
1055                 
1056         if ((strncasecmp(cmdbuf, "ENT0", 4))
1057            && (strncasecmp(cmdbuf, "MESG", 4))
1058            && (strncasecmp(cmdbuf, "MSGS", 4)))
1059         {
1060            CC->cs_flags &= ~CS_POSTING;
1061         }
1062                    
1063         if (!strncasecmp(cmdbuf, "NOOP", 4)) {
1064                 cprintf("%d%cok\n", CIT_OK, CtdlCheckExpress() );
1065         }
1066         
1067         else if (!strncasecmp(cmdbuf, "XYZZY", 5)) {
1068                 cprintf("%d Nothing happens.\n", CIT_OK);
1069         }
1070         
1071         else if (!strncasecmp(cmdbuf, "QNOP", 4)) {
1072                 /* do nothing, this command returns no response */
1073         }
1074
1075         else if (!strncasecmp(cmdbuf,"QUIT",4)) {
1076                 cprintf("%d Goodbye.\n", CIT_OK);
1077                 CC->kill_me = 1;
1078         }
1079
1080         else if (!strncasecmp(cmdbuf,"ASYN",4)) {
1081                 cmd_asyn(&cmdbuf[5]);
1082         }
1083
1084         else if (!strncasecmp(cmdbuf,"LOUT",4)) {
1085                 if (CC->logged_in) logout();
1086                 cprintf("%d logged out.\n", CIT_OK);
1087         }
1088
1089         else if (!strncasecmp(cmdbuf,"USER",4)) {
1090                 cmd_user(&cmdbuf[5]);
1091         }
1092
1093         else if (!strncasecmp(cmdbuf,"PASS",4)) {
1094                 cmd_pass(&cmdbuf[5]);
1095         }
1096
1097         else if (!strncasecmp(cmdbuf,"NEWU",4)) {
1098                 cmd_newu(&cmdbuf[5]);
1099         }
1100
1101         else if (!strncasecmp(cmdbuf,"CREU",4)) {
1102                 cmd_creu(&cmdbuf[5]);
1103         }
1104
1105         else if (!strncasecmp(cmdbuf,"SETP",4)) {
1106                 cmd_setp(&cmdbuf[5]);
1107         }
1108
1109         else if (!strncasecmp(cmdbuf,"LRMS",4)) {
1110                 cmd_lrms(&cmdbuf[5]);
1111         }
1112
1113         else if (!strncasecmp(cmdbuf,"LKRA",4)) {
1114                 cmd_lkra(&cmdbuf[5]);
1115         }
1116
1117         else if (!strncasecmp(cmdbuf,"LKRN",4)) {
1118                 cmd_lkrn(&cmdbuf[5]);
1119         }
1120
1121         else if (!strncasecmp(cmdbuf,"LKRO",4)) {
1122                 cmd_lkro(&cmdbuf[5]);
1123         }
1124
1125         else if (!strncasecmp(cmdbuf,"LZRM",4)) {
1126                 cmd_lzrm(&cmdbuf[5]);
1127         }
1128
1129         else if (!strncasecmp(cmdbuf,"LPRM",4)) {
1130                 cmd_lprm(&cmdbuf[5]);
1131         }
1132
1133         else if (!strncasecmp(cmdbuf,"GETU",4)) {
1134                 cmd_getu();
1135         }
1136
1137         else if (!strncasecmp(cmdbuf,"SETU",4)) {
1138                 cmd_setu(&cmdbuf[5]);
1139         }
1140
1141         else if (!strncasecmp(cmdbuf,"GOTO",4)) {
1142                 cmd_goto(&cmdbuf[5]);
1143         }
1144
1145         else if (!strncasecmp(cmdbuf,"MSGS",4)) {
1146                 cmd_msgs(&cmdbuf[5]);
1147         }
1148
1149         else if (!strncasecmp(cmdbuf,"WHOK",4)) {
1150                 cmd_whok();
1151         }
1152
1153         else if (!strncasecmp(cmdbuf,"RDIR",4)) {
1154                 cmd_rdir();
1155         }
1156
1157         else if (!strncasecmp(cmdbuf,"EUID",4)) {
1158                 cmd_euid(&cmdbuf[5]);
1159         }
1160
1161         else if (!strncasecmp(cmdbuf,"MSG0",4)) {
1162                 cmd_msg0(&cmdbuf[5]);
1163         }
1164
1165         else if (!strncasecmp(cmdbuf,"MSG2",4)) {
1166                 cmd_msg2(&cmdbuf[5]);
1167         }
1168
1169         else if (!strncasecmp(cmdbuf,"MSG3",4)) {
1170                 cmd_msg3(&cmdbuf[5]);
1171         }
1172
1173         else if (!strncasecmp(cmdbuf,"MSG4",4)) {
1174                 cmd_msg4(&cmdbuf[5]);
1175         }
1176
1177         else if (!strncasecmp(cmdbuf,"MSGP",4)) {
1178                 cmd_msgp(&cmdbuf[5]);
1179         }
1180
1181         else if (!strncasecmp(cmdbuf,"OPNA",4)) {
1182                 cmd_opna(&cmdbuf[5]);
1183         }
1184
1185         else if (!strncasecmp(cmdbuf,"DLAT",4)) {
1186                 cmd_dlat(&cmdbuf[5]);
1187         }
1188
1189         else if (!strncasecmp(cmdbuf,"INFO",4)) {
1190                 cmd_info();
1191         }
1192
1193         else if (!strncasecmp(cmdbuf,"SLRP",4)) {
1194                 cmd_slrp(&cmdbuf[5]);
1195         }
1196
1197         else if (!strncasecmp(cmdbuf,"INVT",4)) {
1198                 cmd_invt_kick(&cmdbuf[5],1);
1199         }
1200
1201         else if (!strncasecmp(cmdbuf,"KICK",4)) {
1202                 cmd_invt_kick(&cmdbuf[5],0);
1203         }
1204
1205         else if (!strncasecmp(cmdbuf,"GETR",4)) {
1206                 cmd_getr();
1207         }
1208
1209         else if (!strncasecmp(cmdbuf,"SETR",4)) {
1210                 cmd_setr(&cmdbuf[5]);
1211         }
1212
1213         else if (!strncasecmp(cmdbuf,"GETA",4)) {
1214                 cmd_geta();
1215         }
1216
1217         else if (!strncasecmp(cmdbuf,"SETA",4)) {
1218                 cmd_seta(&cmdbuf[5]);
1219         }
1220
1221         else if (!strncasecmp(cmdbuf,"ENT0",4)) {
1222                 cmd_ent0(&cmdbuf[5]);
1223         }
1224
1225         else if (!strncasecmp(cmdbuf,"RINF",4)) {
1226                 cmd_rinf();
1227         }
1228
1229         else if (!strncasecmp(cmdbuf,"DELE",4)) {
1230                 cmd_dele(&cmdbuf[5]);
1231         }
1232
1233         else if (!strncasecmp(cmdbuf,"KILL",4)) {
1234                 cmd_kill(&cmdbuf[5]);
1235         }
1236
1237         else if (!strncasecmp(cmdbuf,"CRE8",4)) {
1238                 cmd_cre8(&cmdbuf[5]);
1239         }
1240
1241         else if (!strncasecmp(cmdbuf,"MOVE",4)) {
1242                 cmd_move(&cmdbuf[5]);
1243         }
1244
1245         else if (!strncasecmp(cmdbuf,"FORG",4)) {
1246                 cmd_forg();
1247         }
1248
1249         else if (!strncasecmp(cmdbuf,"MESG",4)) {
1250                 cmd_mesg(&cmdbuf[5]);
1251         }
1252
1253         else if (!strncasecmp(cmdbuf,"EMSG",4)) {
1254                 cmd_emsg(&cmdbuf[5]);
1255         }
1256
1257         else if (!strncasecmp(cmdbuf,"GNUR",4)) {
1258                 cmd_gnur();
1259         }
1260
1261         else if (!strncasecmp(cmdbuf,"VALI",4)) {
1262                 cmd_vali(&cmdbuf[5]);
1263         }
1264
1265         else if (!strncasecmp(cmdbuf,"EINF",4)) {
1266                 cmd_einf(&cmdbuf[5]);
1267         }
1268
1269         else if (!strncasecmp(cmdbuf,"LIST",4)) {
1270                 cmd_list(&cmdbuf[5]);
1271         }
1272
1273         else if (!strncasecmp(cmdbuf,"CHEK",4)) {
1274                 cmd_chek();
1275         }
1276
1277         else if (!strncasecmp(cmdbuf,"DELF",4)) {
1278                 cmd_delf(&cmdbuf[5]);
1279         }
1280
1281         else if (!strncasecmp(cmdbuf,"MOVF",4)) {
1282                 cmd_movf(&cmdbuf[5]);
1283         }
1284
1285         else if (!strncasecmp(cmdbuf,"NETF",4)) {
1286                 cmd_netf(&cmdbuf[5]);
1287         }
1288
1289         else if (!strncasecmp(cmdbuf,"OPEN",4)) {
1290                 cmd_open(&cmdbuf[5]);
1291         }
1292
1293         else if (!strncasecmp(cmdbuf,"CLOS",4)) {
1294                 cmd_clos();
1295         }
1296
1297         else if (!strncasecmp(cmdbuf,"UOPN",4)) {
1298                 cmd_uopn(&cmdbuf[5]);
1299         }
1300
1301         else if (!strncasecmp(cmdbuf,"UCLS",4)) {
1302                 cmd_ucls(&cmdbuf[5]);
1303         }
1304
1305         else if (!strncasecmp(cmdbuf,"READ",4)) {
1306                 cmd_read(&cmdbuf[5]);
1307         }
1308
1309         else if (!strncasecmp(cmdbuf,"WRIT",4)) {
1310                 cmd_writ(&cmdbuf[5]);
1311         }
1312
1313         else if (!strncasecmp(cmdbuf,"QUSR",4)) {
1314                 cmd_qusr(&cmdbuf[5]);
1315         }
1316
1317         else if (!strncasecmp(cmdbuf,"ECHO",4)) {
1318                 cmd_echo(&cmdbuf[5]);
1319         }
1320
1321         else if (!strncasecmp(cmdbuf,"OIMG",4)) {
1322                 cmd_oimg(&cmdbuf[5]);
1323         }
1324
1325         else if (!strncasecmp(cmdbuf,"MORE",4)) {
1326                 cmd_more();
1327         }
1328
1329         else if (!strncasecmp(cmdbuf,"NDOP",4)) {
1330                 cmd_ndop(&cmdbuf[5]);
1331         }
1332
1333         else if (!strncasecmp(cmdbuf,"NUOP",4)) {
1334                 cmd_nuop(&cmdbuf[5]);
1335         }
1336
1337         else if (!strncasecmp(cmdbuf,"LFLR",4)) {
1338                 cmd_lflr();
1339         }
1340
1341         else if (!strncasecmp(cmdbuf,"CFLR",4)) {
1342                 cmd_cflr(&cmdbuf[5]);
1343         }
1344
1345         else if (!strncasecmp(cmdbuf,"KFLR",4)) {
1346                 cmd_kflr(&cmdbuf[5]);
1347         }
1348
1349         else if (!strncasecmp(cmdbuf,"EFLR",4)) {
1350                 cmd_eflr(&cmdbuf[5]);
1351         }
1352
1353         else if (!strncasecmp(cmdbuf,"IDEN",4)) {
1354                 cmd_iden(&cmdbuf[5]);
1355         }
1356
1357         else if (!strncasecmp(cmdbuf,"IPGM",4)) {
1358                 cmd_ipgm(&cmdbuf[5]);
1359         }
1360
1361         else if (!strncasecmp(cmdbuf,"TERM",4)) {
1362                 cmd_term(&cmdbuf[5]);
1363         }
1364
1365         else if (!strncasecmp(cmdbuf,"DOWN",4)) {
1366                 cmd_down(&cmdbuf[5]);
1367         }
1368
1369         else if (!strncasecmp(cmdbuf,"HALT",4)) {
1370                 cmd_halt();
1371         }
1372
1373         else if (!strncasecmp(cmdbuf,"SCDN",4)) {
1374                 cmd_scdn(&cmdbuf[5]);
1375         }
1376
1377         else if (!strncasecmp(cmdbuf, "UIMG", 4)) {
1378                 cmd_uimg(&cmdbuf[5]);
1379         }
1380
1381         else if (!strncasecmp(cmdbuf, "TIME", 4)) {
1382                 cmd_time();
1383         }
1384
1385         else if (!strncasecmp(cmdbuf, "AGUP", 4)) {
1386                 cmd_agup(&cmdbuf[5]);
1387         }
1388
1389         else if (!strncasecmp(cmdbuf, "ASUP", 4)) {
1390                 cmd_asup(&cmdbuf[5]);
1391         }
1392
1393         else if (!strncasecmp(cmdbuf, "GPEX", 4)) {
1394                 cmd_gpex(&cmdbuf[5]);
1395         }
1396
1397         else if (!strncasecmp(cmdbuf, "SPEX", 4)) {
1398                 cmd_spex(&cmdbuf[5]);
1399         }
1400
1401         else if (!strncasecmp(cmdbuf, "CONF", 4)) {
1402                 cmd_conf(&cmdbuf[5]);
1403         }
1404
1405         else if (!strncasecmp(cmdbuf, "SEEN", 4)) {
1406                 cmd_seen(&cmdbuf[5]);
1407         }
1408
1409         else if (!strncasecmp(cmdbuf, "GTSN", 4)) {
1410                 cmd_gtsn(&cmdbuf[5]);
1411         }
1412
1413         else if (!strncasecmp(cmdbuf, "VIEW", 4)) {
1414                 cmd_view(&cmdbuf[5]);
1415         }
1416
1417         else if (!strncasecmp(cmdbuf, "ISME", 4)) {
1418                 cmd_isme(&cmdbuf[5]);
1419         }
1420
1421         else if (!strncasecmp(cmdbuf, "RENU", 4)) {
1422                 cmd_renu(&cmdbuf[5]);
1423         }
1424
1425         else if (!DLoader_Exec_Cmd(cmdbuf)) {
1426                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
1427         }
1428
1429         unbuffer_output();
1430
1431         /* Run any after-each-command routines registered by modules */
1432         PerformSessionHooks(EVT_CMD);
1433         CtdlThreadName(old_name);
1434 }
1435
1436
1437 /*
1438  * This loop performs all asynchronous functions.
1439  */
1440 void do_async_loop(void) {
1441         PerformSessionHooks(EVT_ASYNC);
1442 }