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