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)
68 // Locate a context by its session number and terminate it if the user is able.
69 // User can NOT terminate their current session.
70 // User CAN terminate any other session that has them logged in.
71 // Aide CAN terminate any session except the current one.
72 int CtdlTerminateOtherSession (int session_num) {
77 if (session_num == CC->cs_pid) return TERM_NOTALLOWED;
79 aide = ( (CC->user.axlevel >= AxAideU) || (CC->internal_pgm) ) ;
81 syslog(LOG_DEBUG, "context: locating session to kill");
82 begin_critical_section(S_SESSION_TABLE);
83 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
84 if (session_num == ccptr->cs_pid) {
86 if ((ccptr->user.usernum == CC->user.usernum) || aide) {
93 if (((ret & TERM_FOUND) != 0) && ((ret & TERM_ALLOWED) != 0)) {
94 if (ccptr->user.usernum == CC->user.usernum) {
95 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
98 ccptr->kill_me = KILLME_IDLE;
100 end_critical_section(S_SESSION_TABLE);
103 end_critical_section(S_SESSION_TABLE);
110 // Check to see if the user who we just sent mail to is logged in. If yes,
111 // bump the 'new mail' counter for their session. That enables them to
112 // receive a new mail notification without having to hit the database.
113 void CtdlBumpNewMailCounter(long which_user) {
116 begin_critical_section(S_SESSION_TABLE);
118 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
119 if (ptr->user.usernum == which_user) {
124 end_critical_section(S_SESSION_TABLE);
128 // Check to see if a user is currently logged in
129 // Take care with what you do as a result of this test.
130 // The user may not have been logged in when this function was called BUT
131 // because of threading the user might be logged in before you test the result.
132 int CtdlIsUserLoggedIn(char *user_name) {
136 begin_critical_section (S_SESSION_TABLE);
137 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
138 if (!strcasecmp(cptr->user.fullname, user_name)) {
143 end_critical_section(S_SESSION_TABLE);
148 // Check to see if a user is currently logged in.
149 // Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
150 // Take care with what you do as a result of this test.
151 // The user may not have been logged in when this function was called BUT
152 // because of threading the user might be logged in before you test the result.
153 int CtdlIsUserLoggedInByNum (long usernum) {
157 begin_critical_section(S_SESSION_TABLE);
158 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
159 if (cptr->user.usernum == usernum) {
163 end_critical_section(S_SESSION_TABLE);
168 // Return a pointer to the CitContext structure bound to the thread which
169 // called this function. If there's no such binding (for example, if it's
170 // called by the housekeeper thread) then a generic 'master' CC is returned.
172 // This function is used *VERY* frequently and must be kept small.
173 CitContext *MyContext(void) {
174 register CitContext *c;
175 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
179 // Terminate idle sessions. This function pounds through the session table
180 // comparing the current time to each session's time-of-last-command. If an
181 // idle session is found it is terminated, then the search restarts at the
182 // beginning because the pointer to our place in the list becomes invalid.
183 void terminate_idle_sessions(void) {
190 begin_critical_section(S_SESSION_TABLE);
191 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
194 && (CtdlGetConfigLong("c_sleeping") > 0)
195 && (now - (ccptr->lastcmd) > CtdlGetConfigLong("c_sleeping"))
197 if (!ccptr->dont_term) {
198 ccptr->kill_me = KILLME_IDLE;
206 end_critical_section(S_SESSION_TABLE);
208 syslog(LOG_INFO, "context: scheduled %d idle sessions for termination", killed);
210 if (longrunners > 0) {
211 syslog(LOG_INFO, "context: did not terminate %d protected idle sessions", longrunners);
216 // During shutdown, close the sockets of any sessions still connected.
217 void terminate_all_sessions(void) {
221 begin_critical_section(S_SESSION_TABLE);
222 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
223 if (ccptr->client_socket != -1)
225 syslog(LOG_INFO, "context: terminate_all_sessions() is murdering %s CC[%d]", ccptr->curr_user, ccptr->cs_pid);
226 close(ccptr->client_socket);
227 ccptr->client_socket = -1;
231 end_critical_section(S_SESSION_TABLE);
233 syslog(LOG_INFO, "context: flushed %d stuck sessions", killed);
238 // Terminate a session.
239 void RemoveContext(CitContext *con) {
242 syslog(LOG_ERR, "context: RemoveContext() called with NULL, this should not happen");
245 c = con->ServiceName;
249 syslog(LOG_DEBUG, "context: RemoveContext(%s) session %d", c, con->cs_pid);
251 // Run any cleanup routines registered by loadable modules.
252 // Note: We have to "become_session()" because the cleanup functions might make references to "CC" assuming it's the right one.
255 PerformSessionHooks(EVT_STOP); // hooks may free some data structures, close SSL, etc.
256 client_close(); // If the client is still connected, disconnect them immediately.
257 become_session(NULL);
258 syslog(LOG_INFO, "context: session %d (%s) ended.", con->cs_pid, c);
260 /* If using AUTHMODE_LDAP, free the DN */
265 FreeStrBuf(&con->StatusMessage);
266 FreeStrBuf(&con->MigrateBuf);
267 FreeStrBuf(&con->RecvBuf.Buf);
268 if (con->cached_msglist) {
269 free(con->cached_msglist);
272 syslog(LOG_DEBUG, "context: done with RemoveContext()");
276 // Initialize a new context and place it in the list. The session number
277 // used to be the PID (which is why it's called cs_pid), but that was when we
278 // had one process per session. Now we just assign them sequentially, starting
279 // at 1 (don't change it to 0 because masterCC uses 0).
280 CitContext *CreateNewContext(void) {
283 me = (CitContext *) malloc(sizeof(CitContext));
285 syslog(LOG_ERR, "citserver: malloc() failed: %m");
288 memset(me, 0, sizeof(CitContext));
290 // Give the context a name. Hopefully makes it easier to track
291 strcpy (me->user.fullname, "SYS_notauth");
293 me->state = CON_EXECUTING; // Create new context already in CON_EXECUTING so another thread doesn't grab it.
294 me->MigrateBuf = NewStrBuf(); // Generate a unique session number
295 me->RecvBuf.Buf = NewStrBuf();
296 me->lastcmd = time(NULL); // set lastcmd to now to prevent idle timer infanticide
298 begin_critical_section(S_SESSION_TABLE);
299 me->cs_pid = ++next_pid;
301 me->next = ContextList;
303 if (me->next != NULL) {
307 end_critical_section(S_SESSION_TABLE);
312 // Initialize a new context and place it in the list. The session number
313 // used to be the PID (which is why it's called cs_pid), but that was when we
314 // had one process per session. Now we just assign them sequentially, starting
315 // at 1 (don't change it to 0 because masterCC uses 0).
316 CitContext *CloneContext(CitContext *CloneMe) {
319 me = (CitContext *) malloc(sizeof(CitContext));
321 syslog(LOG_ERR, "citserver: malloc() failed: %m");
324 memcpy(me, CloneMe, sizeof(CitContext));
326 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
327 memset(&me->SendBuf, 0, sizeof(IOBuffer));
328 memset(&me->SBuf, 0, sizeof(IOBuffer));
329 me->MigrateBuf = NULL;
330 me->sMigrateBuf = NULL;
331 me->redirect_buffer = NULL;
336 me->download_fp = NULL;
337 me->upload_fp = NULL;
340 me->session_specific_data = NULL;
344 me->cached_msglist = NULL;
345 me->download_fp = NULL;
346 me->upload_fp = NULL;
347 me->client_socket = 0;
349 me->MigrateBuf = NewStrBuf();
350 me->RecvBuf.Buf = NewStrBuf();
352 begin_critical_section(S_SESSION_TABLE);
354 me->cs_pid = ++next_pid;
356 me->next = ContextList;
357 me->lastcmd = time(NULL); // set lastcmd to now to prevent idle timer infanticide
359 if (me->next != NULL) {
364 end_critical_section(S_SESSION_TABLE);
369 // Return an array containing a copy of the context list.
370 // This allows worker threads to perform "for each context" operations without
371 // having to lock and traverse the live list.
372 CitContext *CtdlGetContextArray(int *count) {
374 CitContext *nptr, *cptr;
376 nContexts = num_sessions;
377 nptr = malloc(sizeof(CitContext) * nContexts);
382 begin_critical_section(S_SESSION_TABLE);
383 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
384 memcpy(&nptr[i], cptr, sizeof (CitContext));
386 end_critical_section (S_SESSION_TABLE);
393 // Back-end function for starting a session
394 void begin_session(CitContext *con) {
396 // Initialize some variables specific to our context.
398 con->internal_pgm = 0;
399 con->download_fp = NULL;
400 con->upload_fp = NULL;
401 con->cached_msglist = NULL;
402 con->cached_num_msgs = 0;
403 con->FirstExpressMessage = NULL;
405 time(&con->lastidle);
406 strcpy(con->lastcmdname, " ");
407 strcpy(con->cs_clientname, "(unknown)");
408 strcpy(con->curr_user, NLI);
409 *con->cs_clientinfo = '\0';
410 safestrncpy(con->cs_host, CtdlGetConfigStr("c_fqdn"), sizeof con->cs_host);
411 safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
412 con->cs_UDSclientUID = -1;
413 con->cs_host[sizeof con->cs_host - 1] = 0;
414 if (!CC->is_local_client) {
415 locate_host(con->cs_host, sizeof con->cs_host,
416 con->cs_addr, sizeof con->cs_addr,
427 if (((CtdlGetConfigInt("c_maxsessions") > 0)&&(num_sessions > CtdlGetConfigInt("c_maxsessions"))) || CtdlWantSingleUser()) {
431 syslog(LOG_INFO, "context: session (%s) started from %s (%s) uid=%d",
432 con->ServiceName, con->cs_host, con->cs_addr, con->cs_UDSclientUID
435 /* Run any session startup routines registered by loadable modules */
436 PerformSessionHooks(EVT_START);
440 // This function fills in a context and its user field correctly
441 // Then creates/loads that user
442 void CtdlFillSystemContext(CitContext *context, char *name) {
446 memset(context, 0, sizeof(CitContext));
447 context->internal_pgm = 1;
449 strcpy (sysname, "SYS_");
450 strcat (sysname, name);
451 len = strlen(sysname);
452 memcpy(context->curr_user, sysname, len + 1);
453 context->client_socket = (-1);
454 context->state = CON_SYS;
455 context->ServiceName = name;
457 // internal_create_user has the side effect of loading the user regardless of whether they
458 // already existed or needed to be created
459 internal_create_user(sysname, &(context->user), -1) ;
461 // Check to see if the system user needs upgrading
462 if (context->user.usernum == 0) { // old system user with number 0, upgrade it
463 context->user.usernum = get_new_user_number();
464 syslog(LOG_INFO, "context: upgrading system user \"%s\" from user number 0 to user number %ld", context->user.fullname, context->user.usernum);
465 // add user to the database
466 CtdlPutUser(&(context->user));
467 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
472 // Cleanup any contexts that are left lying around
473 void context_cleanup(void) {
474 CitContext *ptr = NULL;
475 CitContext *rem = NULL;
477 // Clean up the contexts.
478 // There are no threads so no critical_section stuff is needed.
481 // We need to update the ContextList because some modules may want to iterate it
482 // Question is should we NULL it before iterating here or should we just keep updating it as we remove items?
483 // Answer is to NULL it first to prevent modules from doing any actions on the list at all.
486 // Remove the session from the active list
490 syslog(LOG_DEBUG, "context: context_cleanup() purging session %d", ptr->cs_pid);
498 // Purge all sessions which have the 'kill_me' flag set.
499 // This function has code to prevent it from running more than once every
500 // few seconds, because running it after every single unbind would waste a lot
501 // of CPU time and keep the context list locked too much. To force it to run
502 // anyway, set "force" to nonzero.
503 void dead_session_purge(int force) {
504 CitContext *ptr, *ptr2; // general-purpose utility pointer
505 CitContext *rem = NULL; // list of sessions to be destroyed
508 if ( (time(NULL) - last_purge) < 5 ) {
509 return; // Too soon, go away
514 begin_critical_section(S_SESSION_TABLE);
520 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
521 // Remove the session from the active list
523 ptr2->prev->next = ptr2->next;
526 ContextList = ptr2->next;
529 ptr2->next->prev = ptr2->prev;
533 /* And put it on our to-be-destroyed list */
537 //else if (ptr2->kill_me) {
538 //syslog(LOG_DEBUG, "context: session %d is timed out but non-idle", ptr->cs_pid);
541 end_critical_section(S_SESSION_TABLE);
543 // Now that we no longer have the session list locked, we can take
544 // our time and destroy any sessions on the to-be-killed list, which
545 // is allocated privately on this thread's stack.
546 while (rem != NULL) {
547 syslog(LOG_DEBUG, "context: dead_session_purge() purging session %d, reason=%d", rem->cs_pid, rem->kill_me);
556 // masterCC is the context we use when not attached to a session. This function initializes it.
557 void InitializeMasterCC(void) {
558 memset(&masterCC, 0, sizeof(struct CitContext));
559 masterCC.internal_pgm = 1;
564 // Set the "async waiting" flag for a session, if applicable
565 void set_async_waiting(struct CitContext *ccptr) {
566 syslog(LOG_DEBUG, "context: setting async_waiting flag for session %d", ccptr->cs_pid);
567 if (ccptr->is_async) {
568 ccptr->async_waiting++;
569 if (ccptr->state == CON_IDLE) {
570 ccptr->state = CON_READY;
576 CTDL_MODULE_INIT(session) {