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