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 as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 #include <sys/types.h>
32 #include <sys/socket.h>
34 #include <sys/syslog.h>
36 #include <sys/syscall.h>
39 #if TIME_WITH_SYS_TIME
40 # include <sys/time.h>
44 # include <sys/time.h>
51 #include <sys/resource.h>
52 #include <netinet/in.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
62 #include <libcitadel.h>
65 #include "sysdep_decls.h"
66 #include "citserver.h"
70 #include "housekeeping.h"
71 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
74 #ifdef HAVE_SYS_SELECT_H
75 #include <sys/select.h>
82 #include "ctdl_module.h"
89 pthread_key_t MyConKey; /* TSD key for MyContext() */
93 CitContext *ContextList = NULL;
95 time_t last_purge = 0; /* Last dead session purge */
96 int num_sessions = 0; /* Current number of sessions */
98 /* Flag for single user mode */
99 static int want_single_user = 0;
101 /* Try to go single user */
103 int CtdlTrySingleUser(void)
107 begin_critical_section(S_SINGLE_USER);
108 if (want_single_user)
113 want_single_user = 1;
115 end_critical_section(S_SINGLE_USER);
119 void CtdlEndSingleUser(void)
121 begin_critical_section(S_SINGLE_USER);
122 want_single_user = 0;
123 end_critical_section(S_SINGLE_USER);
127 int CtdlWantSingleUser(void)
129 return want_single_user;
132 int CtdlIsSingleUser(void)
134 if (want_single_user)
136 /* check for only one context here */
137 if (num_sessions == 1)
148 * Locate a context by its session number and terminate it if the user is able.
149 * User can NOT terminate their current session.
150 * User CAN terminate any other session that has them logged in.
151 * Aide CAN terminate any session except the current one.
153 int CtdlTerminateOtherSession (int session_num)
158 if (session_num == CC->cs_pid) {
159 return TERM_NOTALLOWED;
162 syslog(LOG_DEBUG, "Locating session to kill\n");
163 begin_critical_section(S_SESSION_TABLE);
164 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
165 if (session_num == ccptr->cs_pid) {
167 if ((ccptr->user.usernum == CC->user.usernum)
168 || (CC->user.axlevel >= AxAideU)) {
170 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
174 end_critical_section(S_SESSION_TABLE);
181 * Check to see if the user who we just sent mail to is logged in. If yes,
182 * bump the 'new mail' counter for their session. That enables them to
183 * receive a new mail notification without having to hit the database.
185 void BumpNewMailCounter(long which_user)
187 CtdlBumpNewMailCounter(which_user);
190 void CtdlBumpNewMailCounter(long which_user)
194 begin_critical_section(S_SESSION_TABLE);
196 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
197 if (ptr->user.usernum == which_user) {
202 end_critical_section(S_SESSION_TABLE);
207 * Check to see if a user is currently logged in
208 * Take care with what you do as a result of this test.
209 * The user may not have been logged in when this function was called BUT
210 * because of threading the user might be logged in before you test the result.
212 int CtdlIsUserLoggedIn (char *user_name)
217 begin_critical_section (S_SESSION_TABLE);
218 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
219 if (!strcasecmp(cptr->user.fullname, user_name)) {
224 end_critical_section(S_SESSION_TABLE);
231 * Check to see if a user is currently logged in.
232 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
233 * Take care with what you do as a result of this test.
234 * The user may not have been logged in when this function was called BUT
235 * because of threading the user might be logged in before you test the result.
237 int CtdlIsUserLoggedInByNum (long usernum)
242 begin_critical_section(S_SESSION_TABLE);
243 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
244 if (cptr->user.usernum == usernum) {
248 end_critical_section(S_SESSION_TABLE);
255 * Return a pointer to the CitContext structure bound to the thread which
256 * called this function. If there's no such binding (for example, if it's
257 * called by the housekeeper thread) then a generic 'master' CC is returned.
259 * This function is used *VERY* frequently and must be kept small.
261 CitContext *MyContext(void) {
262 register CitContext *c;
263 return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
270 * Terminate idle sessions. This function pounds through the session table
271 * comparing the current time to each session's time-of-last-command. If an
272 * idle session is found it is terminated, then the search restarts at the
273 * beginning because the pointer to our place in the list becomes invalid.
275 void terminate_idle_sessions(void)
285 begin_critical_section(S_SESSION_TABLE);
286 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
289 && (config.c_sleeping > 0)
290 && (now - (ccptr->lastcmd) > config.c_sleeping)
292 if (!ccptr->dont_term) {
293 ccptr->kill_me = KILLME_IDLE;
301 end_critical_section(S_SESSION_TABLE);
303 syslog(LOG_INFO, "Terminated %d idle sessions", killed);
305 syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
310 * During shutdown, close the sockets of any sessions still connected.
312 void terminate_all_sessions(void)
317 begin_critical_section(S_SESSION_TABLE);
318 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
319 if (ccptr->client_socket != -1)
321 syslog(LOG_INFO, "terminate_all_sessions() is murdering %s", ccptr->curr_user);
322 close(ccptr->client_socket);
323 ccptr->client_socket = -1;
327 end_critical_section(S_SESSION_TABLE);
329 syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
336 * Terminate a session.
338 void RemoveContext (CitContext *con)
342 syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
345 c = con->ServiceName;
349 syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
352 /* Run any cleanup routines registered by loadable modules.
353 * Note: We have to "become_session()" because the cleanup functions
354 * might make references to "CC" assuming it's the right one.
358 PerformSessionHooks(EVT_STOP);
359 client_close(); /* If the client is still connected, blow 'em away. */
360 become_session(NULL);
362 syslog(LOG_NOTICE, "[%3d] Session ended.", con->cs_pid);
365 * If the client is still connected, blow 'em away.
366 * if the socket is 0 or -1, its already gone or was never there.
368 if (con->client_socket > 0)
370 syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
371 close(con->client_socket);
374 /* If using AUTHMODE_LDAP, free the DN */
380 FreeStrBuf(&con->MigrateBuf);
381 FreeStrBuf(&con->ReadBuf);
382 if (con->cached_msglist) {
383 free(con->cached_msglist);
386 syslog(LOG_DEBUG, "Done with RemoveContext()");
392 * Initialize a new context and place it in the list. The session number
393 * used to be the PID (which is why it's called cs_pid), but that was when we
394 * had one process per session. Now we just assign them sequentially, starting
395 * at 1 (don't change it to 0 because masterCC uses 0).
397 CitContext *CreateNewContext(void) {
399 static int next_pid = 0;
401 me = (CitContext *) malloc(sizeof(CitContext));
403 syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
406 memset(me, 0, sizeof(CitContext));
408 /* Give the context a name. Hopefully makes it easier to track */
409 strcpy (me->user.fullname, "SYS_notauth");
411 /* The new context will be created already in the CON_EXECUTING state
412 * in order to prevent another thread from grabbing it while it's
415 me->state = CON_EXECUTING;
417 * Generate a unique session number and insert this context into
420 me->MigrateBuf = NewStrBuf();
421 me->ReadBuf = NewStrBuf();
422 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
424 begin_critical_section(S_SESSION_TABLE);
425 me->cs_pid = ++next_pid;
427 me->next = ContextList;
429 if (me->next != NULL) {
433 end_critical_section(S_SESSION_TABLE);
439 * Return an array containing a copy of the context list.
440 * This allows worker threads to perform "for each context" operations without
441 * having to lock and traverse the live list.
443 CitContext *CtdlGetContextArray(int *count)
446 CitContext *nptr, *cptr;
448 nContexts = num_sessions;
449 nptr = malloc(sizeof(CitContext) * nContexts);
454 begin_critical_section(S_SESSION_TABLE);
455 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
456 memcpy(&nptr[i], cptr, sizeof (CitContext));
458 end_critical_section (S_SESSION_TABLE);
466 * Cleanup any contexts that are left lying around
468 void context_cleanup(void)
470 CitContext *ptr = NULL;
471 CitContext *rem = NULL;
474 * Clean up the contexts.
475 * There are no threads so no critical_section stuff is needed.
479 /* We need to update the ContextList because some modules may want to itterate it
480 * Question is should we NULL it before iterating here or should we just keep updating it
481 * as we remove items?
483 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
487 /* Remove the session from the active list */
491 syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
501 * Purge all sessions which have the 'kill_me' flag set.
502 * This function has code to prevent it from running more than once every
503 * few seconds, because running it after every single unbind would waste a lot
504 * of CPU time and keep the context list locked too much. To force it to run
505 * anyway, set "force" to nonzero.
507 void dead_session_purge(int force) {
508 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
509 CitContext *rem = NULL; /* list of sessions to be destroyed */
512 if ( (time(NULL) - last_purge) < 5 ) {
513 return; /* Too soon, go away */
518 if (try_critical_section(S_SESSION_TABLE))
526 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
527 /* Remove the session from the active list */
529 ptr2->prev->next = ptr2->next;
532 ContextList = ptr2->next;
535 ptr2->next->prev = ptr2->prev;
539 /* And put it on our to-be-destroyed list */
544 end_critical_section(S_SESSION_TABLE);
546 /* Now that we no longer have the session list locked, we can take
547 * our time and destroy any sessions on the to-be-killed list, which
548 * is allocated privately on this thread's stack.
550 while (rem != NULL) {
551 syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
564 * masterCC is the context we use when not attached to a session. This
565 * function initializes it.
567 void InitializeMasterCC(void) {
568 memset(&masterCC, 0, sizeof(struct CitContext));
569 masterCC.internal_pgm = 1;
578 * Set the "async waiting" flag for a session, if applicable
580 void set_async_waiting(struct CitContext *ccptr)
582 syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
583 if (ccptr->is_async) {
584 ccptr->async_waiting++;
585 if (ccptr->state == CON_IDLE) {
586 ccptr->state = CON_READY;