* Began (but did not finish) applying GPL3+ declarations to each source file. This...
[citadel.git] / citadel / citserver.c
1 /* 
2  * $Id$
3  *
4  * Main source module for the Citadel server
5  *
6  * Copyright (c) 1987-2009 by the citadel.org team
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 3 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "sysdep.h"
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31
32
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
35 # include <time.h>
36 #else
37 # if HAVE_SYS_TIME_H
38 #  include <sys/time.h>
39 # else
40 #  include <time.h>
41 # endif
42 #endif
43
44 #if HAVE_BACKTRACE
45 #include <execinfo.h>
46 #endif
47
48 #include <ctype.h>
49 #include <string.h>
50 #include <dirent.h>
51 #include <errno.h>
52 #include <limits.h>
53 #include <netdb.h>
54 #include <sys/types.h>
55 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
58 #include <libcitadel.h>
59 #include "citadel.h"
60 #include "server.h"
61 #include "sysdep_decls.h"
62 #include "threads.h"
63 #include "citserver.h"
64 #include "config.h"
65 #include "database.h"
66 #include "housekeeping.h"
67 #include "user_ops.h"
68 #include "msgbase.h"
69 #include "support.h"
70 #include "locate_host.h"
71 #include "room_ops.h"
72 #include "file_ops.h"
73 #include "policy.h"
74 #include "control.h"
75 #include "euidindex.h"
76 #include "svn_revision.h"
77
78 #ifndef HAVE_SNPRINTF
79 #include "snprintf.h"
80 #endif
81
82 #include "ctdl_module.h"
83
84
85 struct CitContext *ContextList = NULL;
86 struct CitContext* next_session = NULL;
87 char *unique_session_numbers;
88 int ScheduledShutdown = 0;
89 time_t server_startup_time;
90 int panic_fd;
91
92 /**
93  * \brief print the actual stack frame.
94  */
95 void cit_backtrace(void)
96 {
97 #ifdef HAVE_BACKTRACE
98         void *stack_frames[50];
99         size_t size, i;
100         char **strings;
101
102
103         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
104         strings = backtrace_symbols(stack_frames, size);
105         for (i = 0; i < size; i++) {
106                 if (strings != NULL)
107                         CtdlLogPrintf(1, "%s\n", strings[i]);
108                 else
109                         CtdlLogPrintf(1, "%p\n", stack_frames[i]);
110         }
111         free(strings);
112 #endif
113 }
114
115 /**
116  * \brief print the actual stack frame.
117  */
118 void cit_panic_backtrace(int SigNum)
119 {
120 #ifdef HAVE_BACKTRACE
121         void *stack_frames[10];
122         size_t size, i;
123         char **strings;
124
125         printf("caught signal 11\n");
126         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
127         strings = backtrace_symbols(stack_frames, size);
128         for (i = 0; i < size; i++) {
129                 if (strings != NULL)
130                         CtdlLogPrintf(1, "%s\n", strings[i]);
131                 else
132                         CtdlLogPrintf(1, "%p\n", stack_frames[i]);
133         }
134         free(strings);
135 #endif
136         exit(-1);
137 }
138
139 /*
140  * Various things that need to be initialized at startup
141  */
142 void master_startup(void) {
143         struct timeval tv;
144         unsigned int seed;
145         FILE *urandom;
146         struct ctdlroom qrbuf;
147         
148         CtdlLogPrintf(CTDL_DEBUG, "master_startup() started\n");
149         time(&server_startup_time);
150
151         CtdlLogPrintf(CTDL_INFO, "Opening databases\n");
152         open_databases();
153
154         ctdl_thread_internal_init_tsd();
155         
156         CtdlThreadAllocTSD();
157         
158         check_ref_counts();
159
160         CtdlLogPrintf(CTDL_INFO, "Creating base rooms (if necessary)\n");
161         create_room(config.c_baseroom,  0, "", 0, 1, 0, VIEW_BBS);
162         create_room(AIDEROOM,           3, "", 0, 1, 0, VIEW_BBS);
163         create_room(SYSCONFIGROOM,      3, "", 0, 1, 0, VIEW_BBS);
164         create_room(config.c_twitroom,  0, "", 0, 1, 0, VIEW_BBS);
165
166         /* The "Local System Configuration" room doesn't need to be visible */
167         if (lgetroom(&qrbuf, SYSCONFIGROOM) == 0) {
168                 qrbuf.QRflags2 |= QR2_SYSTEM;
169                 lputroom(&qrbuf);
170         }
171
172         /* Aide needs to be public postable, else we're not RFC conformant. */
173         if (lgetroom(&qrbuf, AIDEROOM) == 0) {
174                 qrbuf.QRflags2 |= QR2_SMTP_PUBLIC;
175                 lputroom(&qrbuf);
176         }
177
178         CtdlLogPrintf(CTDL_INFO, "Seeding the pseudo-random number generator...\n");
179         urandom = fopen("/dev/urandom", "r");
180         if (urandom != NULL) {
181                 fread(&seed, sizeof seed, 1, urandom);
182                 fclose(urandom);
183         }
184         else {
185                 gettimeofday(&tv, NULL);
186                 seed = tv.tv_usec;
187         }
188         srand(seed);
189         srandom(seed);
190
191         CtdlLogPrintf(CTDL_INFO, "Initializing ipgm secret\n");
192         get_config();
193         config.c_ipgm_secret = rand();
194         put_config();
195
196         CtdlLogPrintf(CTDL_DEBUG, "master_startup() finished\n");
197 }
198
199
200 /*
201  * Cleanup routine to be called when the server is shutting down.
202  */
203 void master_cleanup(int exitcode) {
204         struct CleanupFunctionHook *fcn;
205         static int already_cleaning_up = 0;
206
207         if (already_cleaning_up) while(1) sleep(1);
208         already_cleaning_up = 1;
209
210         /* Run any cleanup routines registered by loadable modules */
211         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
212                 (*fcn->h_function_pointer)();
213         }
214
215         /* Close the AdjRefCount queue file */
216         AdjRefCount(-1, 0);
217
218         /* Do system-dependent stuff */
219         sysdep_master_cleanup();
220         
221         /* Close databases */
222         CtdlLogPrintf(CTDL_INFO, "Closing databases\n");
223         close_databases();
224
225 #ifdef DEBUG_MEMORY_LEAKS
226         dump_heap();
227 #endif
228
229         /* If the operator requested a halt but not an exit, halt here. */
230         if (shutdown_and_halt) {
231                 CtdlLogPrintf(CTDL_NOTICE, "citserver: Halting server without exiting.\n");
232                 fflush(stdout); fflush(stderr);
233                 while(1) {
234                         sleep(32767);
235                 }
236         }
237         
238         release_control();
239
240         /* Now go away. */
241         CtdlLogPrintf(CTDL_NOTICE, "citserver: Exiting with status %d\n", exitcode);
242         fflush(stdout); fflush(stderr);
243         
244         if (restart_server != 0)
245                 exit(1);
246         if ((running_as_daemon != 0) && (exitcode == 0))
247                 exitcode = CTDLEXIT_SHUTDOWN;
248         exit(exitcode);
249 }
250
251
252
253 /*
254  * Terminate a session.
255  */
256 void RemoveContext (struct CitContext *con)
257 {
258         if (con==NULL) {
259                 CtdlLogPrintf(CTDL_ERR,
260                         "WARNING: RemoveContext() called with NULL!\n");
261                 return;
262         }
263         CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
264
265         /* Run any cleanup routines registered by loadable modules.
266          * Note: We have to "become_session()" because the cleanup functions
267          *       might make references to "CC" assuming it's the right one.
268          */
269         become_session(con);
270         logout();
271         PerformSessionHooks(EVT_STOP);
272         become_session(NULL);
273
274         CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
275
276         /* If the client is still connected, blow 'em away. */
277         CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
278         close(con->client_socket);
279
280         /* If using AUTHMODE_LDAP, free the DN */
281         if (con->ldap_dn) {
282                 free(con->ldap_dn);
283                 con->ldap_dn = NULL;
284         }
285
286         CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
287 }
288
289
290
291
292
293 /*
294  * cmd_info()  -  tell the client about this server
295  */
296 void cmd_info(char *cmdbuf) {
297         cprintf("%d Server info:\n", LISTING_FOLLOWS);
298         cprintf("%d\n", CC->cs_pid);
299         cprintf("%s\n", config.c_nodename);
300         cprintf("%s\n", config.c_humannode);
301         cprintf("%s\n", config.c_fqdn);
302         cprintf("%s\n", CITADEL);
303         cprintf("%d\n", REV_LEVEL);
304         cprintf("%s\n", config.c_site_location);
305         cprintf("%s\n", config.c_sysadm);
306         cprintf("%d\n", SERVER_TYPE);
307         cprintf("%s\n", config.c_moreprompt);
308         cprintf("1\n"); /* 1 = yes, this system supports floors */
309         cprintf("1\n"); /* 1 = we support the extended paging options */
310         cprintf("%s\n", CC->cs_nonce);
311         cprintf("1\n"); /* 1 = yes, this system supports the QNOP command */
312
313 #ifdef HAVE_LDAP
314         cprintf("1\n"); /* 1 = yes, this server is LDAP-enabled */
315 #else
316         cprintf("0\n"); /* 1 = no, this server is not LDAP-enabled */
317 #endif
318
319         if (config.c_auth_mode == AUTHMODE_NATIVE) {
320                 cprintf("%d\n", config.c_disable_newu);
321         }
322         else {
323                 cprintf("1\n"); /* "create new user" does not work with non-native auth modes */
324         }
325
326         cprintf("%s\n", config.c_default_cal_zone);
327
328         /* Output load averages */
329         cprintf("%f\n", CtdlThreadLoadAvg);
330         cprintf("%f\n", CtdlThreadWorkerAvg);
331         cprintf("%d\n", CtdlThreadGetCount());
332
333         cprintf("1\n");         /* yes, Sieve mail filtering is supported */
334         cprintf("%d\n", config.c_enable_fulltext);
335         cprintf("%s\n", svn_revision());
336
337         if (config.c_auth_mode == AUTHMODE_NATIVE) {
338                 cprintf("1\n"); /* OpenID is enabled when using native auth */
339         }
340         else {
341                 cprintf("0\n"); /* OpenID is disabled when using non-native auth */
342         }
343         
344         cprintf("000\n");
345 }
346
347
348 /*
349  * returns an asterisk if there are any instant messages waiting,
350  * space otherwise.
351  */
352 char CtdlCheckExpress(void) {
353         if (CC->FirstExpressMessage == NULL) {
354                 return(' ');
355         }
356         else {
357                 return('*');
358         }
359 }
360
361 void cmd_time(char *argbuf)
362 {
363    time_t tv;
364    struct tm tmp;
365    
366    tv = time(NULL);
367    localtime_r(&tv, &tmp);
368    
369    /* timezone and daylight global variables are not portable. */
370 #ifdef HAVE_STRUCT_TM_TM_GMTOFF
371    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, tmp.tm_gmtoff, tmp.tm_isdst);
372 #else
373    cprintf("%d %ld|%ld|%d\n", CIT_OK, (long)tv, timezone, tmp.tm_isdst);
374 #endif
375 }
376
377
378 /*
379  * Check originating host against the public_clients file.  This determines
380  * whether the client is allowed to change the hostname for this session
381  * (for example, to show the location of the user rather than the location
382  * of the client).
383  */
384 int is_public_client(void)
385 {
386         char buf[1024];
387         char addrbuf[1024];
388         FILE *fp;
389         int i;
390         char *public_clientspos;
391         char *public_clientsend;
392         char *paddr = NULL;
393         struct stat statbuf;
394         static time_t pc_timestamp = 0;
395         static char public_clients[SIZ];
396         static char public_clients_file[SIZ];
397
398 #define LOCALHOSTSTR "127.0.0.1"
399
400         snprintf(public_clients_file, 
401                          sizeof public_clients_file,
402                          "%s/public_clients",
403                          ctdl_etc_dir);
404
405         /*
406          * Check the time stamp on the public_clients file.  If it's been
407          * updated since the last time we were here (or if this is the first
408          * time we've been through the loop), read its contents and learn
409          * the IP addresses of the listed hosts.
410          */
411         if (stat(public_clients_file, &statbuf) != 0) {
412                 /* No public_clients file exists, so bail out */
413                 CtdlLogPrintf(CTDL_WARNING, "Warning: '%s' does not exist\n", 
414                                 public_clients_file);
415                 return(0);
416         }
417
418         if (statbuf.st_mtime > pc_timestamp) {
419                 begin_critical_section(S_PUBLIC_CLIENTS);
420                 CtdlLogPrintf(CTDL_INFO, "Loading %s\n", public_clients_file);
421
422                 public_clientspos = &public_clients[0];
423                 public_clientsend = public_clientspos + SIZ;
424                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
425                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
426                 
427                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
428                         *(public_clientspos++) = '|';
429                         paddr = &addrbuf[0];
430                         while (!IsEmptyStr (paddr) && 
431                                (public_clientspos < public_clientsend))
432                                 *(public_clientspos++) = *(paddr++);
433                 }
434
435                 fp = fopen(public_clients_file, "r");
436                 if (fp != NULL) 
437                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
438                                (public_clientspos < public_clientsend)){
439                                 char *ptr;
440                                 ptr = buf;
441                                 while (!IsEmptyStr(ptr)) {
442                                         if (*ptr == '#') {
443                                                 *ptr = 0;
444                                                 break;
445                                         }
446                                 else ptr++;
447                                 }
448                                 ptr--;
449                                 while (ptr>buf && isspace(*ptr)) {
450                                         *(ptr--) = 0;
451                                 }
452                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
453                                         *(public_clientspos++) = '|';
454                                         paddr = addrbuf;
455                                         while (!IsEmptyStr(paddr) && 
456                                                (public_clientspos < public_clientsend)){
457                                                 *(public_clientspos++) = *(paddr++);
458                                         }
459                                 }
460                         }
461                 fclose(fp);
462                 pc_timestamp = time(NULL);
463                 end_critical_section(S_PUBLIC_CLIENTS);
464         }
465
466         CtdlLogPrintf(CTDL_DEBUG, "Checking whether %s is a local or public client\n",
467                 CC->cs_addr);
468         for (i=0; i<num_parms(public_clients); ++i) {
469                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
470                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
471                         CtdlLogPrintf(CTDL_DEBUG, "... yes it is.\n");
472                         return(1);
473                 }
474         }
475
476         /* No hits.  This is not a public client. */
477         CtdlLogPrintf(CTDL_DEBUG, "... no it isn't.\n");
478         return(0);
479 }
480
481
482 /*
483  * the client is identifying itself to the server
484  */
485 void cmd_iden(char *argbuf)
486 {
487         int dev_code;
488         int cli_code;
489         int rev_level;
490         char desc[128];
491         char from_host[128];
492         struct in_addr addr;
493         int do_lookup = 0;
494
495         if (num_parms(argbuf)<4) {
496                 cprintf("%d usage error\n", ERROR + ILLEGAL_VALUE);
497                 return;
498         }
499
500         dev_code = extract_int(argbuf,0);
501         cli_code = extract_int(argbuf,1);
502         rev_level = extract_int(argbuf,2);
503         extract_token(desc, argbuf, 3, '|', sizeof desc);
504
505         safestrncpy(from_host, config.c_fqdn, sizeof from_host);
506         from_host[sizeof from_host - 1] = 0;
507         if (num_parms(argbuf)>=5) extract_token(from_host, argbuf, 4, '|', sizeof from_host);
508
509         CC->cs_clientdev = dev_code;
510         CC->cs_clienttyp = cli_code;
511         CC->cs_clientver = rev_level;
512         safestrncpy(CC->cs_clientname, desc, sizeof CC->cs_clientname);
513         CC->cs_clientname[31] = 0;
514
515         if (!IsEmptyStr(from_host)) {
516                 if (CC->is_local_socket) do_lookup = 1;
517                 else if (is_public_client()) do_lookup = 1;
518         }
519
520         if (do_lookup) {
521                 CtdlLogPrintf(CTDL_DEBUG, "Looking up hostname '%s'\n", from_host);
522                 if ((addr.s_addr = inet_addr(from_host)) != -1) {
523                         locate_host(CC->cs_host, sizeof CC->cs_host,
524                                 CC->cs_addr, sizeof CC->cs_addr,
525                                 &addr);
526                 }
527                 else {
528                         safestrncpy(CC->cs_host, from_host, sizeof CC->cs_host);
529                         CC->cs_host[sizeof CC->cs_host - 1] = 0;
530                 }
531         }
532
533         CtdlLogPrintf(CTDL_NOTICE, "Client %d/%d/%01d.%02d (%s) from %s\n",
534                 dev_code,
535                 cli_code,
536                 (rev_level / 100),
537                 (rev_level % 100),
538                 desc,
539                 CC->cs_host);
540         cprintf("%d Ok\n",CIT_OK);
541 }
542
543
544 /*
545  * display system messages or help
546  */
547 void cmd_mesg(char *mname)
548 {
549         FILE *mfp;
550         char targ[256];
551         char buf[256];
552         char buf2[256];
553         char *dirs[2];
554         DIR *dp;
555         struct dirent *d;
556
557         extract_token(buf, mname, 0, '|', sizeof buf);
558
559         dirs[0] = strdup(ctdl_message_dir);
560         dirs[1] = strdup(ctdl_hlp_dir);
561
562         snprintf(buf2, sizeof buf2, "%s.%d.%d",
563                 buf, CC->cs_clientdev, CC->cs_clienttyp);
564
565         /* If the client requested "?" then produce a listing */
566         if (!strcmp(buf, "?")) {
567                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
568                 dp = opendir(dirs[1]);
569                 if (dp != NULL) {
570                         while (d = readdir(dp), d != NULL) {
571                                 if (d->d_name[0] != '.') {
572                                         cprintf(" %s\n", d->d_name);
573                                 }
574                         }
575                         closedir(dp);
576                 }
577                 cprintf("000\n");
578                 free(dirs[0]);
579                 free(dirs[1]);
580                 return;
581         }
582
583         /* Otherwise, look for the requested file by name. */
584         else {
585                 mesg_locate(targ, sizeof targ, buf2, 2, (const char **)dirs);
586                 if (IsEmptyStr(targ)) {
587                         snprintf(buf2, sizeof buf2, "%s.%d",
588                                                         buf, CC->cs_clientdev);
589                         mesg_locate(targ, sizeof targ, buf2, 2,
590                                                         (const char **)dirs);
591                         if (IsEmptyStr(targ)) {
592                                 mesg_locate(targ, sizeof targ, buf, 2,
593                                                         (const char **)dirs);
594                         }       
595                 }
596         }
597
598         free(dirs[0]);
599         free(dirs[1]);
600
601         if (IsEmptyStr(targ)) {
602                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
603                         ERROR + FILE_NOT_FOUND,
604                         mname,
605                         ctdl_message_dir,
606                         ctdl_hlp_dir
607                 );
608                 return;
609         }
610
611         mfp = fopen(targ, "r");
612         if (mfp==NULL) {
613                 cprintf("%d Cannot open '%s': %s\n",
614                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
615                 return;
616         }
617         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
618
619         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
620                 buf[strlen(buf)-1] = 0;
621                 do_help_subst(buf);
622                 cprintf("%s\n",buf);
623         }
624
625         fclose(mfp);
626         cprintf("000\n");
627 }
628
629
630 /*
631  * enter system messages or help
632  */
633 void cmd_emsg(char *mname)
634 {
635         FILE *mfp;
636         char targ[256];
637         char buf[256];
638         char *dirs[2];
639         int a;
640
641         unbuffer_output();
642
643         if (CtdlAccessCheck(ac_aide)) return;
644
645         extract_token(buf, mname, 0, '|', sizeof buf);
646         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
647                 if (buf[a] == '/') buf[a] = '.';
648         }
649
650         dirs[0] = strdup(ctdl_message_dir);
651         dirs[1] = strdup(ctdl_hlp_dir);
652
653         mesg_locate(targ, sizeof targ, buf, 2, (const char**)dirs);
654         free(dirs[0]);
655         free(dirs[1]);
656
657         if (IsEmptyStr(targ)) {
658                 snprintf(targ, sizeof targ, 
659                                  "%s/%s",
660                                  ctdl_hlp_dir, buf);
661         }
662
663         mfp = fopen(targ,"w");
664         if (mfp==NULL) {
665                 cprintf("%d Cannot open '%s': %s\n",
666                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
667                 return;
668         }
669         cprintf("%d %s\n", SEND_LISTING, targ);
670
671         while (client_getln(buf, sizeof buf) >=0 && strcmp(buf, "000")) {
672                 fprintf(mfp, "%s\n", buf);
673         }
674
675         fclose(mfp);
676 }
677
678
679 /* Don't show the names of private rooms unless the viewing
680  * user also knows the rooms.
681  */
682 void GenerateRoomDisplay(char *real_room,
683                         struct CitContext *viewed,
684                         struct CitContext *viewer) {
685
686         int ra;
687
688         strcpy(real_room, viewed->room.QRname);
689         if (viewed->room.QRflags & QR_MAILBOX) {
690                 strcpy(real_room, &real_room[11]);
691         }
692         if (viewed->room.QRflags & QR_PRIVATE) {
693                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
694                 if ( (ra & UA_KNOWN) == 0) {
695                         strcpy(real_room, "<private room>");
696                 }
697         }
698
699         if (viewed->cs_flags & CS_CHAT) {
700                 while (strlen(real_room) < 14) {
701                         strcat(real_room, " ");
702                 }
703                 strcpy(&real_room[14], "<chat>");
704         }
705
706 }
707
708 /*
709  * Convenience function.
710  */
711 int CtdlAccessCheck(int required_level) {
712
713         if (CC->internal_pgm) return(0);
714         if (required_level >= ac_internal) {
715                 cprintf("%d This is not a user-level command.\n",
716                         ERROR + HIGHER_ACCESS_REQUIRED);
717                 return(-1);
718         }
719
720         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
721                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
722                 return(-1);
723         }
724
725         if (CC->user.axlevel >= 6) return(0);
726         if (required_level >= ac_aide) {
727                 cprintf("%d This command requires Aide access.\n",
728                         ERROR + HIGHER_ACCESS_REQUIRED);
729                 return(-1);
730         }
731
732         if (is_room_aide()) return(0);
733         if (required_level >= ac_room_aide) {
734                 cprintf("%d This command requires Aide or Room Aide access.\n",
735                         ERROR + HIGHER_ACCESS_REQUIRED);
736                 return(-1);
737         }
738
739         /* shhh ... succeed quietly */
740         return(0);
741 }
742
743
744
745 /*
746  * Terminate another running session
747  */
748 void cmd_term(char *cmdbuf)
749 {
750         int session_num;
751         struct CitContext *ccptr;
752         int found_it = 0;
753         int allowed = 0;
754
755         session_num = extract_int(cmdbuf, 0);
756         if (session_num == CC->cs_pid) {
757                 cprintf("%d You can't kill your own session.\n", ERROR + ILLEGAL_VALUE);
758                 return;
759         }
760
761         CtdlLogPrintf(CTDL_DEBUG, "Locating session to kill\n");
762         begin_critical_section(S_SESSION_TABLE);
763         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
764                 if (session_num == ccptr->cs_pid) {
765                         found_it = 1;
766                         if ((ccptr->user.usernum == CC->user.usernum)
767                            || (CC->user.axlevel >= 6)) {
768                                 allowed = 1;
769                                 ccptr->kill_me = 1;
770                         }
771                         else {
772                                 allowed = 0;
773                         }
774                 }
775         }
776         end_critical_section(S_SESSION_TABLE);
777
778         if (found_it) {
779                 if (allowed) {
780                         cprintf("%d Session terminated.\n", CIT_OK);
781                 }
782                 else {
783                         cprintf("%d You are not allowed to do that.\n",
784                                 ERROR + HIGHER_ACCESS_REQUIRED);
785                 }
786         }
787         else {
788                 cprintf("%d No such session.\n", ERROR + ILLEGAL_VALUE);
789         }
790 }
791
792
793
794
795
796 /* 
797  * get the paginator prompt
798  */
799 void cmd_more(char *argbuf) {
800         cprintf("%d %s\n", CIT_OK, config.c_moreprompt);
801 }
802
803 /*
804  * echo 
805  */
806 void cmd_echo(char *etext)
807 {
808         cprintf("%d %s\n", CIT_OK, etext);
809 }
810
811
812
813 /* 
814  * identify as internal program
815  */
816 void cmd_ipgm(char *argbuf)
817 {
818         int secret;
819
820         secret = extract_int(argbuf, 0);
821
822         /* For security reasons, we do NOT allow this command to run
823          * over the network.  Local sockets only.
824          */
825         if (!CC->is_local_socket) {
826                 sleep(5);
827                 cprintf("%d Authentication failed.\n",
828                         ERROR + PASSWORD_REQUIRED);
829         }
830         else if (secret == config.c_ipgm_secret) {
831                 CC->internal_pgm = 1;
832                 strcpy(CC->curr_user, "<internal program>");
833                 CC->cs_flags = CC->cs_flags|CS_STEALTH;
834                 cprintf("%d Authenticated as an internal program.\n", CIT_OK);
835         }
836         else {
837                 sleep(5);
838                 cprintf("%d Authentication failed.\n",
839                         ERROR + PASSWORD_REQUIRED);
840                 CtdlLogPrintf(CTDL_ERR, "Warning: ipgm authentication failed.\n");
841                 CC->kill_me = 1;
842         }
843 }
844
845
846 /*
847  * Shut down the server
848  */
849 void cmd_down(char *argbuf) {
850         char *Reply ="%d Shutting down server.  Goodbye.\n";
851
852         if (CtdlAccessCheck(ac_aide)) return;
853
854         if (!IsEmptyStr(argbuf))
855         {
856                 int state = CIT_OK;
857                 restart_server = extract_int(argbuf, 0);
858                 
859                 if (restart_server > 0)
860                 {
861                         Reply = "%d citserver will now shut down and automatically restart.\n";
862                 }
863                 if ((restart_server > 0) && !running_as_daemon)
864                 {
865                         CtdlLogPrintf(CTDL_ERR, "The user requested restart, but not running as daemon! Geronimooooooo!\n");
866                         Reply = "%d Warning: citserver is not running in daemon mode and is therefore unlikely to restart automatically.\n";
867                         state = ERROR;
868                 }
869                 cprintf(Reply, state);
870         }
871         else
872         {
873                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN); 
874         }
875         CtdlThreadStopAll();
876 }
877
878 /*
879  * Halt the server without exiting the server process.
880  */
881 void cmd_halt(char *argbuf) {
882
883         if (CtdlAccessCheck(ac_aide)) return;
884
885         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
886         CtdlThreadStopAll();
887         shutdown_and_halt = 1;
888 }
889
890 /*
891  * Schedule or cancel a server shutdown
892  */
893 void cmd_scdn(char *argbuf)
894 {
895         int new_state;
896         int state = CIT_OK;
897         char *Reply = "%d %d\n";
898
899         if (CtdlAccessCheck(ac_aide)) return;
900
901         new_state = extract_int(argbuf, 0);
902         if ((new_state == 2) || (new_state == 3))
903         {
904                 restart_server = 1;
905                 if (!running_as_daemon)
906                 {
907                         CtdlLogPrintf(CTDL_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
908                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
909                         state = ERROR;
910                 }
911
912                 restart_server = extract_int(argbuf, 0);
913                 new_state -= 2;
914         }
915         if ((new_state == 0) || (new_state == 1)) {
916                 ScheduledShutdown = new_state;
917         }
918         cprintf(Reply, state, ScheduledShutdown);
919 }
920
921
922 /*
923  * Set or unset asynchronous protocol mode
924  */
925 void cmd_asyn(char *argbuf)
926 {
927         int new_state;
928
929         new_state = extract_int(argbuf, 0);
930         if ((new_state == 0) || (new_state == 1)) {
931                 CC->is_async = new_state;
932         }
933         cprintf("%d %d\n", CIT_OK, CC->is_async);
934 }
935
936
937 /*
938  * Generate a "nonce" for APOP-style authentication.
939  *
940  * RFC 1725 et al specify a PID to be placed in front of the nonce.
941  * Quoth BTX: That would be stupid.
942  */
943 void generate_nonce(struct CitContext *con) {
944         struct timeval tv;
945
946         memset(con->cs_nonce, NONCE_SIZE, 0);
947         gettimeofday(&tv, NULL);
948         memset(con->cs_nonce, NONCE_SIZE, 0);
949         snprintf(con->cs_nonce, NONCE_SIZE, "<%d%ld@%s>",
950                 rand(), (long)tv.tv_usec, config.c_fqdn);
951 }
952
953
954
955
956 /*
957  * Back-end function for starting a session
958  */
959 void begin_session(struct CitContext *con)
960 {
961         socklen_t len;
962         struct sockaddr_in sin;
963
964         /* 
965          * Initialize some variables specific to our context.
966          */
967         con->logged_in = 0;
968         con->internal_pgm = 0;
969         con->download_fp = NULL;
970         con->upload_fp = NULL;
971         con->FirstExpressMessage = NULL;
972         time(&con->lastcmd);
973         time(&con->lastidle);
974         strcpy(con->lastcmdname, "    ");
975         strcpy(con->cs_clientname, "(unknown)");
976         strcpy(con->curr_user, NLI);
977         *con->net_node = '\0';
978         *con->fake_username = '\0';
979         *con->fake_hostname = '\0';
980         *con->fake_roomname = '\0';
981         generate_nonce(con);
982         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
983         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
984         con->cs_UDSclientUID = -1;
985         con->cs_host[sizeof con->cs_host - 1] = 0;
986         len = sizeof sin;
987         if (!CC->is_local_socket) {
988                 if (!getpeername(con->client_socket, (struct sockaddr *) &sin, &len)) {
989                         locate_host(con->cs_host, sizeof con->cs_host,
990                                 con->cs_addr, sizeof con->cs_addr,
991                                 &sin.sin_addr
992                         );
993                 }
994         }
995         else {
996                 strcpy(con->cs_host, "");
997 #ifdef HAVE_STRUCT_UCRED
998                 {
999                         /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
1000                         struct ucred credentials;
1001                         int ucred_length = sizeof(struct ucred);
1002                         
1003                         /*fill in the user data structure */
1004                         if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
1005                                 CtdlLogPrintf(CTDL_NOTICE, "could obtain credentials from unix domain socket");
1006                                 
1007                         }
1008                         else {          
1009                                 /* the process ID of the process on the other side of the socket */
1010                                 /* credentials.pid; */
1011                                 
1012                                 /* the effective UID of the process on the other side of the socket  */
1013                                 con->cs_UDSclientUID = credentials.uid;
1014                                 
1015                                 /* the effective primary GID of the process on the other side of the socket */
1016                                 /* credentials.gid; */
1017                                 
1018                                 /* To get supplemental groups, we will have to look them up in our account
1019                                    database, after a reverse lookup on the UID to get the account name.
1020                                    We can take this opportunity to check to see if this is a legit account.
1021                                 */
1022                         }
1023                 }
1024 #endif
1025         }
1026         con->cs_flags = 0;
1027         con->upload_type = UPL_FILE;
1028         con->dl_is_net = 0;
1029
1030         con->nologin = 0;
1031         if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
1032                 con->nologin = 1;
1033         }
1034
1035         if (!CC->is_local_socket) {
1036                 CtdlLogPrintf(CTDL_NOTICE, "Session started from %s [%s].\n", con->cs_host, con->cs_addr);
1037         }
1038         else {
1039                 CtdlLogPrintf(CTDL_NOTICE, "Session started via local socket.\n");
1040         }
1041
1042         /* Run any session startup routines registered by loadable modules */
1043         PerformSessionHooks(EVT_START);
1044 }
1045
1046
1047 void citproto_begin_session() {
1048         if (CC->nologin==1) {
1049                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
1050                         ERROR + MAX_SESSIONS_EXCEEDED,
1051                         config.c_nodename, config.c_maxsessions
1052                 );
1053                 CC->kill_me = 1;
1054         }
1055         else {
1056                 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
1057                 CC->can_receive_im = 1;
1058         }
1059 }
1060
1061
1062
1063 void cmd_noop(char *argbuf)
1064 {
1065         cprintf("%d%cok\n", CIT_OK, CtdlCheckExpress() );
1066 }
1067
1068 void cmd_qnop(char *argbuf)
1069 {
1070         /* do nothing, this command returns no response */
1071 }
1072
1073 void cmd_quit(char *argbuf)
1074 {
1075         cprintf("%d Goodbye.\n", CIT_OK);
1076         CC->kill_me = 1;
1077 }
1078
1079 void cmd_lout(char *argbuf)
1080 {
1081         if (CC->logged_in) 
1082                 logout();
1083         cprintf("%d logged out.\n", CIT_OK);
1084 }
1085
1086 /*
1087  * This loop recognizes all server commands.
1088  */
1089 void do_command_loop(void) {
1090         char cmdbuf[SIZ];
1091         const char *old_name = NULL;
1092         
1093         old_name = CtdlThreadName("do_command_loop");
1094         
1095         time(&CC->lastcmd);
1096         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1097         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1098                 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\n");
1099                 CC->kill_me = 1;
1100                 CtdlThreadName(old_name);
1101                 return;
1102         }
1103
1104         /* Log the server command, but don't show passwords... */
1105         if ( (strncasecmp(cmdbuf, "PASS", 4))
1106            && (strncasecmp(cmdbuf, "SETP", 4)) ) {
1107                 CtdlLogPrintf(CTDL_INFO, "%s\n", cmdbuf);
1108         }
1109         else {
1110                 CtdlLogPrintf(CTDL_INFO, "<password command sent>\n");
1111         }
1112
1113         buffer_output();
1114
1115         /*
1116          * Let other clients see the last command we executed, and
1117          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
1118          */
1119         if ( (strncasecmp(cmdbuf, "NOOP", 4))
1120            && (strncasecmp(cmdbuf, "QNOP", 4))
1121            && (strncasecmp(cmdbuf, "PEXP", 4))
1122            && (strncasecmp(cmdbuf, "GEXP", 4))
1123            && (strncasecmp(cmdbuf, "RWHO", 4))
1124            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
1125                 strcpy(CC->lastcmdname, "    ");
1126                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
1127                 time(&CC->lastidle);
1128         }
1129         
1130         CtdlThreadName(cmdbuf);
1131                 
1132         if ((strncasecmp(cmdbuf, "ENT0", 4))
1133            && (strncasecmp(cmdbuf, "MESG", 4))
1134            && (strncasecmp(cmdbuf, "MSGS", 4)))
1135         {
1136            CC->cs_flags &= ~CS_POSTING;
1137         }
1138                    
1139         if (!DLoader_Exec_Cmd(cmdbuf)) {
1140                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
1141         }       
1142
1143         unbuffer_output();
1144
1145         /* Run any after-each-command routines registered by modules */
1146         PerformSessionHooks(EVT_CMD);
1147         CtdlThreadName(old_name);
1148 }
1149
1150
1151 /*
1152  * This loop performs all asynchronous functions.
1153  */
1154 void do_async_loop(void) {
1155         PerformSessionHooks(EVT_ASYNC);
1156 }
1157
1158
1159
1160
1161
1162
1163
1164 /*****************************************************************************/
1165 /*                      MODULE INITIALIZATION STUFF                          */
1166 /*****************************************************************************/
1167
1168 CTDL_MODULE_INIT(citserver)
1169 {
1170         CtdlRegisterProtoHook(cmd_noop, "NOOP", "Autoconverted. TODO: document me.");
1171         CtdlRegisterProtoHook(cmd_qnop, "QNOP", "Autoconverted. TODO: document me.");
1172         CtdlRegisterProtoHook(cmd_quit, "QUIT", "Autoconverted. TODO: document me.");
1173         CtdlRegisterProtoHook(cmd_lout, "LOUT", "Autoconverted. TODO: document me.");
1174         CtdlRegisterProtoHook(cmd_asyn, "ASYN", "Autoconverted. TODO: document me.");
1175         CtdlRegisterProtoHook(cmd_info, "INFO", "Autoconverted. TODO: document me.");
1176         CtdlRegisterProtoHook(cmd_mesg, "MESG", "Autoconverted. TODO: document me.");
1177         CtdlRegisterProtoHook(cmd_emsg, "EMSG", "Autoconverted. TODO: document me.");
1178         CtdlRegisterProtoHook(cmd_echo, "ECHO", "Autoconverted. TODO: document me.");
1179         CtdlRegisterProtoHook(cmd_more, "MORE", "Autoconverted. TODO: document me.");
1180         CtdlRegisterProtoHook(cmd_iden, "IDEN", "Autoconverted. TODO: document me.");
1181         CtdlRegisterProtoHook(cmd_ipgm, "IPGM", "Autoconverted. TODO: document me.");
1182         CtdlRegisterProtoHook(cmd_term, "TERM", "Autoconverted. TODO: document me.");
1183         CtdlRegisterProtoHook(cmd_down, "DOWN", "Autoconverted. TODO: document me.");
1184         CtdlRegisterProtoHook(cmd_halt, "HALT", "Autoconverted. TODO: document me.");
1185         CtdlRegisterProtoHook(cmd_scdn, "SCDN", "Autoconverted. TODO: document me.");
1186         CtdlRegisterProtoHook(cmd_time, "TIME", "Autoconverted. TODO: document me.");
1187         /* return our Subversion id for the Log */
1188         return "$Id$";
1189 }