1 // Citadel context management stuff.
2 // Here's where we (hopefully) have all the code that manipulates contexts.
4 // Copyright (c) 1987-2023 by the citadel.org team
6 // This program is open source software. Use, duplication, or disclosure
7 // is subject to the terms of the GNU General Public License, version 3.
9 #include "ctdl_module.h"
10 #include "serv_extensions.h"
11 #include "citserver.h"
13 #include "locate_host.h"
18 pthread_key_t MyConKey; /* TSD key for MyContext() */
20 CitContext *ContextList = NULL;
21 time_t last_purge = 0; /* Last dead session purge */
22 int num_sessions = 0; /* Current number of sessions */
25 /* Flag for single user mode */
26 static int want_single_user = 0;
28 /* Try to go single user */
30 int CtdlTrySingleUser(void) {
33 begin_critical_section(S_SINGLE_USER);
34 if (want_single_user) {
41 end_critical_section(S_SINGLE_USER);
46 void CtdlEndSingleUser(void) {
47 begin_critical_section(S_SINGLE_USER);
49 end_critical_section(S_SINGLE_USER);
53 int CtdlWantSingleUser(void) {
54 return want_single_user;
58 int CtdlIsSingleUser(void) {
59 if (want_single_user) {
60 /* check for only one context here */
61 if (num_sessions == 1)
69 * Locate a context by its session number and terminate it if the user is able.
70 * User can NOT terminate their current session.
71 * User CAN terminate any other session that has them logged in.
72 * Aide CAN terminate any session except the current one.
74 int CtdlTerminateOtherSession (int session_num) {
79 if (session_num == CC->cs_pid) return TERM_NOTALLOWED;
81 aide = ( (CC->user.axlevel >= AxAideU) || (CC->internal_pgm) ) ;
83 syslog(LOG_DEBUG, "context: locating session to kill");
84 begin_critical_section(S_SESSION_TABLE);
85 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
86 if (session_num == ccptr->cs_pid) {
88 if ((ccptr->user.usernum == CC->user.usernum) || aide) {
95 if (((ret & TERM_FOUND) != 0) && ((ret & TERM_ALLOWED) != 0)) {
96 if (ccptr->user.usernum == CC->user.usernum) {
97 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
100 ccptr->kill_me = KILLME_IDLE;
102 end_critical_section(S_SESSION_TABLE);
105 end_critical_section(S_SESSION_TABLE);
112 // Check to see if the user who we just sent mail to is logged in. If yes,
113 // bump the 'new mail' counter for their session. That enables them to
114 // receive a new mail notification without having to hit the database.
115 void CtdlBumpNewMailCounter(long which_user) {
118 begin_critical_section(S_SESSION_TABLE);
120 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
121 if (ptr->user.usernum == which_user) {
126 end_critical_section(S_SESSION_TABLE);
131 * Check to see if a user is currently logged in
132 * Take care with what you do as a result of this test.
133 * The user may not have been logged in when this function was called BUT
134 * because of threading the user might be logged in before you test the result.
136 int CtdlIsUserLoggedIn(char *user_name) {
140 begin_critical_section (S_SESSION_TABLE);
141 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
142 if (!strcasecmp(cptr->user.fullname, user_name)) {
147 end_critical_section(S_SESSION_TABLE);
153 * Check to see if a user is currently logged in.
154 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
155 * Take care with what you do as a result of this test.
156 * The user may not have been logged in when this function was called BUT
157 * because of threading the user might be logged in before you test the result.
159 int CtdlIsUserLoggedInByNum (long usernum) {
163 begin_critical_section(S_SESSION_TABLE);
164 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
165 if (cptr->user.usernum == usernum) {
169 end_critical_section(S_SESSION_TABLE);
175 * Return a pointer to the CitContext structure bound to the thread which
176 * called this function. If there's no such binding (for example, if it's
177 * called by the housekeeper thread) then a generic 'master' CC is returned.
179 * This function is used *VERY* frequently and must be kept small.
181 CitContext *MyContext(void) {
182 register CitContext *c;
183 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
188 * Terminate idle sessions. This function pounds through the session table
189 * comparing the current time to each session's time-of-last-command. If an
190 * idle session is found it is terminated, then the search restarts at the
191 * beginning because the pointer to our place in the list becomes invalid.
193 void terminate_idle_sessions(void) {
200 begin_critical_section(S_SESSION_TABLE);
201 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
204 && (CtdlGetConfigLong("c_sleeping") > 0)
205 && (now - (ccptr->lastcmd) > CtdlGetConfigLong("c_sleeping"))
207 if (!ccptr->dont_term) {
208 ccptr->kill_me = KILLME_IDLE;
216 end_critical_section(S_SESSION_TABLE);
218 syslog(LOG_INFO, "context: scheduled %d idle sessions for termination", killed);
220 if (longrunners > 0) {
221 syslog(LOG_INFO, "context: did not terminate %d protected idle sessions", longrunners);
227 * During shutdown, close the sockets of any sessions still connected.
229 void terminate_all_sessions(void) {
233 begin_critical_section(S_SESSION_TABLE);
234 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
235 if (ccptr->client_socket != -1)
237 syslog(LOG_INFO, "context: terminate_all_sessions() is murdering %s CC[%d]", ccptr->curr_user, ccptr->cs_pid);
238 close(ccptr->client_socket);
239 ccptr->client_socket = -1;
243 end_critical_section(S_SESSION_TABLE);
245 syslog(LOG_INFO, "context: flushed %d stuck sessions", killed);
250 // Terminate a session.
251 void RemoveContext(CitContext *con) {
254 syslog(LOG_ERR, "context: RemoveContext() called with NULL, this should not happen");
257 c = con->ServiceName;
261 syslog(LOG_DEBUG, "context: RemoveContext(%s) session %d", c, con->cs_pid);
263 // Run any cleanup routines registered by loadable modules.
264 // Note: We have to "become_session()" because the cleanup functions might make references to "CC" assuming it's the right one.
267 PerformSessionHooks(EVT_STOP); // hooks may free some data structures, close SSL, etc.
268 client_close(); // If the client is still connected, disconnect them immediately.
269 become_session(NULL);
270 syslog(LOG_INFO, "context: session %d (%s) ended.", con->cs_pid, c);
272 /* If using AUTHMODE_LDAP, free the DN */
277 FreeStrBuf(&con->StatusMessage);
278 FreeStrBuf(&con->MigrateBuf);
279 FreeStrBuf(&con->RecvBuf.Buf);
280 if (con->cached_msglist) {
281 free(con->cached_msglist);
284 syslog(LOG_DEBUG, "context: done with RemoveContext()");
289 * Initialize a new context and place it in the list. The session number
290 * used to be the PID (which is why it's called cs_pid), but that was when we
291 * had one process per session. Now we just assign them sequentially, starting
292 * at 1 (don't change it to 0 because masterCC uses 0).
294 CitContext *CreateNewContext(void) {
297 me = (CitContext *) malloc(sizeof(CitContext));
299 syslog(LOG_ERR, "citserver: malloc() failed: %m");
302 memset(me, 0, sizeof(CitContext));
304 /* Give the context a name. Hopefully makes it easier to track */
305 strcpy (me->user.fullname, "SYS_notauth");
307 /* The new context will be created already in the CON_EXECUTING state
308 * in order to prevent another thread from grabbing it while it's
311 me->state = CON_EXECUTING;
313 * Generate a unique session number and insert this context into
316 me->MigrateBuf = NewStrBuf();
318 me->RecvBuf.Buf = NewStrBuf();
320 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. */
323 begin_critical_section(S_SESSION_TABLE);
324 me->cs_pid = ++next_pid;
326 me->next = ContextList;
328 if (me->next != NULL) {
332 end_critical_section(S_SESSION_TABLE);
338 * Initialize a new context and place it in the list. The session number
339 * used to be the PID (which is why it's called cs_pid), but that was when we
340 * had one process per session. Now we just assign them sequentially, starting
341 * at 1 (don't change it to 0 because masterCC uses 0).
343 CitContext *CloneContext(CitContext *CloneMe) {
346 me = (CitContext *) malloc(sizeof(CitContext));
348 syslog(LOG_ERR, "citserver: malloc() failed: %m");
351 memcpy(me, CloneMe, sizeof(CitContext));
353 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
354 memset(&me->SendBuf, 0, sizeof(IOBuffer));
355 memset(&me->SBuf, 0, sizeof(IOBuffer));
356 me->MigrateBuf = NULL;
357 me->sMigrateBuf = NULL;
358 me->redirect_buffer = NULL;
363 me->download_fp = NULL;
364 me->upload_fp = NULL;
365 /// TODO: what about the room/user?
368 me->session_specific_data = NULL;
372 me->cached_msglist = NULL;
373 me->download_fp = NULL;
374 me->upload_fp = NULL;
375 me->client_socket = 0;
377 me->MigrateBuf = NewStrBuf();
378 me->RecvBuf.Buf = NewStrBuf();
380 begin_critical_section(S_SESSION_TABLE);
382 me->cs_pid = ++next_pid;
384 me->next = ContextList;
385 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
387 if (me->next != NULL) {
392 end_critical_section(S_SESSION_TABLE);
398 * Return an array containing a copy of the context list.
399 * This allows worker threads to perform "for each context" operations without
400 * having to lock and traverse the live list.
402 CitContext *CtdlGetContextArray(int *count) {
404 CitContext *nptr, *cptr;
406 nContexts = num_sessions;
407 nptr = malloc(sizeof(CitContext) * nContexts);
412 begin_critical_section(S_SESSION_TABLE);
413 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
414 memcpy(&nptr[i], cptr, sizeof (CitContext));
416 end_critical_section (S_SESSION_TABLE);
424 * Back-end function for starting a session
426 void begin_session(CitContext *con) {
428 * Initialize some variables specific to our context.
431 con->internal_pgm = 0;
432 con->download_fp = NULL;
433 con->upload_fp = NULL;
434 con->cached_msglist = NULL;
435 con->cached_num_msgs = 0;
436 con->FirstExpressMessage = NULL;
438 time(&con->lastidle);
439 strcpy(con->lastcmdname, " ");
440 strcpy(con->cs_clientname, "(unknown)");
441 strcpy(con->curr_user, NLI);
442 *con->cs_clientinfo = '\0';
443 safestrncpy(con->cs_host, CtdlGetConfigStr("c_fqdn"), sizeof con->cs_host);
444 safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
445 con->cs_UDSclientUID = -1;
446 con->cs_host[sizeof con->cs_host - 1] = 0;
447 if (!CC->is_local_client) {
448 locate_host(con->cs_host, sizeof con->cs_host,
449 con->cs_addr, sizeof con->cs_addr,
456 #ifdef HAVE_STRUCT_UCRED
458 /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
459 struct ucred credentials;
460 socklen_t ucred_length = sizeof(struct ucred);
462 /*fill in the user data structure */
463 if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
464 syslog(LOG_ERR, "context: could obtain credentials from unix domain socket");
468 /* the process ID of the process on the other side of the socket */
469 /* credentials.pid; */
471 /* the effective UID of the process on the other side of the socket */
472 con->cs_UDSclientUID = credentials.uid;
474 /* the effective primary GID of the process on the other side of the socket */
475 /* credentials.gid; */
477 /* To get supplemental groups, we will have to look them up in our account
478 database, after a reverse lookup on the UID to get the account name.
479 We can take this opportunity to check to see if this is a legit account.
481 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
482 "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ",
493 if (((CtdlGetConfigInt("c_maxsessions") > 0)&&(num_sessions > CtdlGetConfigInt("c_maxsessions"))) || CtdlWantSingleUser()) {
497 syslog(LOG_INFO, "context: session (%s) started from %s (%s) uid=%d",
498 con->ServiceName, con->cs_host, con->cs_addr, con->cs_UDSclientUID
501 /* Run any session startup routines registered by loadable modules */
502 PerformSessionHooks(EVT_START);
507 * This function fills in a context and its user field correctly
508 * Then creates/loads that user
510 void CtdlFillSystemContext(CitContext *context, char *name) {
514 memset(context, 0, sizeof(CitContext));
515 context->internal_pgm = 1;
517 strcpy (sysname, "SYS_");
518 strcat (sysname, name);
519 len = strlen(sysname);
520 memcpy(context->curr_user, sysname, len + 1);
521 context->client_socket = (-1);
522 context->state = CON_SYS;
523 context->ServiceName = name;
525 /* internal_create_user has the side effect of loading the user regardless of whether they
526 * already existed or needed to be created
528 internal_create_user(sysname, &(context->user), -1) ;
530 /* Check to see if the system user needs upgrading */
531 if (context->user.usernum == 0) { /* old system user with number 0, upgrade it */
532 context->user.usernum = get_new_user_number();
533 syslog(LOG_INFO, "context: upgrading system user \"%s\" from user number 0 to user number %ld", context->user.fullname, context->user.usernum);
534 /* add user to the database */
535 CtdlPutUser(&(context->user));
536 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
542 * Cleanup any contexts that are left lying around
544 void context_cleanup(void) {
545 CitContext *ptr = NULL;
546 CitContext *rem = NULL;
549 * Clean up the contexts.
550 * There are no threads so no critical_section stuff is needed.
554 /* We need to update the ContextList because some modules may want to itterate it
555 * Question is should we NULL it before iterating here or should we just keep updating it
556 * as we remove items?
558 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
562 /* Remove the session from the active list */
566 syslog(LOG_DEBUG, "context: context_cleanup() purging session %d", ptr->cs_pid);
575 * Purge all sessions which have the 'kill_me' flag set.
576 * This function has code to prevent it from running more than once every
577 * few seconds, because running it after every single unbind would waste a lot
578 * of CPU time and keep the context list locked too much. To force it to run
579 * anyway, set "force" to nonzero.
581 void dead_session_purge(int force) {
582 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
583 CitContext *rem = NULL; /* list of sessions to be destroyed */
586 if ( (time(NULL) - last_purge) < 5 ) {
587 return; /* Too soon, go away */
592 if (try_critical_section(S_SESSION_TABLE))
600 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
601 /* Remove the session from the active list */
603 ptr2->prev->next = ptr2->next;
606 ContextList = ptr2->next;
609 ptr2->next->prev = ptr2->prev;
613 /* And put it on our to-be-destroyed list */
617 else if (ptr2->kill_me) {
618 syslog(LOG_DEBUG, "context: session %d is timed out but non-idle", rem->cs_pid);
621 end_critical_section(S_SESSION_TABLE);
623 /* Now that we no longer have the session list locked, we can take
624 * our time and destroy any sessions on the to-be-killed list, which
625 * is allocated privately on this thread's stack.
627 while (rem != NULL) {
628 syslog(LOG_DEBUG, "context: dead_session_purge() purging session %d, reason=%d", rem->cs_pid, rem->kill_me);
638 * masterCC is the context we use when not attached to a session. This
639 * function initializes it.
641 void InitializeMasterCC(void) {
642 memset(&masterCC, 0, sizeof(struct CitContext));
643 masterCC.internal_pgm = 1;
649 * Set the "async waiting" flag for a session, if applicable
651 void set_async_waiting(struct CitContext *ccptr) {
652 syslog(LOG_DEBUG, "context: setting async_waiting flag for session %d", ccptr->cs_pid);
653 if (ccptr->is_async) {
654 ccptr->async_waiting++;
655 if (ccptr->state == CON_IDLE) {
656 ccptr->state = CON_READY;
662 CTDL_MODULE_INIT(session)