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