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