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