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