2 * Citadel context management stuff.
3 * Here's where we (hopefully) have all the code that manipulates contexts.
5 * Copyright (c) 1987-2015 by the citadel.org team
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License, version 3.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
16 #include "ctdl_module.h"
17 #include "serv_extensions.h"
20 #include "citserver.h"
22 #include "locate_host.h"
29 pthread_key_t MyConKey; /* TSD key for MyContext() */
33 CitContext *ContextList = NULL;
35 time_t last_purge = 0; /* Last dead session purge */
36 int num_sessions = 0; /* Current number of sessions */
39 /* Flag for single user mode */
40 static int want_single_user = 0;
42 /* Try to go single user */
44 int CtdlTrySingleUser(void)
48 begin_critical_section(S_SINGLE_USER);
56 end_critical_section(S_SINGLE_USER);
60 void CtdlEndSingleUser(void)
62 begin_critical_section(S_SINGLE_USER);
64 end_critical_section(S_SINGLE_USER);
68 int CtdlWantSingleUser(void)
70 return want_single_user;
73 int CtdlIsSingleUser(void)
77 /* check for only one context here */
78 if (num_sessions == 1)
89 * Locate a context by its session number and terminate it if the user is able.
90 * User can NOT terminate their current session.
91 * User CAN terminate any other session that has them logged in.
92 * Aide CAN terminate any session except the current one.
94 int CtdlTerminateOtherSession (int session_num)
96 struct CitContext *CCC = CC;
101 if (session_num == CCC->cs_pid) return TERM_NOTALLOWED;
103 aide = ( (CCC->user.axlevel >= AxAideU) || (CCC->internal_pgm) ) ;
105 CONM_syslog(LOG_DEBUG, "Locating session to kill\n");
106 begin_critical_section(S_SESSION_TABLE);
107 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
108 if (session_num == ccptr->cs_pid) {
110 if ((ccptr->user.usernum == CCC->user.usernum) || aide) {
117 if (((ret & TERM_FOUND) != 0) && ((ret & TERM_ALLOWED) != 0))
119 if (ccptr->IO != NULL) {
120 AsyncIO *IO = ccptr->IO;
121 end_critical_section(S_SESSION_TABLE);
122 KillAsyncIOContext(IO);
126 if (ccptr->user.usernum == CCC->user.usernum)
127 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
129 ccptr->kill_me = KILLME_IDLE;
130 end_critical_section(S_SESSION_TABLE);
134 end_critical_section(S_SESSION_TABLE);
142 * Check to see if the user who we just sent mail to is logged in. If yes,
143 * bump the 'new mail' counter for their session. That enables them to
144 * receive a new mail notification without having to hit the database.
146 void BumpNewMailCounter(long which_user)
148 CtdlBumpNewMailCounter(which_user);
151 void CtdlBumpNewMailCounter(long which_user)
155 begin_critical_section(S_SESSION_TABLE);
157 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
158 if (ptr->user.usernum == which_user) {
163 end_critical_section(S_SESSION_TABLE);
168 * Check to see if a user is currently logged in
169 * Take care with what you do as a result of this test.
170 * The user may not have been logged in when this function was called BUT
171 * because of threading the user might be logged in before you test the result.
173 int CtdlIsUserLoggedIn (char *user_name)
178 begin_critical_section (S_SESSION_TABLE);
179 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
180 if (!strcasecmp(cptr->user.fullname, user_name)) {
185 end_critical_section(S_SESSION_TABLE);
192 * Check to see if a user is currently logged in.
193 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
194 * Take care with what you do as a result of this test.
195 * The user may not have been logged in when this function was called BUT
196 * because of threading the user might be logged in before you test the result.
198 int CtdlIsUserLoggedInByNum (long usernum)
203 begin_critical_section(S_SESSION_TABLE);
204 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
205 if (cptr->user.usernum == usernum) {
209 end_critical_section(S_SESSION_TABLE);
216 * Return a pointer to the CitContext structure bound to the thread which
217 * called this function. If there's no such binding (for example, if it's
218 * called by the housekeeper thread) then a generic 'master' CC is returned.
220 * This function is used *VERY* frequently and must be kept small.
222 CitContext *MyContext(void) {
223 register CitContext *c;
224 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
231 * Terminate idle sessions. This function pounds through the session table
232 * comparing the current time to each session's time-of-last-command. If an
233 * idle session is found it is terminated, then the search restarts at the
234 * beginning because the pointer to our place in the list becomes invalid.
236 void terminate_idle_sessions(void)
244 begin_critical_section(S_SESSION_TABLE);
245 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
248 && (CtdlGetConfigLong("c_sleeping") > 0)
249 && (now - (ccptr->lastcmd) > CtdlGetConfigLong("c_sleeping"))
251 if (!ccptr->dont_term) {
252 ccptr->kill_me = KILLME_IDLE;
260 end_critical_section(S_SESSION_TABLE);
262 CON_syslog(LOG_INFO, "Scheduled %d idle sessions for termination\n", killed);
264 CON_syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
269 * During shutdown, close the sockets of any sessions still connected.
271 void terminate_all_sessions(void)
276 begin_critical_section(S_SESSION_TABLE);
277 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
278 if (ccptr->client_socket != -1)
280 if (ccptr->IO != NULL) {
281 CON_syslog(LOG_INFO, "terminate_all_sessions() is murdering %s IO[%ld]CC[%d]", ccptr->curr_user, ccptr->IO->ID, ccptr->cs_pid);
284 CON_syslog(LOG_INFO, "terminate_all_sessions() is murdering %s CC[%d]", ccptr->curr_user, ccptr->cs_pid);
286 close(ccptr->client_socket);
287 ccptr->client_socket = -1;
291 end_critical_section(S_SESSION_TABLE);
293 CON_syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
300 * Terminate a session.
302 void RemoveContext (CitContext *con)
306 CONM_syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
309 c = con->ServiceName;
313 CON_syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
316 /* Run any cleanup routines registered by loadable modules.
317 * Note: We have to "become_session()" because the cleanup functions
318 * might make references to "CC" assuming it's the right one.
322 PerformSessionHooks(EVT_STOP);
323 client_close(); /* If the client is still connected, blow 'em away. */
324 become_session(NULL);
326 CON_syslog(LOG_NOTICE, "[%3d]SRV[%s] Session ended.", con->cs_pid, c);
329 * If the client is still connected, blow 'em away.
330 * if the socket is 0 or -1, its already gone or was never there.
332 if (con->client_socket > 0)
334 CON_syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
335 close(con->client_socket);
338 /* If using AUTHMODE_LDAP, free the DN */
343 FreeStrBuf(&con->StatusMessage);
344 FreeStrBuf(&con->MigrateBuf);
345 FreeStrBuf(&con->RecvBuf.Buf);
346 if (con->cached_msglist) {
347 free(con->cached_msglist);
350 CONM_syslog(LOG_DEBUG, "Done with RemoveContext()");
356 * Initialize a new context and place it in the list. The session number
357 * used to be the PID (which is why it's called cs_pid), but that was when we
358 * had one process per session. Now we just assign them sequentially, starting
359 * at 1 (don't change it to 0 because masterCC uses 0).
361 CitContext *CreateNewContext(void) {
364 me = (CitContext *) malloc(sizeof(CitContext));
366 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
369 memset(me, 0, sizeof(CitContext));
371 /* Give the context a name. Hopefully makes it easier to track */
372 strcpy (me->user.fullname, "SYS_notauth");
374 /* The new context will be created already in the CON_EXECUTING state
375 * in order to prevent another thread from grabbing it while it's
378 me->state = CON_EXECUTING;
380 * Generate a unique session number and insert this context into
383 me->MigrateBuf = NewStrBuf();
385 me->RecvBuf.Buf = NewStrBuf();
387 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide TODO: if we have a valid IO, use that to set the timer. */
390 begin_critical_section(S_SESSION_TABLE);
391 me->cs_pid = ++next_pid;
393 me->next = ContextList;
395 if (me->next != NULL) {
399 end_critical_section(S_SESSION_TABLE);
405 * Initialize a new context and place it in the list. The session number
406 * used to be the PID (which is why it's called cs_pid), but that was when we
407 * had one process per session. Now we just assign them sequentially, starting
408 * at 1 (don't change it to 0 because masterCC uses 0).
410 CitContext *CloneContext(CitContext *CloneMe) {
413 me = (CitContext *) malloc(sizeof(CitContext));
415 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
418 memcpy(me, CloneMe, sizeof(CitContext));
420 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
421 memset(&me->SendBuf, 0, sizeof(IOBuffer));
422 memset(&me->SBuf, 0, sizeof(IOBuffer));
423 me->MigrateBuf = NULL;
424 me->sMigrateBuf = NULL;
425 me->redirect_buffer = NULL;
430 me->download_fp = NULL;
431 me->upload_fp = NULL;
432 /// TODO: what about the room/user?
434 me->openid_data = NULL;
436 me->session_specific_data = NULL;
440 me->cached_msglist = NULL;
441 me->download_fp = NULL;
442 me->upload_fp = NULL;
443 me->client_socket = 0;
445 me->MigrateBuf = NewStrBuf();
446 me->RecvBuf.Buf = NewStrBuf();
448 begin_critical_section(S_SESSION_TABLE);
450 me->cs_pid = ++next_pid;
452 me->next = ContextList;
453 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
455 if (me->next != NULL) {
460 end_critical_section(S_SESSION_TABLE);
466 * Return an array containing a copy of the context list.
467 * This allows worker threads to perform "for each context" operations without
468 * having to lock and traverse the live list.
470 CitContext *CtdlGetContextArray(int *count)
473 CitContext *nptr, *cptr;
475 nContexts = num_sessions;
476 nptr = malloc(sizeof(CitContext) * nContexts);
481 begin_critical_section(S_SESSION_TABLE);
482 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
483 memcpy(&nptr[i], cptr, sizeof (CitContext));
485 end_critical_section (S_SESSION_TABLE);
494 * Back-end function for starting a session
496 void begin_session(CitContext *con)
499 * Initialize some variables specific to our context.
502 con->internal_pgm = 0;
503 con->download_fp = NULL;
504 con->upload_fp = NULL;
505 con->cached_msglist = NULL;
506 con->cached_num_msgs = 0;
507 con->FirstExpressMessage = NULL;
509 time(&con->lastidle);
510 strcpy(con->lastcmdname, " ");
511 strcpy(con->cs_clientname, "(unknown)");
512 strcpy(con->curr_user, NLI);
513 *con->net_node = '\0';
514 *con->fake_username = '\0';
515 *con->fake_hostname = '\0';
516 *con->fake_roomname = '\0';
517 *con->cs_clientinfo = '\0';
518 safestrncpy(con->cs_host, CtdlGetConfigStr("c_fqdn"), sizeof con->cs_host);
519 safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
520 con->cs_UDSclientUID = -1;
521 con->cs_host[sizeof con->cs_host - 1] = 0;
522 if (!CC->is_local_socket) {
523 locate_host(con->cs_host, sizeof con->cs_host,
524 con->cs_addr, sizeof con->cs_addr,
531 #ifdef HAVE_STRUCT_UCRED
533 /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
534 struct ucred credentials;
535 socklen_t ucred_length = sizeof(struct ucred);
537 /*fill in the user data structure */
538 if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
539 syslog(LOG_NOTICE, "could obtain credentials from unix domain socket");
543 /* the process ID of the process on the other side of the socket */
544 /* credentials.pid; */
546 /* the effective UID of the process on the other side of the socket */
547 con->cs_UDSclientUID = credentials.uid;
549 /* the effective primary GID of the process on the other side of the socket */
550 /* credentials.gid; */
552 /* To get supplemental groups, we will have to look them up in our account
553 database, after a reverse lookup on the UID to get the account name.
554 We can take this opportunity to check to see if this is a legit account.
556 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
557 "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ",
566 con->upload_type = UPL_FILE;
570 if (((CtdlGetConfigInt("c_maxsessions") > 0)&&(num_sessions > CtdlGetConfigInt("c_maxsessions"))) || CtdlWantSingleUser()) {
574 if (!CC->is_local_socket) {
575 syslog(LOG_NOTICE, "Session (%s) started from %s (%s).\n", con->ServiceName, con->cs_host, con->cs_addr);
578 syslog(LOG_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
581 /* Run any session startup routines registered by loadable modules */
582 PerformSessionHooks(EVT_START);
587 * This function fills in a context and its user field correctly
588 * Then creates/loads that user
590 void CtdlFillSystemContext(CitContext *context, char *name)
595 memset(context, 0, sizeof(CitContext));
596 context->internal_pgm = 1;
598 strcpy (sysname, "SYS_");
599 strcat (sysname, name);
600 len = cutuserkey(sysname);
601 memcpy(context->curr_user, sysname, len + 1);
602 context->client_socket = (-1);
603 context->state = CON_SYS;
604 context->ServiceName = name;
606 /* internal_create_user has the side effect of loading the user regardless of wether they
607 * already existed or needed to be created
609 internal_create_user (sysname, len, &(context->user), -1) ;
611 /* Check to see if the system user needs upgrading */
612 if (context->user.usernum == 0)
613 { /* old system user with number 0, upgrade it */
614 context->user.usernum = get_new_user_number();
615 CON_syslog(LOG_INFO, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
616 /* add user to the database */
617 CtdlPutUser(&(context->user));
618 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
624 * Cleanup any contexts that are left lying around
626 void context_cleanup(void)
628 CitContext *ptr = NULL;
629 CitContext *rem = NULL;
632 * Clean up the contexts.
633 * There are no threads so no critical_section stuff is needed.
637 /* We need to update the ContextList because some modules may want to itterate it
638 * Question is should we NULL it before iterating here or should we just keep updating it
639 * as we remove items?
641 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
645 /* Remove the session from the active list */
649 CON_syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
659 * Purge all sessions which have the 'kill_me' flag set.
660 * This function has code to prevent it from running more than once every
661 * few seconds, because running it after every single unbind would waste a lot
662 * of CPU time and keep the context list locked too much. To force it to run
663 * anyway, set "force" to nonzero.
665 void dead_session_purge(int force) {
666 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
667 CitContext *rem = NULL; /* list of sessions to be destroyed */
670 if ( (time(NULL) - last_purge) < 5 ) {
671 return; /* Too soon, go away */
676 if (try_critical_section(S_SESSION_TABLE))
684 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
685 /* Remove the session from the active list */
687 ptr2->prev->next = ptr2->next;
690 ContextList = ptr2->next;
693 ptr2->next->prev = ptr2->prev;
697 /* And put it on our to-be-destroyed list */
702 end_critical_section(S_SESSION_TABLE);
704 /* Now that we no longer have the session list locked, we can take
705 * our time and destroy any sessions on the to-be-killed list, which
706 * is allocated privately on this thread's stack.
708 while (rem != NULL) {
709 CON_syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
722 * masterCC is the context we use when not attached to a session. This
723 * function initializes it.
725 void InitializeMasterCC(void) {
726 memset(&masterCC, 0, sizeof(struct CitContext));
727 masterCC.internal_pgm = 1;
736 * Set the "async waiting" flag for a session, if applicable
738 void set_async_waiting(struct CitContext *ccptr)
740 CON_syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
741 if (ccptr->is_async) {
742 ccptr->async_waiting++;
743 if (ccptr->state == CON_IDLE) {
744 ccptr->state = CON_READY;
750 void DebugSessionEnable(const int n)
754 CTDL_MODULE_INIT(session)
757 CtdlRegisterDebugFlagHook(HKEY("session"), DebugSessionEnable, &DebugSession);