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