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.
23 #include <sys/types.h>
26 #include <sys/socket.h>
28 #include <sys/syslog.h>
30 #include <sys/syscall.h>
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
38 # include <sys/time.h>
45 #include <sys/resource.h>
46 #include <netinet/in.h>
47 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
56 #include <libcitadel.h>
59 #include "sysdep_decls.h"
60 #include "citserver.h"
64 #include "housekeeping.h"
65 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
68 #ifdef HAVE_SYS_SELECT_H
69 #include <sys/select.h>
72 #include "ctdl_module.h"
79 pthread_key_t MyConKey; /* TSD key for MyContext() */
83 CitContext *ContextList = NULL;
85 time_t last_purge = 0; /* Last dead session purge */
86 int num_sessions = 0; /* Current number of sessions */
89 /* Flag for single user mode */
90 static int want_single_user = 0;
92 /* Try to go single user */
94 int CtdlTrySingleUser(void)
98 begin_critical_section(S_SINGLE_USER);
104 want_single_user = 1;
106 end_critical_section(S_SINGLE_USER);
110 void CtdlEndSingleUser(void)
112 begin_critical_section(S_SINGLE_USER);
113 want_single_user = 0;
114 end_critical_section(S_SINGLE_USER);
118 int CtdlWantSingleUser(void)
120 return want_single_user;
123 int CtdlIsSingleUser(void)
125 if (want_single_user)
127 /* check for only one context here */
128 if (num_sessions == 1)
139 * Locate a context by its session number and terminate it if the user is able.
140 * User can NOT terminate their current session.
141 * User CAN terminate any other session that has them logged in.
142 * Aide CAN terminate any session except the current one.
144 int CtdlTerminateOtherSession (int session_num)
146 struct CitContext *CCC = CC;
151 if (session_num == CCC->cs_pid) return TERM_NOTALLOWED;
153 aide = ( (CCC->user.axlevel >= AxAideU) || (CCC->internal_pgm) ) ;
155 CONM_syslog(LOG_DEBUG, "Locating session to kill\n");
156 begin_critical_section(S_SESSION_TABLE);
157 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
158 if (session_num == ccptr->cs_pid) {
160 if ((ccptr->user.usernum == CCC->user.usernum) || aide) {
167 if (((ret & TERM_FOUND) != 0) && ((ret & TERM_ALLOWED) != 0))
169 if (ccptr->IO != NULL) {
170 AsyncIO *IO = ccptr->IO;
171 end_critical_section(S_SESSION_TABLE);
172 KillAsyncIOContext(IO);
176 if (ccptr->user.usernum == CCC->user.usernum)
177 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
179 ccptr->kill_me = KILLME_IDLE;
180 end_critical_section(S_SESSION_TABLE);
184 end_critical_section(S_SESSION_TABLE);
192 * Check to see if the user who we just sent mail to is logged in. If yes,
193 * bump the 'new mail' counter for their session. That enables them to
194 * receive a new mail notification without having to hit the database.
196 void BumpNewMailCounter(long which_user)
198 CtdlBumpNewMailCounter(which_user);
201 void CtdlBumpNewMailCounter(long which_user)
205 begin_critical_section(S_SESSION_TABLE);
207 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
208 if (ptr->user.usernum == which_user) {
213 end_critical_section(S_SESSION_TABLE);
218 * Check to see if a user is currently logged in
219 * Take care with what you do as a result of this test.
220 * The user may not have been logged in when this function was called BUT
221 * because of threading the user might be logged in before you test the result.
223 int CtdlIsUserLoggedIn (char *user_name)
228 begin_critical_section (S_SESSION_TABLE);
229 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
230 if (!strcasecmp(cptr->user.fullname, user_name)) {
235 end_critical_section(S_SESSION_TABLE);
242 * Check to see if a user is currently logged in.
243 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
244 * Take care with what you do as a result of this test.
245 * The user may not have been logged in when this function was called BUT
246 * because of threading the user might be logged in before you test the result.
248 int CtdlIsUserLoggedInByNum (long usernum)
253 begin_critical_section(S_SESSION_TABLE);
254 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
255 if (cptr->user.usernum == usernum) {
259 end_critical_section(S_SESSION_TABLE);
266 * Return a pointer to the CitContext structure bound to the thread which
267 * called this function. If there's no such binding (for example, if it's
268 * called by the housekeeper thread) then a generic 'master' CC is returned.
270 * This function is used *VERY* frequently and must be kept small.
272 CitContext *MyContext(void) {
273 register CitContext *c;
274 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
281 * Terminate idle sessions. This function pounds through the session table
282 * comparing the current time to each session's time-of-last-command. If an
283 * idle session is found it is terminated, then the search restarts at the
284 * beginning because the pointer to our place in the list becomes invalid.
286 void terminate_idle_sessions(void)
294 begin_critical_section(S_SESSION_TABLE);
295 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
298 && (config.c_sleeping > 0)
299 && (now - (ccptr->lastcmd) > config.c_sleeping)
301 if (!ccptr->dont_term) {
302 ccptr->kill_me = KILLME_IDLE;
310 end_critical_section(S_SESSION_TABLE);
312 CON_syslog(LOG_INFO, "Scheduled %d idle sessions for termination\n", killed);
314 CON_syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
319 * During shutdown, close the sockets of any sessions still connected.
321 void terminate_all_sessions(void)
326 begin_critical_section(S_SESSION_TABLE);
327 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
328 if (ccptr->client_socket != -1)
330 CON_syslog(LOG_INFO, "terminate_all_sessions() is murdering %s", ccptr->curr_user);
331 close(ccptr->client_socket);
332 ccptr->client_socket = -1;
336 end_critical_section(S_SESSION_TABLE);
338 CON_syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
345 * Terminate a session.
347 void RemoveContext (CitContext *con)
351 CONM_syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
354 c = con->ServiceName;
358 CON_syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
361 /* Run any cleanup routines registered by loadable modules.
362 * Note: We have to "become_session()" because the cleanup functions
363 * might make references to "CC" assuming it's the right one.
367 PerformSessionHooks(EVT_STOP);
368 client_close(); /* If the client is still connected, blow 'em away. */
369 become_session(NULL);
371 CON_syslog(LOG_NOTICE, "[%3d]SRV[%s] Session ended.", con->cs_pid, c);
374 * If the client is still connected, blow 'em away.
375 * if the socket is 0 or -1, its already gone or was never there.
377 if (con->client_socket > 0)
379 CON_syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
380 close(con->client_socket);
383 /* If using AUTHMODE_LDAP, free the DN */
388 FreeStrBuf(&con->StatusMessage);
389 FreeStrBuf(&con->MigrateBuf);
390 FreeStrBuf(&con->RecvBuf.Buf);
391 if (con->cached_msglist) {
392 free(con->cached_msglist);
395 CONM_syslog(LOG_DEBUG, "Done with RemoveContext()");
401 * Initialize a new context and place it in the list. The session number
402 * used to be the PID (which is why it's called cs_pid), but that was when we
403 * had one process per session. Now we just assign them sequentially, starting
404 * at 1 (don't change it to 0 because masterCC uses 0).
406 CitContext *CreateNewContext(void) {
409 me = (CitContext *) malloc(sizeof(CitContext));
411 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
414 memset(me, 0, sizeof(CitContext));
416 /* Give the context a name. Hopefully makes it easier to track */
417 strcpy (me->user.fullname, "SYS_notauth");
419 /* The new context will be created already in the CON_EXECUTING state
420 * in order to prevent another thread from grabbing it while it's
423 me->state = CON_EXECUTING;
425 * Generate a unique session number and insert this context into
428 me->MigrateBuf = NewStrBuf();
430 me->RecvBuf.Buf = NewStrBuf();
432 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. */
435 begin_critical_section(S_SESSION_TABLE);
436 me->cs_pid = ++next_pid;
438 me->next = ContextList;
440 if (me->next != NULL) {
444 end_critical_section(S_SESSION_TABLE);
450 * Initialize a new context and place it in the list. The session number
451 * used to be the PID (which is why it's called cs_pid), but that was when we
452 * had one process per session. Now we just assign them sequentially, starting
453 * at 1 (don't change it to 0 because masterCC uses 0).
455 CitContext *CloneContext(CitContext *CloneMe) {
458 me = (CitContext *) malloc(sizeof(CitContext));
460 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
463 memcpy(me, CloneMe, sizeof(CitContext));
465 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
466 memset(&me->SendBuf, 0, sizeof(IOBuffer));
467 memset(&me->SBuf, 0, sizeof(IOBuffer));
468 me->MigrateBuf = NULL;
469 me->sMigrateBuf = NULL;
470 me->redirect_buffer = NULL;
475 me->download_fp = NULL;
476 me->upload_fp = NULL;
477 /// TODO: what about the room/user?
479 me->openid_data = NULL;
481 me->session_specific_data = NULL;
485 me->cached_msglist = NULL;
486 me->download_fp = NULL;
487 me->upload_fp = NULL;
488 me->client_socket = 0;
490 me->MigrateBuf = NewStrBuf();
491 me->RecvBuf.Buf = NewStrBuf();
493 begin_critical_section(S_SESSION_TABLE);
495 me->cs_pid = ++next_pid;
497 me->next = ContextList;
498 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
500 if (me->next != NULL) {
505 end_critical_section(S_SESSION_TABLE);
511 * Return an array containing a copy of the context list.
512 * This allows worker threads to perform "for each context" operations without
513 * having to lock and traverse the live list.
515 CitContext *CtdlGetContextArray(int *count)
518 CitContext *nptr, *cptr;
520 nContexts = num_sessions;
521 nptr = malloc(sizeof(CitContext) * nContexts);
526 begin_critical_section(S_SESSION_TABLE);
527 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
528 memcpy(&nptr[i], cptr, sizeof (CitContext));
530 end_critical_section (S_SESSION_TABLE);
539 * This function fills in a context and its user field correctly
540 * Then creates/loads that user
542 void CtdlFillSystemContext(CitContext *context, char *name)
547 memset(context, 0, sizeof(CitContext));
548 context->internal_pgm = 1;
550 strcpy (sysname, "SYS_");
551 strcat (sysname, name);
552 len = cutuserkey(sysname);
553 memcpy(context->curr_user, sysname, len + 1);
554 context->client_socket = (-1);
555 context->state = CON_SYS;
556 context->ServiceName = name;
558 /* internal_create_user has the side effect of loading the user regardless of wether they
559 * already existed or needed to be created
561 internal_create_user (sysname, len, &(context->user), -1) ;
563 /* Check to see if the system user needs upgrading */
564 if (context->user.usernum == 0)
565 { /* old system user with number 0, upgrade it */
566 context->user.usernum = get_new_user_number();
567 CON_syslog(LOG_INFO, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
568 /* add user to the database */
569 CtdlPutUser(&(context->user));
570 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
576 * Cleanup any contexts that are left lying around
578 void context_cleanup(void)
580 CitContext *ptr = NULL;
581 CitContext *rem = NULL;
584 * Clean up the contexts.
585 * There are no threads so no critical_section stuff is needed.
589 /* We need to update the ContextList because some modules may want to itterate it
590 * Question is should we NULL it before iterating here or should we just keep updating it
591 * as we remove items?
593 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
597 /* Remove the session from the active list */
601 CON_syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
611 * Purge all sessions which have the 'kill_me' flag set.
612 * This function has code to prevent it from running more than once every
613 * few seconds, because running it after every single unbind would waste a lot
614 * of CPU time and keep the context list locked too much. To force it to run
615 * anyway, set "force" to nonzero.
617 void dead_session_purge(int force) {
618 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
619 CitContext *rem = NULL; /* list of sessions to be destroyed */
622 if ( (time(NULL) - last_purge) < 5 ) {
623 return; /* Too soon, go away */
628 if (try_critical_section(S_SESSION_TABLE))
636 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
637 /* Remove the session from the active list */
639 ptr2->prev->next = ptr2->next;
642 ContextList = ptr2->next;
645 ptr2->next->prev = ptr2->prev;
649 /* And put it on our to-be-destroyed list */
654 end_critical_section(S_SESSION_TABLE);
656 /* Now that we no longer have the session list locked, we can take
657 * our time and destroy any sessions on the to-be-killed list, which
658 * is allocated privately on this thread's stack.
660 while (rem != NULL) {
661 CON_syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
674 * masterCC is the context we use when not attached to a session. This
675 * function initializes it.
677 void InitializeMasterCC(void) {
678 memset(&masterCC, 0, sizeof(struct CitContext));
679 masterCC.internal_pgm = 1;
688 * Set the "async waiting" flag for a session, if applicable
690 void set_async_waiting(struct CitContext *ccptr)
692 CON_syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
693 if (ccptr->is_async) {
694 ccptr->async_waiting++;
695 if (ccptr->state == CON_IDLE) {
696 ccptr->state = CON_READY;
702 void DebugSessionEnable(const int n)
706 CTDL_MODULE_INIT(session)
709 CtdlRegisterDebugFlagHook(HKEY("session"), DebugSessionEnable, &DebugSession);