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