2 * Citadel context management stuff.
3 * Here's where we (hopefully) have all the code that manipulates contexts.
5 * Copyright (c) 1987-2011 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"
28 pthread_key_t MyConKey; /* TSD key for MyContext() */
32 CitContext *ContextList = NULL;
34 time_t last_purge = 0; /* Last dead session purge */
35 int num_sessions = 0; /* Current number of sessions */
38 /* Flag for single user mode */
39 static int want_single_user = 0;
41 /* Try to go single user */
43 int CtdlTrySingleUser(void)
47 begin_critical_section(S_SINGLE_USER);
55 end_critical_section(S_SINGLE_USER);
59 void CtdlEndSingleUser(void)
61 begin_critical_section(S_SINGLE_USER);
63 end_critical_section(S_SINGLE_USER);
67 int CtdlWantSingleUser(void)
69 return want_single_user;
72 int CtdlIsSingleUser(void)
76 /* check for only one context here */
77 if (num_sessions == 1)
88 * Locate a context by its session number and terminate it if the user is able.
89 * User can NOT terminate their current session.
90 * User CAN terminate any other session that has them logged in.
91 * Aide CAN terminate any session except the current one.
93 int CtdlTerminateOtherSession (int session_num)
95 struct CitContext *CCC = CC;
100 if (session_num == CCC->cs_pid) return TERM_NOTALLOWED;
102 aide = ( (CCC->user.axlevel >= AxAideU) || (CCC->internal_pgm) ) ;
104 CONM_syslog(LOG_DEBUG, "Locating session to kill\n");
105 begin_critical_section(S_SESSION_TABLE);
106 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
107 if (session_num == ccptr->cs_pid) {
109 if ((ccptr->user.usernum == CCC->user.usernum) || aide) {
116 if (((ret & TERM_FOUND) != 0) && ((ret & TERM_ALLOWED) != 0))
118 if (ccptr->IO != NULL) {
119 AsyncIO *IO = ccptr->IO;
120 end_critical_section(S_SESSION_TABLE);
121 KillAsyncIOContext(IO);
125 if (ccptr->user.usernum == CCC->user.usernum)
126 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
128 ccptr->kill_me = KILLME_IDLE;
129 end_critical_section(S_SESSION_TABLE);
133 end_critical_section(S_SESSION_TABLE);
141 * Check to see if the user who we just sent mail to is logged in. If yes,
142 * bump the 'new mail' counter for their session. That enables them to
143 * receive a new mail notification without having to hit the database.
145 void BumpNewMailCounter(long which_user)
147 CtdlBumpNewMailCounter(which_user);
150 void CtdlBumpNewMailCounter(long which_user)
154 begin_critical_section(S_SESSION_TABLE);
156 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
157 if (ptr->user.usernum == which_user) {
162 end_critical_section(S_SESSION_TABLE);
167 * Check to see if a user is currently logged in
168 * Take care with what you do as a result of this test.
169 * The user may not have been logged in when this function was called BUT
170 * because of threading the user might be logged in before you test the result.
172 int CtdlIsUserLoggedIn (char *user_name)
177 begin_critical_section (S_SESSION_TABLE);
178 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
179 if (!strcasecmp(cptr->user.fullname, user_name)) {
184 end_critical_section(S_SESSION_TABLE);
191 * Check to see if a user is currently logged in.
192 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
193 * Take care with what you do as a result of this test.
194 * The user may not have been logged in when this function was called BUT
195 * because of threading the user might be logged in before you test the result.
197 int CtdlIsUserLoggedInByNum (long usernum)
202 begin_critical_section(S_SESSION_TABLE);
203 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
204 if (cptr->user.usernum == usernum) {
208 end_critical_section(S_SESSION_TABLE);
215 * Return a pointer to the CitContext structure bound to the thread which
216 * called this function. If there's no such binding (for example, if it's
217 * called by the housekeeper thread) then a generic 'master' CC is returned.
219 * This function is used *VERY* frequently and must be kept small.
221 CitContext *MyContext(void) {
222 register CitContext *c;
223 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
230 * Terminate idle sessions. This function pounds through the session table
231 * comparing the current time to each session's time-of-last-command. If an
232 * idle session is found it is terminated, then the search restarts at the
233 * beginning because the pointer to our place in the list becomes invalid.
235 void terminate_idle_sessions(void)
243 begin_critical_section(S_SESSION_TABLE);
244 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
247 && (config.c_sleeping > 0)
248 && (now - (ccptr->lastcmd) > config.c_sleeping)
250 if (!ccptr->dont_term) {
251 ccptr->kill_me = KILLME_IDLE;
259 end_critical_section(S_SESSION_TABLE);
261 CON_syslog(LOG_INFO, "Scheduled %d idle sessions for termination\n", killed);
263 CON_syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
268 * During shutdown, close the sockets of any sessions still connected.
270 void terminate_all_sessions(void)
275 begin_critical_section(S_SESSION_TABLE);
276 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
277 if (ccptr->client_socket != -1)
279 CON_syslog(LOG_INFO, "terminate_all_sessions() is murdering %s", ccptr->curr_user);
280 close(ccptr->client_socket);
281 ccptr->client_socket = -1;
285 end_critical_section(S_SESSION_TABLE);
287 CON_syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
294 * Terminate a session.
296 void RemoveContext (CitContext *con)
300 CONM_syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
303 c = con->ServiceName;
307 CON_syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
310 /* Run any cleanup routines registered by loadable modules.
311 * Note: We have to "become_session()" because the cleanup functions
312 * might make references to "CC" assuming it's the right one.
316 PerformSessionHooks(EVT_STOP);
317 client_close(); /* If the client is still connected, blow 'em away. */
318 become_session(NULL);
320 CON_syslog(LOG_NOTICE, "[%3d]SRV[%s] Session ended.", con->cs_pid, c);
323 * If the client is still connected, blow 'em away.
324 * if the socket is 0 or -1, its already gone or was never there.
326 if (con->client_socket > 0)
328 CON_syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
329 close(con->client_socket);
332 /* If using AUTHMODE_LDAP, free the DN */
337 FreeStrBuf(&con->StatusMessage);
338 FreeStrBuf(&con->MigrateBuf);
339 FreeStrBuf(&con->RecvBuf.Buf);
340 if (con->cached_msglist) {
341 free(con->cached_msglist);
344 CONM_syslog(LOG_DEBUG, "Done with RemoveContext()");
350 * Initialize a new context and place it in the list. The session number
351 * used to be the PID (which is why it's called cs_pid), but that was when we
352 * had one process per session. Now we just assign them sequentially, starting
353 * at 1 (don't change it to 0 because masterCC uses 0).
355 CitContext *CreateNewContext(void) {
358 me = (CitContext *) malloc(sizeof(CitContext));
360 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
363 memset(me, 0, sizeof(CitContext));
365 /* Give the context a name. Hopefully makes it easier to track */
366 strcpy (me->user.fullname, "SYS_notauth");
368 /* The new context will be created already in the CON_EXECUTING state
369 * in order to prevent another thread from grabbing it while it's
372 me->state = CON_EXECUTING;
374 * Generate a unique session number and insert this context into
377 me->MigrateBuf = NewStrBuf();
379 me->RecvBuf.Buf = NewStrBuf();
381 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. */
384 begin_critical_section(S_SESSION_TABLE);
385 me->cs_pid = ++next_pid;
387 me->next = ContextList;
389 if (me->next != NULL) {
393 end_critical_section(S_SESSION_TABLE);
399 * Initialize a new context and place it in the list. The session number
400 * used to be the PID (which is why it's called cs_pid), but that was when we
401 * had one process per session. Now we just assign them sequentially, starting
402 * at 1 (don't change it to 0 because masterCC uses 0).
404 CitContext *CloneContext(CitContext *CloneMe) {
407 me = (CitContext *) malloc(sizeof(CitContext));
409 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
412 memcpy(me, CloneMe, sizeof(CitContext));
414 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
415 memset(&me->SendBuf, 0, sizeof(IOBuffer));
416 memset(&me->SBuf, 0, sizeof(IOBuffer));
417 me->MigrateBuf = NULL;
418 me->sMigrateBuf = NULL;
419 me->redirect_buffer = NULL;
424 me->download_fp = NULL;
425 me->upload_fp = NULL;
426 /// TODO: what about the room/user?
428 me->openid_data = NULL;
430 me->session_specific_data = NULL;
434 me->cached_msglist = NULL;
435 me->download_fp = NULL;
436 me->upload_fp = NULL;
437 me->client_socket = 0;
439 me->MigrateBuf = NewStrBuf();
440 me->RecvBuf.Buf = NewStrBuf();
442 begin_critical_section(S_SESSION_TABLE);
444 me->cs_pid = ++next_pid;
446 me->next = ContextList;
447 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
449 if (me->next != NULL) {
454 end_critical_section(S_SESSION_TABLE);
460 * Return an array containing a copy of the context list.
461 * This allows worker threads to perform "for each context" operations without
462 * having to lock and traverse the live list.
464 CitContext *CtdlGetContextArray(int *count)
467 CitContext *nptr, *cptr;
469 nContexts = num_sessions;
470 nptr = malloc(sizeof(CitContext) * nContexts);
475 begin_critical_section(S_SESSION_TABLE);
476 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
477 memcpy(&nptr[i], cptr, sizeof (CitContext));
479 end_critical_section (S_SESSION_TABLE);
488 * Back-end function for starting a session
490 void begin_session(CitContext *con)
493 * Initialize some variables specific to our context.
496 con->internal_pgm = 0;
497 con->download_fp = NULL;
498 con->upload_fp = NULL;
499 con->cached_msglist = NULL;
500 con->cached_num_msgs = 0;
501 con->FirstExpressMessage = NULL;
503 time(&con->lastidle);
504 strcpy(con->lastcmdname, " ");
505 strcpy(con->cs_clientname, "(unknown)");
506 strcpy(con->curr_user, NLI);
507 *con->net_node = '\0';
508 *con->fake_username = '\0';
509 *con->fake_hostname = '\0';
510 *con->fake_roomname = '\0';
511 *con->cs_clientinfo = '\0';
512 safestrncpy(con->cs_host, config.c_fqdn, sizeof con->cs_host);
513 safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
514 con->cs_UDSclientUID = -1;
515 con->cs_host[sizeof con->cs_host - 1] = 0;
516 if (!CC->is_local_socket) {
517 locate_host(con->cs_host, sizeof con->cs_host,
518 con->cs_addr, sizeof con->cs_addr,
525 #ifdef HAVE_STRUCT_UCRED
527 /* as http://www.wsinnovations.com/softeng/articles/uds.html told us... */
528 struct ucred credentials;
529 socklen_t ucred_length = sizeof(struct ucred);
531 /*fill in the user data structure */
532 if(getsockopt(con->client_socket, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length)) {
533 syslog(LOG_NOTICE, "could obtain credentials from unix domain socket");
537 /* the process ID of the process on the other side of the socket */
538 /* credentials.pid; */
540 /* the effective UID of the process on the other side of the socket */
541 con->cs_UDSclientUID = credentials.uid;
543 /* the effective primary GID of the process on the other side of the socket */
544 /* credentials.gid; */
546 /* To get supplemental groups, we will have to look them up in our account
547 database, after a reverse lookup on the UID to get the account name.
548 We can take this opportunity to check to see if this is a legit account.
550 snprintf(con->cs_clientinfo, sizeof(con->cs_clientinfo),
551 "PID: "F_PID_T"; UID: "F_UID_T"; GID: "F_XPID_T" ",
560 con->upload_type = UPL_FILE;
564 if (((config.c_maxsessions > 0)&&(num_sessions > config.c_maxsessions)) || CtdlWantSingleUser()) {
568 if (!CC->is_local_socket) {
569 syslog(LOG_NOTICE, "Session (%s) started from %s (%s).\n", con->ServiceName, con->cs_host, con->cs_addr);
572 syslog(LOG_NOTICE, "Session (%s) started via local socket UID:%d.\n", con->ServiceName, con->cs_UDSclientUID);
575 /* Run any session startup routines registered by loadable modules */
576 PerformSessionHooks(EVT_START);
581 * This function fills in a context and its user field correctly
582 * Then creates/loads that user
584 void CtdlFillSystemContext(CitContext *context, char *name)
589 memset(context, 0, sizeof(CitContext));
590 context->internal_pgm = 1;
592 strcpy (sysname, "SYS_");
593 strcat (sysname, name);
594 len = cutuserkey(sysname);
595 memcpy(context->curr_user, sysname, len + 1);
596 context->client_socket = (-1);
597 context->state = CON_SYS;
598 context->ServiceName = name;
600 /* internal_create_user has the side effect of loading the user regardless of wether they
601 * already existed or needed to be created
603 internal_create_user (sysname, len, &(context->user), -1) ;
605 /* Check to see if the system user needs upgrading */
606 if (context->user.usernum == 0)
607 { /* old system user with number 0, upgrade it */
608 context->user.usernum = get_new_user_number();
609 CON_syslog(LOG_INFO, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
610 /* add user to the database */
611 CtdlPutUser(&(context->user));
612 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
618 * Cleanup any contexts that are left lying around
620 void context_cleanup(void)
622 CitContext *ptr = NULL;
623 CitContext *rem = NULL;
626 * Clean up the contexts.
627 * There are no threads so no critical_section stuff is needed.
631 /* We need to update the ContextList because some modules may want to itterate it
632 * Question is should we NULL it before iterating here or should we just keep updating it
633 * as we remove items?
635 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
639 /* Remove the session from the active list */
643 CON_syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
653 * Purge all sessions which have the 'kill_me' flag set.
654 * This function has code to prevent it from running more than once every
655 * few seconds, because running it after every single unbind would waste a lot
656 * of CPU time and keep the context list locked too much. To force it to run
657 * anyway, set "force" to nonzero.
659 void dead_session_purge(int force) {
660 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
661 CitContext *rem = NULL; /* list of sessions to be destroyed */
664 if ( (time(NULL) - last_purge) < 5 ) {
665 return; /* Too soon, go away */
670 if (try_critical_section(S_SESSION_TABLE))
678 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
679 /* Remove the session from the active list */
681 ptr2->prev->next = ptr2->next;
684 ContextList = ptr2->next;
687 ptr2->next->prev = ptr2->prev;
691 /* And put it on our to-be-destroyed list */
696 end_critical_section(S_SESSION_TABLE);
698 /* Now that we no longer have the session list locked, we can take
699 * our time and destroy any sessions on the to-be-killed list, which
700 * is allocated privately on this thread's stack.
702 while (rem != NULL) {
703 CON_syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
716 * masterCC is the context we use when not attached to a session. This
717 * function initializes it.
719 void InitializeMasterCC(void) {
720 memset(&masterCC, 0, sizeof(struct CitContext));
721 masterCC.internal_pgm = 1;
730 * Set the "async waiting" flag for a session, if applicable
732 void set_async_waiting(struct CitContext *ccptr)
734 CON_syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
735 if (ccptr->is_async) {
736 ccptr->async_waiting++;
737 if (ccptr->state == CON_IDLE) {
738 ccptr->state = CON_READY;
744 void DebugSessionEnable(const int n)
748 CTDL_MODULE_INIT(session)
751 CtdlRegisterDebugFlagHook(HKEY("session"), DebugSessionEnable, &DebugSession);