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