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