move session related functions to ctdlproto/serv_session.c
[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, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <stdlib.h>
17 #include <unistd.h>
18 #include <stdio.h>
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
26 # include <time.h>
27 #else
28 # if HAVE_SYS_TIME_H
29 #  include <sys/time.h>
30 # else
31 #  include <time.h>
32 # endif
33 #endif
34
35 #if HAVE_BACKTRACE
36 #include <execinfo.h>
37 #endif
38
39 #include <ctype.h>
40 #include <string.h>
41 #include <dirent.h>
42 #include <errno.h>
43 #include <limits.h>
44 #include <netdb.h>
45 #include <sys/types.h>
46 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <arpa/inet.h>
49 #include <libcitadel.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "sysdep_decls.h"
53 #include "threads.h"
54 #include "citserver.h"
55 #include "config.h"
56 #include "database.h"
57 #include "housekeeping.h"
58 #include "user_ops.h"
59 #include "msgbase.h"
60 #include "support.h"
61 #include "locate_host.h"
62 #include "room_ops.h"
63 #include "file_ops.h"
64 #include "control.h"
65 #include "euidindex.h"
66 #include "context.h"
67 #include "svn_revision.h"
68 #include "ctdl_module.h"
69
70 char *unique_session_numbers;
71 int ScheduledShutdown = 0;
72 time_t server_startup_time;
73 int panic_fd;
74 int openid_level_supported = 0;
75
76 /*
77  * print the actual stack frame.
78  */
79 void cit_backtrace(void)
80 {
81 #ifdef HAVE_BACKTRACE
82         void *stack_frames[50];
83         size_t size, i;
84         char **strings;
85
86
87         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
88         strings = backtrace_symbols(stack_frames, size);
89         for (i = 0; i < size; i++) {
90                 if (strings != NULL)
91                         syslog(LOG_ALERT, "%s\n", strings[i]);
92                 else
93                         syslog(LOG_ALERT, "%p\n", stack_frames[i]);
94         }
95         free(strings);
96 #endif
97 }
98
99 void cit_oneline_backtrace(void)
100 {
101 #ifdef HAVE_BACKTRACE
102         void *stack_frames[50];
103         size_t size, i;
104         char **strings;
105         StrBuf *Buf;
106
107         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
108         strings = backtrace_symbols(stack_frames, size);
109         if (size > 0)
110         {
111                 Buf = NewStrBuf();
112                 for (i = 1; i < size; i++) {
113                         if (strings != NULL)
114                                 StrBufAppendPrintf(Buf, "%s : ", strings[i]);
115                         else
116                                 StrBufAppendPrintf(Buf, "%p : ", stack_frames[i]);
117                 }
118                 free(strings);
119                 syslog(LOG_ALERT, "%s\n", ChrPtr(Buf));
120                 FreeStrBuf(&Buf);
121         }
122 #endif
123 }
124
125 /*
126  * print the actual stack frame.
127  */
128 void cit_panic_backtrace(int SigNum)
129 {
130 #ifdef HAVE_BACKTRACE
131         void *stack_frames[10];
132         size_t size, i;
133         char **strings;
134
135         printf("caught signal 11\n");
136         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
137         strings = backtrace_symbols(stack_frames, size);
138         for (i = 0; i < size; i++) {
139                 if (strings != NULL)
140                         syslog(LOG_ALERT, "%s\n", strings[i]);
141                 else
142                         syslog(LOG_ALERT, "%p\n", stack_frames[i]);
143         }
144         free(strings);
145 #endif
146         exit(-1);
147 }
148
149 /*
150  * Various things that need to be initialized at startup
151  */
152 void master_startup(void) {
153         struct timeval tv;
154         unsigned int seed;
155         FILE *urandom;
156         struct ctdlroom qrbuf;
157         int rv;
158         
159         syslog(LOG_DEBUG, "master_startup() started\n");
160         time(&server_startup_time);
161         get_config();
162
163         syslog(LOG_INFO, "Opening databases\n");
164         open_databases();
165         check_ref_counts();
166
167         syslog(LOG_INFO, "Creating base rooms (if necessary)\n");
168         CtdlCreateRoom(config.c_baseroom,       0, "", 0, 1, 0, VIEW_BBS);
169         CtdlCreateRoom(AIDEROOM,                3, "", 0, 1, 0, VIEW_BBS);
170         CtdlCreateRoom(SYSCONFIGROOM,           3, "", 0, 1, 0, VIEW_BBS);
171         CtdlCreateRoom(config.c_twitroom,       0, "", 0, 1, 0, VIEW_BBS);
172
173         /* The "Local System Configuration" room doesn't need to be visible */
174         if (CtdlGetRoomLock(&qrbuf, SYSCONFIGROOM) == 0) {
175                 qrbuf.QRflags2 |= QR2_SYSTEM;
176                 CtdlPutRoomLock(&qrbuf);
177         }
178
179         /* Aide needs to be public postable, else we're not RFC conformant. */
180         if (CtdlGetRoomLock(&qrbuf, AIDEROOM) == 0) {
181                 qrbuf.QRflags2 |= QR2_SMTP_PUBLIC;
182                 CtdlPutRoomLock(&qrbuf);
183         }
184
185         syslog(LOG_INFO, "Seeding the pseudo-random number generator...\n");
186         urandom = fopen("/dev/urandom", "r");
187         if (urandom != NULL) {
188                 rv = fread(&seed, sizeof seed, 1, urandom);
189                 if (rv == -1)
190                         syslog(LOG_EMERG, "failed to read random seed: %s\n", 
191                                strerror(errno));
192                 fclose(urandom);
193         }
194         else {
195                 gettimeofday(&tv, NULL);
196                 seed = tv.tv_usec;
197         }
198         srand(seed);
199         srandom(seed);
200
201         put_config();
202
203         syslog(LOG_DEBUG, "master_startup() finished\n");
204 }
205
206
207 /*
208  * Cleanup routine to be called when the server is shutting down.
209  */
210 void master_cleanup(int exitcode) {
211         struct CleanupFunctionHook *fcn;
212         static int already_cleaning_up = 0;
213
214         if (already_cleaning_up) while(1) usleep(1000000);
215         already_cleaning_up = 1;
216
217         /* Run any cleanup routines registered by loadable modules */
218         for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
219                 (*fcn->h_function_pointer)();
220         }
221
222         /* Close the AdjRefCount queue file */
223         AdjRefCount(-1, 0);
224
225         /* Do system-dependent stuff */
226         sysdep_master_cleanup();
227         
228         /* Close databases */
229         syslog(LOG_INFO, "Closing databases\n");
230         close_databases();
231
232         /* If the operator requested a halt but not an exit, halt here. */
233         if (shutdown_and_halt) {
234                 syslog(LOG_NOTICE, "citserver: Halting server without exiting.\n");
235                 fflush(stdout); fflush(stderr);
236                 while(1) {
237                         sleep(32767);
238                 }
239         }
240         
241         release_control();
242
243         /* Now go away. */
244         syslog(LOG_NOTICE, "citserver: Exiting with status %d\n", exitcode);
245         fflush(stdout); fflush(stderr);
246         
247         if (restart_server != 0)
248                 exit(1);
249         if ((running_as_daemon != 0) && ((exitcode == 0) ))
250                 exitcode = CTDLEXIT_SHUTDOWN;
251         exit(exitcode);
252 }
253
254
255
256 /*
257  * returns an asterisk if there are any instant messages waiting,
258  * space otherwise.
259  */
260 char CtdlCheckExpress(void) {
261         if (CC->FirstExpressMessage == NULL) {
262                 return(' ');
263         }
264         else {
265                 return('*');
266         }
267 }
268
269
270 /*
271  * Check originating host against the public_clients file.  This determines
272  * whether the client is allowed to change the hostname for this session
273  * (for example, to show the location of the user rather than the location
274  * of the client).
275  */
276 int is_public_client(void)
277 {
278         char buf[1024];
279         char addrbuf[1024];
280         FILE *fp;
281         int i;
282         char *public_clientspos;
283         char *public_clientsend;
284         char *paddr = NULL;
285         struct stat statbuf;
286         static time_t pc_timestamp = 0;
287         static char public_clients[SIZ];
288         static char public_clients_file[SIZ];
289
290 #define LOCALHOSTSTR "127.0.0.1"
291
292         snprintf(public_clients_file, sizeof public_clients_file, "%s/public_clients", ctdl_etc_dir);
293
294         /*
295          * Check the time stamp on the public_clients file.  If it's been
296          * updated since the last time we were here (or if this is the first
297          * time we've been through the loop), read its contents and learn
298          * the IP addresses of the listed hosts.
299          */
300         if (stat(public_clients_file, &statbuf) != 0) {
301                 /* No public_clients file exists, so bail out */
302                 syslog(LOG_WARNING, "Warning: '%s' does not exist\n", 
303                                 public_clients_file);
304                 return(0);
305         }
306
307         if (statbuf.st_mtime > pc_timestamp) {
308                 begin_critical_section(S_PUBLIC_CLIENTS);
309                 syslog(LOG_INFO, "Loading %s\n", public_clients_file);
310
311                 public_clientspos = &public_clients[0];
312                 public_clientsend = public_clientspos + SIZ;
313                 safestrncpy(public_clientspos, LOCALHOSTSTR, sizeof public_clients);
314                 public_clientspos += sizeof(LOCALHOSTSTR) - 1;
315                 
316                 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
317                         *(public_clientspos++) = '|';
318                         paddr = &addrbuf[0];
319                         while (!IsEmptyStr (paddr) && 
320                                (public_clientspos < public_clientsend))
321                                 *(public_clientspos++) = *(paddr++);
322                 }
323
324                 fp = fopen(public_clients_file, "r");
325                 if (fp != NULL) 
326                         while ((fgets(buf, sizeof buf, fp)!=NULL) &&
327                                (public_clientspos < public_clientsend)){
328                                 char *ptr;
329                                 ptr = buf;
330                                 while (!IsEmptyStr(ptr)) {
331                                         if (*ptr == '#') {
332                                                 *ptr = 0;
333                                                 break;
334                                         }
335                                 else ptr++;
336                                 }
337                                 ptr--;
338                                 while (ptr>buf && isspace(*ptr)) {
339                                         *(ptr--) = 0;
340                                 }
341                                 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
342                                         *(public_clientspos++) = '|';
343                                         paddr = addrbuf;
344                                         while (!IsEmptyStr(paddr) && 
345                                                (public_clientspos < public_clientsend)){
346                                                 *(public_clientspos++) = *(paddr++);
347                                         }
348                                 }
349                         }
350                 if (fp != NULL) fclose(fp);
351                 pc_timestamp = time(NULL);
352                 end_critical_section(S_PUBLIC_CLIENTS);
353         }
354
355         syslog(LOG_DEBUG, "Checking whether %s is a local or public client\n",
356                 CC->cs_addr);
357         for (i=0; i<num_parms(public_clients); ++i) {
358                 extract_token(addrbuf, public_clients, i, '|', sizeof addrbuf);
359                 if (!strcasecmp(CC->cs_addr, addrbuf)) {
360                         syslog(LOG_DEBUG, "... yes its local.\n");
361                         return(1);
362                 }
363         }
364
365         /* No hits.  This is not a public client. */
366         syslog(LOG_DEBUG, "... no it isn't.\n");
367         return(0);
368 }
369
370
371
372 /* 
373  * help_subst()  -  support routine for help file viewer
374  */
375 void help_subst(char *strbuf, char *source, char *dest)
376 {
377         char workbuf[SIZ];
378         int p;
379
380         while (p = pattern2(strbuf, source), (p >= 0)) {
381                 strcpy(workbuf, &strbuf[p + strlen(source)]);
382                 strcpy(&strbuf[p], dest);
383                 strcat(strbuf, workbuf);
384         }
385 }
386
387 void do_help_subst(char *buffer)
388 {
389         char buf2[16];
390
391         help_subst(buffer, "^nodename", config.c_nodename);
392         help_subst(buffer, "^humannode", config.c_humannode);
393         help_subst(buffer, "^fqdn", config.c_fqdn);
394         help_subst(buffer, "^username", CC->user.fullname);
395         snprintf(buf2, sizeof buf2, "%ld", CC->user.usernum);
396         help_subst(buffer, "^usernum", buf2);
397         help_subst(buffer, "^sysadm", config.c_sysadm);
398         help_subst(buffer, "^variantname", CITADEL);
399         snprintf(buf2, sizeof buf2, "%d", config.c_maxsessions);
400         help_subst(buffer, "^maxsessions", buf2);
401         help_subst(buffer, "^bbsdir", ctdl_message_dir);
402 }
403
404
405 typedef const char *ccharp;
406 /*
407  * display system messages or help
408  */
409 void cmd_mesg(char *mname)
410 {
411         FILE *mfp;
412         char targ[256];
413         char buf[256];
414         char buf2[256];
415         char *dirs[2];
416         DIR *dp;
417         struct dirent *d;
418
419         extract_token(buf, mname, 0, '|', sizeof buf);
420
421         dirs[0] = strdup(ctdl_message_dir);
422         dirs[1] = strdup(ctdl_hlp_dir);
423
424         snprintf(buf2, sizeof buf2, "%s.%d.%d",
425                 buf, CC->cs_clientdev, CC->cs_clienttyp);
426
427         /* If the client requested "?" then produce a listing */
428         if (!strcmp(buf, "?")) {
429                 cprintf("%d %s\n", LISTING_FOLLOWS, buf);
430                 dp = opendir(dirs[1]);
431                 if (dp != NULL) {
432                         while (d = readdir(dp), d != NULL) {
433                                 if (d->d_name[0] != '.') {
434                                         cprintf(" %s\n", d->d_name);
435                                 }
436                         }
437                         closedir(dp);
438                 }
439                 cprintf("000\n");
440                 free(dirs[0]);
441                 free(dirs[1]);
442                 return;
443         }
444
445         /* Otherwise, look for the requested file by name. */
446         else {
447                 mesg_locate(targ, sizeof targ, buf2, 2, (const ccharp*)dirs);
448                 if (IsEmptyStr(targ)) {
449                         snprintf(buf2, sizeof buf2, "%s.%d",
450                                                         buf, CC->cs_clientdev);
451                         mesg_locate(targ, sizeof targ, buf2, 2,
452                                     (const ccharp*)dirs);
453                         if (IsEmptyStr(targ)) {
454                                 mesg_locate(targ, sizeof targ, buf, 2,
455                                             (const ccharp*)dirs);
456                         }       
457                 }
458         }
459
460         free(dirs[0]);
461         free(dirs[1]);
462
463         if (IsEmptyStr(targ)) {
464                 cprintf("%d '%s' not found.  (Searching in %s and %s)\n",
465                         ERROR + FILE_NOT_FOUND,
466                         mname,
467                         ctdl_message_dir,
468                         ctdl_hlp_dir
469                 );
470                 return;
471         }
472
473         mfp = fopen(targ, "r");
474         if (mfp==NULL) {
475                 cprintf("%d Cannot open '%s': %s\n",
476                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
477                 return;
478         }
479         cprintf("%d %s\n", LISTING_FOLLOWS,buf);
480
481         while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
482                 buf[strlen(buf)-1] = 0;
483                 do_help_subst(buf);
484                 cprintf("%s\n",buf);
485         }
486
487         fclose(mfp);
488         cprintf("000\n");
489 }
490
491
492 /*
493  * enter system messages or help
494  */
495 void cmd_emsg(char *mname)
496 {
497         FILE *mfp;
498         char targ[256];
499         char buf[256];
500         char *dirs[2];
501         int a;
502
503         unbuffer_output();
504
505         if (CtdlAccessCheck(ac_aide)) return;
506
507         extract_token(buf, mname, 0, '|', sizeof buf);
508         for (a=0; !IsEmptyStr(&buf[a]); ++a) {          /* security measure */
509                 if (buf[a] == '/') buf[a] = '.';
510         }
511
512         dirs[0] = strdup(ctdl_message_dir);
513         dirs[1] = strdup(ctdl_hlp_dir);
514
515         mesg_locate(targ, sizeof targ, buf, 2, (const ccharp*)dirs);
516         free(dirs[0]);
517         free(dirs[1]);
518
519         if (IsEmptyStr(targ)) {
520                 snprintf(targ, sizeof targ, 
521                                  "%s/%s",
522                                  ctdl_hlp_dir, buf);
523         }
524
525         mfp = fopen(targ,"w");
526         if (mfp==NULL) {
527                 cprintf("%d Cannot open '%s': %s\n",
528                         ERROR + INTERNAL_ERROR, targ, strerror(errno));
529                 return;
530         }
531         cprintf("%d %s\n", SEND_LISTING, targ);
532
533         while (client_getln(buf, sizeof buf) >=0 && strcmp(buf, "000")) {
534                 fprintf(mfp, "%s\n", buf);
535         }
536
537         fclose(mfp);
538 }
539
540
541 /* Don't show the names of private rooms unless the viewing
542  * user also knows the rooms.
543  */
544 void GenerateRoomDisplay(char *real_room,
545                         CitContext *viewed,
546                         CitContext *viewer) {
547
548         int ra;
549
550         strcpy(real_room, viewed->room.QRname);
551         if (viewed->room.QRflags & QR_MAILBOX) {
552                 strcpy(real_room, &real_room[11]);
553         }
554         if (viewed->room.QRflags & QR_PRIVATE) {
555                 CtdlRoomAccess(&viewed->room, &viewer->user, &ra, NULL);
556                 if ( (ra & UA_KNOWN) == 0) {
557                         strcpy(real_room, " ");
558                 }
559         }
560
561         if (viewed->cs_flags & CS_CHAT) {
562                 while (strlen(real_room) < 14) {
563                         strcat(real_room, " ");
564                 }
565                 strcpy(&real_room[14], "<chat>");
566         }
567
568 }
569
570 /*
571  * Convenience function.
572  */
573 int CtdlAccessCheck(int required_level) {
574
575         if (CC->internal_pgm) return(0);
576         if (required_level >= ac_internal) {
577                 cprintf("%d This is not a user-level command.\n",
578                         ERROR + HIGHER_ACCESS_REQUIRED);
579                 return(-1);
580         }
581
582         if ((required_level >= ac_logged_in_or_guest) && (CC->logged_in == 0) && (!config.c_guest_logins)) {
583                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
584                 return(-1);
585         }
586
587         if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
588                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
589                 return(-1);
590         }
591
592         if (CC->user.axlevel >= AxAideU) return(0);
593         if (required_level >= ac_aide) {
594                 cprintf("%d This command requires Admin access.\n",
595                         ERROR + HIGHER_ACCESS_REQUIRED);
596                 return(-1);
597         }
598
599         if (is_room_aide()) return(0);
600         if (required_level >= ac_room_aide) {
601                 cprintf("%d This command requires Admin or Room Admin access.\n",
602                         ERROR + HIGHER_ACCESS_REQUIRED);
603                 return(-1);
604         }
605
606         /* shhh ... succeed quietly */
607         return(0);
608 }
609
610
611
612
613
614
615 /*
616  * Shut down the server
617  */
618 void cmd_down(char *argbuf) {
619         char *Reply ="%d Shutting down server.  Goodbye.\n";
620
621         if (CtdlAccessCheck(ac_aide)) return;
622
623         if (!IsEmptyStr(argbuf))
624         {
625                 int state = CIT_OK;
626                 restart_server = extract_int(argbuf, 0);
627                 
628                 if (restart_server > 0)
629                 {
630                         Reply = "%d citserver will now shut down and automatically restart.\n";
631                 }
632                 if ((restart_server > 0) && !running_as_daemon)
633                 {
634                         syslog(LOG_ERR, "The user requested restart, but not running as daemon! Geronimooooooo!\n");
635                         Reply = "%d Warning: citserver is not running in daemon mode and is therefore unlikely to restart automatically.\n";
636                         state = ERROR;
637                 }
638                 cprintf(Reply, state);
639         }
640         else
641         {
642                 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN); 
643         }
644         CC->kill_me = KILLME_SERVER_SHUTTING_DOWN;
645         server_shutting_down = 1;
646 }
647
648
649 /*
650  * Halt the server without exiting the server process.
651  */
652 void cmd_halt(char *argbuf) {
653
654         if (CtdlAccessCheck(ac_aide)) return;
655
656         cprintf("%d Halting server.  Goodbye.\n", CIT_OK);
657         server_shutting_down = 1;
658         shutdown_and_halt = 1;
659 }
660
661
662 /*
663  * Schedule or cancel a server shutdown
664  */
665 void cmd_scdn(char *argbuf)
666 {
667         int new_state;
668         int state = CIT_OK;
669         char *Reply = "%d %d\n";
670
671         if (CtdlAccessCheck(ac_aide)) return;
672
673         new_state = extract_int(argbuf, 0);
674         if ((new_state == 2) || (new_state == 3))
675         {
676                 restart_server = 1;
677                 if (!running_as_daemon)
678                 {
679                         syslog(LOG_ERR, "The user requested restart, but not running as deamon! Geronimooooooo!\n");
680                         Reply = "%d %d Warning, not running in deamon mode. maybe we will come up again, but don't lean on it.\n";
681                         state = ERROR;
682                 }
683
684                 restart_server = extract_int(argbuf, 0);
685                 new_state -= 2;
686         }
687         if ((new_state == 0) || (new_state == 1)) {
688                 ScheduledShutdown = new_state;
689         }
690         cprintf(Reply, state, ScheduledShutdown);
691 }
692
693
694
695 /*
696  * Back-end function for starting a session
697  */
698 void begin_session(CitContext *con)
699 {
700         /* 
701          * Initialize some variables specific to our context.
702          */
703         con->logged_in = 0;
704         con->internal_pgm = 0;
705         con->download_fp = NULL;
706         con->upload_fp = NULL;
707         con->cached_msglist = NULL;
708         con->cached_num_msgs = 0;
709         con->FirstExpressMessage = NULL;
710         time(&con->lastcmd);
711         time(&con->lastidle);
712         strcpy(con->lastcmdname, "    ");
713         strcpy(con->cs_clientname, "(unknown)");
714         strcpy(con->curr_user, NLI);
715         *con->net_node = '\0';
716         *con->fake_username = '\0';
717         *con->fake_hostname = '\0';
718         *con->fake_roomname = '\0';
719         *con->cs_clientinfo = '\0';
720         safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
721         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
722         con->cs_UDSclientUID = -1;
723         con->cs_host[sizeof con->cs_host - 1] = 0;
724         if (!CC->is_local_socket) {
725                 locate_host(con->cs_host, sizeof con->cs_host,
726                         con->cs_addr, sizeof con->cs_addr,
727                         con->client_socket
728                 );
729         }
730         else {
731                 con->cs_host[0] = 0;
732                 con->cs_addr[0] = 0;
733 #ifdef HAVE_STRUCT_UCRED
734                 {
735                         /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
736                         struct ucred credentials;
737                         socklen_t ucred_length = sizeof(struct ucred);
738                         
739                         /*fill in the user data structure */
740                         if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
741                                 syslog(LOG_NOTICE, "could obtain credentials from unix domain socket");
742                                 
743                         }
744                         else {          
745                                 /* the process ID of the process on the other side of the socket */
746                                 /* credentials.pid; */
747                                 
748                                 /* the effective UID of the process on the other side of the socket  */
749                                 con->cs_UDSclientUID = credentials.uid;
750                                 
751                                 /* the effective primary GID of the process on the other side of the socket */
752                                 /* credentials.gid; */
753                                 
754                                 /* To get supplemental groups, we will have to look them up in our account
755                                    database, after a reverse lookup on the UID to get the account name.
756                                    We can take this opportunity to check to see if this is a legit account.
757                                 */
758                                 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
759                                          "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ", 
760                                          credentials.pid,
761                                          credentials.uid,
762                                          credentials.gid);
763                         }
764                 }
765 #endif
766         }
767         con->cs_flags = 0;
768         con->upload_type = UPL_FILE;
769         con->dl_is_net = 0;
770
771         con->nologin = 0;
772         if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
773                 con->nologin = 1;
774         }
775
776         if (!CC->is_local_socket) {
777                 syslog(LOG_NOTICE, "Session (%s) started from %s (%s).\n", con->ServiceName, con->cs_host, con->cs_addr);
778         }
779         else {
780                 syslog(LOG_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
781         }
782
783         /* Run any session startup routines registered by loadable modules */
784         PerformSessionHooks(EVT_START);
785 }
786
787
788 void citproto_begin_session() {
789         if (CC->nologin==1) {
790                 cprintf("%d %s: Too many users are already online (maximum is %d)\n",
791                         ERROR + MAX_SESSIONS_EXCEEDED,
792                         config.c_nodename, config.c_maxsessions
793                 );
794                 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
795         }
796         else {
797                 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
798                 CC->can_receive_im = 1;
799         }
800 }
801
802
803 void citproto_begin_admin_session() {
804         CC->internal_pgm = 1;
805         cprintf("%d %s Citadel server ADMIN CONNECTION ready.\n", CIT_OK, config.c_nodename);
806 }
807
808
809
810
811 /*
812  * This loop recognizes all server commands.
813  */
814 void do_command_loop(void) {
815         char cmdbuf[SIZ];
816         
817         time(&CC->lastcmd);
818         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
819         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
820                 syslog(LOG_ERR, "Citadel client disconnected: ending session.\n");
821                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
822                 return;
823         }
824
825         /* Log the server command, but don't show passwords... */
826         if ( (strncasecmp(cmdbuf, "PASS", 4)) && (strncasecmp(cmdbuf, "SETP", 4)) ) {
827                 syslog(LOG_INFO, "[%d][%s(%ld)] %s",
828                         CC->cs_pid, CC->curr_user, CC->user.usernum, cmdbuf
829                 );
830         }
831         else {
832                 syslog(LOG_INFO, "[%d][%s(%ld)] <password command hidden from log>",
833                         CC->cs_pid, CC->curr_user, CC->user.usernum
834                 );
835         }
836
837         buffer_output();
838
839         /*
840          * Let other clients see the last command we executed, and
841          * update the idle time, but not NOOP, QNOP, PEXP, GEXP, RWHO, or TIME.
842          */
843         if ( (strncasecmp(cmdbuf, "NOOP", 4))
844            && (strncasecmp(cmdbuf, "QNOP", 4))
845            && (strncasecmp(cmdbuf, "PEXP", 4))
846            && (strncasecmp(cmdbuf, "GEXP", 4))
847            && (strncasecmp(cmdbuf, "RWHO", 4))
848            && (strncasecmp(cmdbuf, "TIME", 4)) ) {
849                 strcpy(CC->lastcmdname, "    ");
850                 safestrncpy(CC->lastcmdname, cmdbuf, sizeof(CC->lastcmdname));
851                 time(&CC->lastidle);
852         }
853         
854         if ((strncasecmp(cmdbuf, "ENT0", 4))
855            && (strncasecmp(cmdbuf, "MESG", 4))
856            && (strncasecmp(cmdbuf, "MSGS", 4)))
857         {
858            CC->cs_flags &= ~CS_POSTING;
859         }
860                    
861         if (!DLoader_Exec_Cmd(cmdbuf)) {
862                 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
863         }       
864
865         unbuffer_output();
866
867         /* Run any after-each-command routines registered by modules */
868         PerformSessionHooks(EVT_CMD);
869 }
870
871
872 /*
873  * This loop performs all asynchronous functions.
874  */
875 void do_async_loop(void) {
876         PerformSessionHooks(EVT_ASYNC);
877 }
878
879
880 /*****************************************************************************/
881 /*                      MODULE INITIALIZATION STUFF                          */
882 /*****************************************************************************/
883
884 CTDL_MODULE_INIT(citserver)
885 {
886         if (!threading) {
887
888                 CtdlRegisterProtoHook(cmd_mesg, "MESG", "fetch system banners");
889                 CtdlRegisterProtoHook(cmd_emsg, "EMSG", "submit system banners");
890 ;
891                 CtdlRegisterProtoHook(cmd_down, "DOWN", "perform a server shutdown");
892                 CtdlRegisterProtoHook(cmd_halt, "HALT", "halt the server without exiting the server process");
893                 CtdlRegisterProtoHook(cmd_scdn, "SCDN", "schedule or cancel a server shutdown");
894         }
895         /* return our id for the Log */
896         return "citserver";
897 }