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