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