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"
27 pthread_key_t MyConKey; /* TSD key for MyContext() */
29 CitContext *ContextList = NULL;
30 time_t last_purge = 0; /* Last dead session purge */
31 int num_sessions = 0; /* Current number of sessions */
34 /* Flag for single user mode */
35 static int want_single_user = 0;
37 /* Try to go single user */
39 int CtdlTrySingleUser(void)
43 begin_critical_section(S_SINGLE_USER);
51 end_critical_section(S_SINGLE_USER);
55 void CtdlEndSingleUser(void)
57 begin_critical_section(S_SINGLE_USER);
59 end_critical_section(S_SINGLE_USER);
63 int CtdlWantSingleUser(void)
65 return want_single_user;
68 int CtdlIsSingleUser(void)
72 /* check for only one context here */
73 if (num_sessions == 1)
84 * Locate a context by its session number and terminate it if the user is able.
85 * User can NOT terminate their current session.
86 * User CAN terminate any other session that has them logged in.
87 * Aide CAN terminate any session except the current one.
89 int CtdlTerminateOtherSession (int session_num)
91 struct CitContext *CCC = CC;
96 if (session_num == CCC->cs_pid) return TERM_NOTALLOWED;
98 aide = ( (CCC->user.axlevel >= AxAideU) || (CCC->internal_pgm) ) ;
100 syslog(LOG_DEBUG, "context: locating session to kill");
101 begin_critical_section(S_SESSION_TABLE);
102 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
103 if (session_num == ccptr->cs_pid) {
105 if ((ccptr->user.usernum == CCC->user.usernum) || aide) {
112 if (((ret & TERM_FOUND) != 0) && ((ret & TERM_ALLOWED) != 0))
114 if (ccptr->user.usernum == CCC->user.usernum)
115 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
117 ccptr->kill_me = KILLME_IDLE;
118 end_critical_section(S_SESSION_TABLE);
121 end_critical_section(S_SESSION_TABLE);
129 * Check to see if the user who we just sent mail to is logged in. If yes,
130 * bump the 'new mail' counter for their session. That enables them to
131 * receive a new mail notification without having to hit the database.
133 void BumpNewMailCounter(long which_user)
135 CtdlBumpNewMailCounter(which_user);
138 void CtdlBumpNewMailCounter(long which_user)
142 begin_critical_section(S_SESSION_TABLE);
144 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
145 if (ptr->user.usernum == which_user) {
150 end_critical_section(S_SESSION_TABLE);
155 * Check to see if a user is currently logged in
156 * Take care with what you do as a result of this test.
157 * The user may not have been logged in when this function was called BUT
158 * because of threading the user might be logged in before you test the result.
160 int CtdlIsUserLoggedIn (char *user_name)
165 begin_critical_section (S_SESSION_TABLE);
166 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
167 if (!strcasecmp(cptr->user.fullname, user_name)) {
172 end_critical_section(S_SESSION_TABLE);
179 * Check to see if a user is currently logged in.
180 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
181 * Take care with what you do as a result of this test.
182 * The user may not have been logged in when this function was called BUT
183 * because of threading the user might be logged in before you test the result.
185 int CtdlIsUserLoggedInByNum (long usernum)
190 begin_critical_section(S_SESSION_TABLE);
191 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
192 if (cptr->user.usernum == usernum) {
196 end_critical_section(S_SESSION_TABLE);
203 * Return a pointer to the CitContext structure bound to the thread which
204 * called this function. If there's no such binding (for example, if it's
205 * called by the housekeeper thread) then a generic 'master' CC is returned.
207 * This function is used *VERY* frequently and must be kept small.
209 CitContext *MyContext(void) {
210 register CitContext *c;
211 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
218 * Terminate idle sessions. This function pounds through the session table
219 * comparing the current time to each session's time-of-last-command. If an
220 * idle session is found it is terminated, then the search restarts at the
221 * beginning because the pointer to our place in the list becomes invalid.
223 void terminate_idle_sessions(void)
231 begin_critical_section(S_SESSION_TABLE);
232 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
235 && (CtdlGetConfigLong("c_sleeping") > 0)
236 && (now - (ccptr->lastcmd) > CtdlGetConfigLong("c_sleeping"))
238 if (!ccptr->dont_term) {
239 ccptr->kill_me = KILLME_IDLE;
247 end_critical_section(S_SESSION_TABLE);
249 syslog(LOG_INFO, "context: scheduled %d idle sessions for termination", killed);
251 if (longrunners > 0) {
252 syslog(LOG_INFO, "context: did not terminate %d protected idle sessions", longrunners);
258 * During shutdown, close the sockets of any sessions still connected.
260 void terminate_all_sessions(void)
265 begin_critical_section(S_SESSION_TABLE);
266 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
267 if (ccptr->client_socket != -1)
269 syslog(LOG_INFO, "context: terminate_all_sessions() is murdering %s CC[%d]", ccptr->curr_user, ccptr->cs_pid);
270 close(ccptr->client_socket);
271 ccptr->client_socket = -1;
275 end_critical_section(S_SESSION_TABLE);
277 syslog(LOG_INFO, "context: flushed %d stuck sessions", killed);
284 * Terminate a session.
286 void RemoveContext (CitContext *con)
290 syslog(LOG_ERR, "context: RemoveContext() called with NULL, this should not happen");
293 c = con->ServiceName;
297 syslog(LOG_DEBUG, "context: RemoveContext(%s) session %d", c, con->cs_pid);
300 /* Run any cleanup routines registered by loadable modules.
301 * Note: We have to "become_session()" because the cleanup functions
302 * might make references to "CC" assuming it's the right one.
306 PerformSessionHooks(EVT_STOP);
307 client_close(); /* If the client is still connected, blow 'em away. */
308 become_session(NULL);
310 syslog(LOG_INFO, "context: [%3d]SRV[%s] Session ended.", con->cs_pid, c);
313 * If the client is still connected, blow 'em away.
314 * if the socket is 0 or -1, its already gone or was never there.
316 if (con->client_socket > 0)
318 syslog(LOG_INFO, "context: closing socket %d", con->client_socket);
319 close(con->client_socket);
322 /* If using AUTHMODE_LDAP, free the DN */
327 FreeStrBuf(&con->StatusMessage);
328 FreeStrBuf(&con->MigrateBuf);
329 FreeStrBuf(&con->RecvBuf.Buf);
330 if (con->cached_msglist) {
331 free(con->cached_msglist);
334 syslog(LOG_DEBUG, "context: done with RemoveContext()");
340 * Initialize a new context and place it in the list. The session number
341 * used to be the PID (which is why it's called cs_pid), but that was when we
342 * had one process per session. Now we just assign them sequentially, starting
343 * at 1 (don't change it to 0 because masterCC uses 0).
345 CitContext *CreateNewContext(void) {
348 me = (CitContext *) malloc(sizeof(CitContext));
350 syslog(LOG_ERR, "citserver: malloc() failed: %m");
353 memset(me, 0, sizeof(CitContext));
355 /* Give the context a name. Hopefully makes it easier to track */
356 strcpy (me->user.fullname, "SYS_notauth");
358 /* The new context will be created already in the CON_EXECUTING state
359 * in order to prevent another thread from grabbing it while it's
362 me->state = CON_EXECUTING;
364 * Generate a unique session number and insert this context into
367 me->MigrateBuf = NewStrBuf();
369 me->RecvBuf.Buf = NewStrBuf();
371 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. */
374 begin_critical_section(S_SESSION_TABLE);
375 me->cs_pid = ++next_pid;
377 me->next = ContextList;
379 if (me->next != NULL) {
383 end_critical_section(S_SESSION_TABLE);
389 * Initialize a new context and place it in the list. The session number
390 * used to be the PID (which is why it's called cs_pid), but that was when we
391 * had one process per session. Now we just assign them sequentially, starting
392 * at 1 (don't change it to 0 because masterCC uses 0).
394 CitContext *CloneContext(CitContext *CloneMe) {
397 me = (CitContext *) malloc(sizeof(CitContext));
399 syslog(LOG_ERR, "citserver: malloc() failed: %m");
402 memcpy(me, CloneMe, sizeof(CitContext));
404 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
405 memset(&me->SendBuf, 0, sizeof(IOBuffer));
406 memset(&me->SBuf, 0, sizeof(IOBuffer));
407 me->MigrateBuf = NULL;
408 me->sMigrateBuf = NULL;
409 me->redirect_buffer = NULL;
414 me->download_fp = NULL;
415 me->upload_fp = NULL;
416 /// TODO: what about the room/user?
418 me->openid_data = NULL;
420 me->session_specific_data = NULL;
424 me->cached_msglist = NULL;
425 me->download_fp = NULL;
426 me->upload_fp = NULL;
427 me->client_socket = 0;
429 me->MigrateBuf = NewStrBuf();
430 me->RecvBuf.Buf = NewStrBuf();
432 begin_critical_section(S_SESSION_TABLE);
434 me->cs_pid = ++next_pid;
436 me->next = ContextList;
437 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
439 if (me->next != NULL) {
444 end_critical_section(S_SESSION_TABLE);
450 * Return an array containing a copy of the context list.
451 * This allows worker threads to perform "for each context" operations without
452 * having to lock and traverse the live list.
454 CitContext *CtdlGetContextArray(int *count)
457 CitContext *nptr, *cptr;
459 nContexts = num_sessions;
460 nptr = malloc(sizeof(CitContext) * nContexts);
465 begin_critical_section(S_SESSION_TABLE);
466 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
467 memcpy(&nptr[i], cptr, sizeof (CitContext));
469 end_critical_section (S_SESSION_TABLE);
478 * Back-end function for starting a session
480 void begin_session(CitContext *con)
483 * Initialize some variables specific to our context.
486 con->internal_pgm = 0;
487 con->download_fp = NULL;
488 con->upload_fp = NULL;
489 con->cached_msglist = NULL;
490 con->cached_num_msgs = 0;
491 con->FirstExpressMessage = NULL;
493 time(&con->lastidle);
494 strcpy(con->lastcmdname, " ");
495 strcpy(con->cs_clientname, "(unknown)");
496 strcpy(con->curr_user, NLI);
497 *con->net_node = '\0';
498 *con->fake_username = '\0';
499 *con->fake_hostname = '\0';
500 *con->fake_roomname = '\0';
501 *con->cs_clientinfo = '\0';
502 safestrncpy(con->cs_host, CtdlGetConfigStr("c_fqdn"), sizeof con->cs_host);
503 safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
504 con->cs_UDSclientUID = -1;
505 con->cs_host[sizeof con->cs_host - 1] = 0;
506 if (!CC->is_local_socket) {
507 locate_host(con->cs_host, sizeof con->cs_host,
508 con->cs_addr, sizeof con->cs_addr,
515 #ifdef HAVE_STRUCT_UCRED
517 /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
518 struct ucred credentials;
519 socklen_t ucred_length = sizeof(struct ucred);
521 /*fill in the user data structure */
522 if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
523 syslog(LOG_ERR, "context: could obtain credentials from unix domain socket");
527 /* the process ID of the process on the other side of the socket */
528 /* credentials.pid; */
530 /* the effective UID of the process on the other side of the socket */
531 con->cs_UDSclientUID = credentials.uid;
533 /* the effective primary GID of the process on the other side of the socket */
534 /* credentials.gid; */
536 /* To get supplemental groups, we will have to look them up in our account
537 database, after a reverse lookup on the UID to get the account name.
538 We can take this opportunity to check to see if this is a legit account.
540 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
541 "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ",
550 con->upload_type = UPL_FILE;
554 if (((CtdlGetConfigInt("c_maxsessions") > 0)&&(num_sessions > CtdlGetConfigInt("c_maxsessions"))) || CtdlWantSingleUser()) {
558 if (!CC->is_local_socket) {
559 syslog(LOG_INFO, "context: session (%s) started from %s (%s)", con->ServiceName, con->cs_host, con->cs_addr);
562 syslog(LOG_INFO, "context: session (%s) started via local socket with uid=%d", con->ServiceName, con->cs_UDSclientUID);
565 /* Run any session startup routines registered by loadable modules */
566 PerformSessionHooks(EVT_START);
571 * This function fills in a context and its user field correctly
572 * Then creates/loads that user
574 void CtdlFillSystemContext(CitContext *context, char *name)
579 memset(context, 0, sizeof(CitContext));
580 context->internal_pgm = 1;
582 strcpy (sysname, "SYS_");
583 strcat (sysname, name);
584 len = cutuserkey(sysname);
585 memcpy(context->curr_user, sysname, len + 1);
586 context->client_socket = (-1);
587 context->state = CON_SYS;
588 context->ServiceName = name;
590 /* internal_create_user has the side effect of loading the user regardless of whether they
591 * already existed or needed to be created
593 internal_create_user(sysname, &(context->user), -1) ;
595 /* Check to see if the system user needs upgrading */
596 if (context->user.usernum == 0)
597 { /* old system user with number 0, upgrade it */
598 context->user.usernum = get_new_user_number();
599 syslog(LOG_INFO, "context: upgrading system user \"%s\" from user number 0 to user number %ld", context->user.fullname, context->user.usernum);
600 /* add user to the database */
601 CtdlPutUser(&(context->user));
602 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
608 * Cleanup any contexts that are left lying around
610 void context_cleanup(void)
612 CitContext *ptr = NULL;
613 CitContext *rem = NULL;
616 * Clean up the contexts.
617 * There are no threads so no critical_section stuff is needed.
621 /* We need to update the ContextList because some modules may want to itterate it
622 * Question is should we NULL it before iterating here or should we just keep updating it
623 * as we remove items?
625 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
629 /* Remove the session from the active list */
633 syslog(LOG_DEBUG, "context: context_cleanup() purging session %d", ptr->cs_pid);
643 * Purge all sessions which have the 'kill_me' flag set.
644 * This function has code to prevent it from running more than once every
645 * few seconds, because running it after every single unbind would waste a lot
646 * of CPU time and keep the context list locked too much. To force it to run
647 * anyway, set "force" to nonzero.
649 void dead_session_purge(int force) {
650 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
651 CitContext *rem = NULL; /* list of sessions to be destroyed */
654 if ( (time(NULL) - last_purge) < 5 ) {
655 return; /* Too soon, go away */
660 if (try_critical_section(S_SESSION_TABLE))
668 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
669 /* Remove the session from the active list */
671 ptr2->prev->next = ptr2->next;
674 ContextList = ptr2->next;
677 ptr2->next->prev = ptr2->prev;
681 /* And put it on our to-be-destroyed list */
686 end_critical_section(S_SESSION_TABLE);
688 /* Now that we no longer have the session list locked, we can take
689 * our time and destroy any sessions on the to-be-killed list, which
690 * is allocated privately on this thread's stack.
692 while (rem != NULL) {
693 syslog(LOG_DEBUG, "context: dead_session_purge() purging session %d, reason=%d", rem->cs_pid, rem->kill_me);
706 * masterCC is the context we use when not attached to a session. This
707 * function initializes it.
709 void InitializeMasterCC(void) {
710 memset(&masterCC, 0, sizeof(struct CitContext));
711 masterCC.internal_pgm = 1;
720 * Set the "async waiting" flag for a session, if applicable
722 void set_async_waiting(struct CitContext *ccptr)
724 syslog(LOG_DEBUG, "context: setting async_waiting flag for session %d", ccptr->cs_pid);
725 if (ccptr->is_async) {
726 ccptr->async_waiting++;
727 if (ccptr->state == CON_IDLE) {
728 ccptr->state = CON_READY;
734 CTDL_MODULE_INIT(session)