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