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