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