2 * Main source module for the Citadel server
4 * Copyright (c) 1987-2011 by the citadel.org team
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.
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.
21 #include <sys/types.h>
24 #if TIME_WITH_SYS_TIME
25 # include <sys/time.h>
29 # include <sys/time.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>
52 #include "sysdep_decls.h"
54 #include "citserver.h"
57 #include "housekeeping.h"
61 #include "locate_host.h"
64 #include "euidindex.h"
66 #include "svn_revision.h"
67 #include "ctdl_module.h"
69 char *unique_session_numbers;
70 int ScheduledShutdown = 0;
71 time_t server_startup_time;
73 int openid_level_supported = 0;
76 * print the actual stack frame.
78 void cit_backtrace(void)
81 void *stack_frames[50];
86 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
87 strings = backtrace_symbols(stack_frames, size);
88 for (i = 0; i < size; i++) {
90 syslog(LOG_ALERT, "%s\n", strings[i]);
92 syslog(LOG_ALERT, "%p\n", stack_frames[i]);
98 void cit_oneline_backtrace(void)
100 #ifdef HAVE_BACKTRACE
101 void *stack_frames[50];
106 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
107 strings = backtrace_symbols(stack_frames, size);
111 for (i = 1; i < size; i++) {
113 StrBufAppendPrintf(Buf, "%s : ", strings[i]);
115 StrBufAppendPrintf(Buf, "%p : ", stack_frames[i]);
118 syslog(LOG_ALERT, "%s\n", ChrPtr(Buf));
125 * print the actual stack frame.
127 void cit_panic_backtrace(int SigNum)
129 #ifdef HAVE_BACKTRACE
130 void *stack_frames[10];
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++) {
139 syslog(LOG_ALERT, "%s\n", strings[i]);
141 syslog(LOG_ALERT, "%p\n", stack_frames[i]);
149 * Various things that need to be initialized at startup
151 void master_startup(void) {
155 struct ctdlroom qrbuf;
158 syslog(LOG_DEBUG, "master_startup() started\n");
159 time(&server_startup_time);
162 syslog(LOG_INFO, "Opening databases\n");
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);
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);
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);
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);
189 syslog(LOG_EMERG, "failed to read random seed: %s\n",
194 gettimeofday(&tv, NULL);
202 syslog(LOG_DEBUG, "master_startup() finished\n");
207 * Cleanup routine to be called when the server is shutting down.
209 void master_cleanup(int exitcode) {
210 struct CleanupFunctionHook *fcn;
211 static int already_cleaning_up = 0;
213 if (already_cleaning_up) while(1) usleep(1000000);
214 already_cleaning_up = 1;
216 /* Run any cleanup routines registered by loadable modules */
217 for (fcn = CleanupHookTable; fcn != NULL; fcn = fcn->next) {
218 (*fcn->h_function_pointer)();
221 /* Close the AdjRefCount queue file */
224 /* Do system-dependent stuff */
225 sysdep_master_cleanup();
227 /* Close databases */
228 syslog(LOG_INFO, "Closing databases\n");
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);
243 syslog(LOG_NOTICE, "citserver: Exiting with status %d\n", exitcode);
244 fflush(stdout); fflush(stderr);
246 if (restart_server != 0)
248 if ((running_as_daemon != 0) && ((exitcode == 0) ))
249 exitcode = CTDLEXIT_SHUTDOWN;
256 * returns an asterisk if there are any instant messages waiting,
259 char CtdlCheckExpress(void) {
260 if (CC->FirstExpressMessage == NULL) {
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
275 int CtdlIsPublicClient(void)
281 char *public_clientspos;
282 char *public_clientsend;
285 static time_t pc_timestamp = 0;
286 static char public_clients[SIZ];
287 static char public_clients_file[SIZ];
289 #define LOCALHOSTSTR "127.0.0.1"
291 snprintf(public_clients_file, sizeof public_clients_file, "%s/public_clients", ctdl_etc_dir);
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.
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);
306 if (statbuf.st_mtime > pc_timestamp) {
307 begin_critical_section(S_PUBLIC_CLIENTS);
308 syslog(LOG_INFO, "Loading %s\n", public_clients_file);
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;
315 if (hostname_to_dotted_quad(addrbuf, config.c_fqdn) == 0) {
316 *(public_clientspos++) = '|';
318 while (!IsEmptyStr (paddr) &&
319 (public_clientspos < public_clientsend))
320 *(public_clientspos++) = *(paddr++);
323 fp = fopen(public_clients_file, "r");
325 while ((fgets(buf, sizeof buf, fp)!=NULL) &&
326 (public_clientspos < public_clientsend)){
329 while (!IsEmptyStr(ptr)) {
337 while (ptr>buf && isspace(*ptr)) {
340 if (hostname_to_dotted_quad(addrbuf, buf) == 0) {
341 *(public_clientspos++) = '|';
343 while (!IsEmptyStr(paddr) &&
344 (public_clientspos < public_clientsend)){
345 *(public_clientspos++) = *(paddr++);
349 if (fp != NULL) fclose(fp);
350 pc_timestamp = time(NULL);
351 end_critical_section(S_PUBLIC_CLIENTS);
354 syslog(LOG_DEBUG, "Checking whether %s is a local or public client\n",
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");
364 /* No hits. This is not a public client. */
365 syslog(LOG_DEBUG, "... no it isn't.\n");
372 * help_subst() - support routine for help file viewer
374 void help_subst(char *strbuf, char *source, char *dest)
379 while (p = pattern2(strbuf, source), (p >= 0)) {
380 strcpy(workbuf, &strbuf[p + strlen(source)]);
381 strcpy(&strbuf[p], dest);
382 strcat(strbuf, workbuf);
386 void do_help_subst(char *buffer)
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);
404 typedef const char *ccharp;
406 * display system messages or help
408 void cmd_mesg(char *mname)
418 extract_token(buf, mname, 0, '|', sizeof buf);
420 dirs[0] = strdup(ctdl_message_dir);
421 dirs[1] = strdup(ctdl_hlp_dir);
423 snprintf(buf2, sizeof buf2, "%s.%d.%d",
424 buf, CC->cs_clientdev, CC->cs_clienttyp);
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]);
431 while (d = readdir(dp), d != NULL) {
432 if (d->d_name[0] != '.') {
433 cprintf(" %s\n", d->d_name);
444 /* Otherwise, look for the requested file by name. */
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);
462 if (IsEmptyStr(targ)) {
463 cprintf("%d '%s' not found. (Searching in %s and %s)\n",
464 ERROR + FILE_NOT_FOUND,
472 mfp = fopen(targ, "r");
474 cprintf("%d Cannot open '%s': %s\n",
475 ERROR + INTERNAL_ERROR, targ, strerror(errno));
478 cprintf("%d %s\n", LISTING_FOLLOWS,buf);
480 while (fgets(buf, (sizeof buf - 1), mfp) != NULL) {
481 buf[strlen(buf)-1] = 0;
492 * enter system messages or help
494 void cmd_emsg(char *mname)
504 if (CtdlAccessCheck(ac_aide)) return;
506 extract_token(buf, mname, 0, '|', sizeof buf);
507 for (a=0; !IsEmptyStr(&buf[a]); ++a) { /* security measure */
508 if (buf[a] == '/') buf[a] = '.';
511 dirs[0] = strdup(ctdl_message_dir);
512 dirs[1] = strdup(ctdl_hlp_dir);
514 mesg_locate(targ, sizeof targ, buf, 2, (const ccharp*)dirs);
518 if (IsEmptyStr(targ)) {
519 snprintf(targ, sizeof targ,
524 mfp = fopen(targ,"w");
526 cprintf("%d Cannot open '%s': %s\n",
527 ERROR + INTERNAL_ERROR, targ, strerror(errno));
530 cprintf("%d %s\n", SEND_LISTING, targ);
532 while (client_getln(buf, sizeof buf) >=0 && strcmp(buf, "000")) {
533 fprintf(mfp, "%s\n", buf);
540 /* Don't show the names of private rooms unless the viewing
541 * user also knows the rooms.
543 void GenerateRoomDisplay(char *real_room,
545 CitContext *viewer) {
549 strcpy(real_room, viewed->room.QRname);
550 if (viewed->room.QRflags & QR_MAILBOX) {
551 strcpy(real_room, &real_room[11]);
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, " ");
560 if (viewed->cs_flags & CS_CHAT) {
561 while (strlen(real_room) < 14) {
562 strcat(real_room, " ");
564 strcpy(&real_room[14], "<chat>");
570 * Convenience function.
572 int CtdlAccessCheck(int required_level) {
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);
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);
586 if ((required_level >= ac_logged_in) && (CC->logged_in == 0)) {
587 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
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);
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);
605 /* shhh ... succeed quietly */
615 * Shut down the server
617 void cmd_down(char *argbuf) {
618 char *Reply ="%d Shutting down server. Goodbye.\n";
620 if (CtdlAccessCheck(ac_aide)) return;
622 if (!IsEmptyStr(argbuf))
625 restart_server = extract_int(argbuf, 0);
627 if (restart_server > 0)
629 Reply = "%d citserver will now shut down and automatically restart.\n";
631 if ((restart_server > 0) && !running_as_daemon)
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";
637 cprintf(Reply, state);
641 cprintf(Reply, CIT_OK + SERVER_SHUTTING_DOWN);
643 CC->kill_me = KILLME_SERVER_SHUTTING_DOWN;
644 server_shutting_down = 1;
649 * Halt the server without exiting the server process.
651 void cmd_halt(char *argbuf) {
653 if (CtdlAccessCheck(ac_aide)) return;
655 cprintf("%d Halting server. Goodbye.\n", CIT_OK);
656 server_shutting_down = 1;
657 shutdown_and_halt = 1;
662 * Schedule or cancel a server shutdown
664 void cmd_scdn(char *argbuf)
668 char *Reply = "%d %d\n";
670 if (CtdlAccessCheck(ac_aide)) return;
672 new_state = extract_int(argbuf, 0);
673 if ((new_state == 2) || (new_state == 3))
676 if (!running_as_daemon)
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";
683 restart_server = extract_int(argbuf, 0);
686 if ((new_state == 0) || (new_state == 1)) {
687 ScheduledShutdown = new_state;
689 cprintf(Reply, state, ScheduledShutdown);
695 * Back-end function for starting a session
697 void begin_session(CitContext *con)
700 * Initialize some variables specific to our context.
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;
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,
732 #ifdef HAVE_STRUCT_UCRED
734 /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
735 struct ucred credentials;
736 socklen_t ucred_length = sizeof(struct ucred);
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");
744 /* the process ID of the process on the other side of the socket */
745 /* credentials.pid; */
747 /* the effective UID of the process on the other side of the socket */
748 con->cs_UDSclientUID = credentials.uid;
750 /* the effective primary GID of the process on the other side of the socket */
751 /* credentials.gid; */
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.
757 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
758 "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ",
767 con->upload_type = UPL_FILE;
771 if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
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);
779 syslog(LOG_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
782 /* Run any session startup routines registered by loadable modules */
783 PerformSessionHooks(EVT_START);
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
793 CC->kill_me = KILLME_MAX_SESSIONS_EXCEEDED;
796 cprintf("%d %s Citadel server ready.\n", CIT_OK, config.c_nodename);
797 CC->can_receive_im = 1;
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);
811 * This loop recognizes all server commands.
813 void do_command_loop(void) {
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;
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
831 syslog(LOG_INFO, "[%d][%s(%ld)] <password command hidden from log>",
832 CC->cs_pid, CC->curr_user, CC->user.usernum
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.
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));
853 if ((strncasecmp(cmdbuf, "ENT0", 4))
854 && (strncasecmp(cmdbuf, "MESG", 4))
855 && (strncasecmp(cmdbuf, "MSGS", 4)))
857 CC->cs_flags &= ~CS_POSTING;
860 if (!DLoader_Exec_Cmd(cmdbuf)) {
861 cprintf("%d Unrecognized or unsupported command.\n", ERROR + CMD_NOT_SUPPORTED);
866 /* Run any after-each-command routines registered by modules */
867 PerformSessionHooks(EVT_CMD);
872 * This loop performs all asynchronous functions.
874 void do_async_loop(void) {
875 PerformSessionHooks(EVT_ASYNC);
879 /*****************************************************************************/
880 /* MODULE INITIALIZATION STUFF */
881 /*****************************************************************************/
883 CTDL_MODULE_INIT(citserver)
887 CtdlRegisterProtoHook(cmd_mesg, "MESG", "fetch system banners");
888 CtdlRegisterProtoHook(cmd_emsg, "EMSG", "submit system banners");
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");
894 /* return our id for the Log */