2 * $Id: sysdep.c 7989 2009-10-31 15:29:37Z davew $
4 * Citadel context management stuff.
5 * Here's where we (hopefully) have all the code that manipulates contexts.
7 * Copyright (c) 1987-2010 by the citadel.org team
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31 #include <sys/types.h>
34 #include <sys/socket.h>
36 #include <sys/syslog.h>
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
43 # include <sys/time.h>
50 #include <sys/resource.h>
51 #include <netinet/in.h>
52 #include <netinet/tcp.h>
53 #include <arpa/inet.h>
61 #include <libcitadel.h>
64 #include "sysdep_decls.h"
65 #include "citserver.h"
69 #include "housekeeping.h"
70 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
73 #ifdef HAVE_SYS_SELECT_H
74 #include <sys/select.h>
81 #include "ctdl_module.h"
88 citthread_key_t MyConKey; /* TSD key for MyContext() */
92 CitContext *ContextList = NULL;
94 time_t last_purge = 0; /* Last dead session purge */
95 int num_sessions = 0; /* Current number of sessions */
97 /* Flag for single user mode */
98 static int want_single_user = 0;
100 /* Try to go single user */
102 int CtdlTrySingleUser(void)
106 begin_critical_section(S_SINGLE_USER);
107 if (want_single_user)
112 want_single_user = 1;
114 end_critical_section(S_SINGLE_USER);
118 void CtdlEndSingleUser(void)
120 begin_critical_section(S_SINGLE_USER);
121 want_single_user = 0;
122 end_critical_section(S_SINGLE_USER);
126 int CtdlWantSingleUser(void)
128 return want_single_user;
131 int CtdlIsSingleUser(void)
133 if (want_single_user)
135 /* check for only one context here */
136 if (num_sessions == 1)
147 * Locate a context by its session number and terminate it if the user is able.
148 * User can NOT terminate their current session.
149 * User CAN terminate any other session that has them logged in.
150 * Aide CAN terminate any session except the current one.
152 int CtdlTerminateOtherSession (int session_num)
157 if (session_num == CC->cs_pid) {
158 return TERM_NOTALLOWED;
161 CtdlLogPrintf(CTDL_DEBUG, "Locating session to kill\n");
162 begin_critical_section(S_SESSION_TABLE);
163 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
164 if (session_num == ccptr->cs_pid) {
166 if ((ccptr->user.usernum == CC->user.usernum)
167 || (CC->user.axlevel >= AxAideU)) {
173 end_critical_section(S_SESSION_TABLE);
180 * Check to see if the user who we just sent mail to is logged in. If yes,
181 * bump the 'new mail' counter for their session. That enables them to
182 * receive a new mail notification without having to hit the database.
184 void BumpNewMailCounter(long which_user)
186 CtdlBumpNewMailCounter(which_user);
189 void CtdlBumpNewMailCounter(long which_user)
193 begin_critical_section(S_SESSION_TABLE);
195 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
196 if (ptr->user.usernum == which_user) {
201 end_critical_section(S_SESSION_TABLE);
206 * Check to see if a user is currently logged in
207 * Take care with what you do as a result of this test.
208 * The user may not have been logged in when this function was called BUT
209 * because of threading the user might be logged in before you test the result.
211 int CtdlIsUserLoggedIn (char *user_name)
216 begin_critical_section (S_SESSION_TABLE);
217 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
218 if (!strcasecmp(cptr->user.fullname, user_name)) {
223 end_critical_section(S_SESSION_TABLE);
230 * Check to see if a user is currently logged in.
231 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
232 * Take care with what you do as a result of this test.
233 * The user may not have been logged in when this function was called BUT
234 * because of threading the user might be logged in before you test the result.
236 int CtdlIsUserLoggedInByNum (long usernum)
241 begin_critical_section(S_SESSION_TABLE);
242 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
243 if (cptr->user.usernum == usernum) {
247 end_critical_section(S_SESSION_TABLE);
254 * Return a pointer to the CitContext structure bound to the thread which
255 * called this function. If there's no such binding (for example, if it's
256 * called by the housekeeper thread) then a generic 'master' CC is returned.
258 * This function is used *VERY* frequently and must be kept small.
260 CitContext *MyContext(void) {
262 register CitContext *c;
264 return ((c = (CitContext *) citthread_getspecific(MyConKey),
265 c == NULL) ? &masterCC : c
273 * Terminate idle sessions. This function pounds through the session table
274 * comparing the current time to each session's time-of-last-command. If an
275 * idle session is found it is terminated, then the search restarts at the
276 * beginning because the pointer to our place in the list becomes invalid.
278 void terminate_idle_sessions(void)
288 begin_critical_section(S_SESSION_TABLE);
289 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
291 && (config.c_sleeping > 0)
292 && (now - (ccptr->lastcmd) > config.c_sleeping) ) {
293 if (!ccptr->dont_term) {
301 end_critical_section(S_SESSION_TABLE);
303 CtdlLogPrintf(CTDL_INFO, "Terminated %d idle sessions\n", killed);
305 CtdlLogPrintf(CTDL_INFO, "Didn't terminate %d protected idle sessions;\n", killed);
311 * Terminate a session.
313 void RemoveContext (CitContext *con)
316 CtdlLogPrintf(CTDL_ERR,
317 "WARNING: RemoveContext() called with NULL!\n");
320 CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
322 /* Run any cleanup routines registered by loadable modules.
323 * Note: We have to "become_session()" because the cleanup functions
324 * might make references to "CC" assuming it's the right one.
328 PerformSessionHooks(EVT_STOP);
329 become_session(NULL);
331 CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
333 /* If the client is still connected, blow 'em away. */
334 CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
335 close(con->client_socket);
337 /* If using AUTHMODE_LDAP, free the DN */
343 FreeStrBuf(&con->MigrateBuf);
344 FreeStrBuf(&con->ReadBuf);
345 CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
352 * Initialize a new context and place it in the list. The session number
353 * used to be the PID (which is why it's called cs_pid), but that was when we
354 * had one process per session. Now we just assign them sequentially, starting
355 * at 1 (don't change it to 0 because masterCC uses 0).
357 CitContext *CreateNewContext(void) {
359 static int next_pid = 0;
361 me = (CitContext *) malloc(sizeof(CitContext));
363 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
366 memset(me, 0, sizeof(CitContext));
368 /* Give the contaxt a name. Hopefully makes it easier to track */
369 strcpy (me->user.fullname, "SYS_notauth");
371 /* The new context will be created already in the CON_EXECUTING state
372 * in order to prevent another thread from grabbing it while it's
375 me->state = CON_EXECUTING;
377 * Generate a unique session number and insert this context into
380 me->MigrateBuf = NewStrBuf();
381 me->ReadBuf = NewStrBuf();
382 begin_critical_section(S_SESSION_TABLE);
383 me->cs_pid = ++next_pid;
385 me->next = ContextList;
387 if (me->next != NULL) {
391 end_critical_section(S_SESSION_TABLE);
397 * Return an array containing a copy of the context list.
398 * This allows worker threads to perform "for each context" operations without
399 * having to lock and traverse the live list.
401 CitContext *CtdlGetContextArray(int *count)
404 CitContext *nptr, *cptr;
406 nContexts = num_sessions;
407 nptr = malloc(sizeof(CitContext) * nContexts);
412 begin_critical_section(S_SESSION_TABLE);
413 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
414 memcpy(&nptr[i], cptr, sizeof (CitContext));
416 end_critical_section (S_SESSION_TABLE);
425 * This function fills in a context and its user field correctly
426 * Then creates/loads that user
428 void CtdlFillSystemContext(CitContext *context, char *name)
430 char sysname[USERNAME_SIZE];
432 memset(context, 0, sizeof(CitContext));
433 context->internal_pgm = 1;
435 strcpy (sysname, "SYS_");
436 strcat (sysname, name);
437 /* internal_create_user has the side effect of loading the user regardless of wether they
438 * already existed or needed to be created
440 internal_create_user (sysname, &(context->user), -1) ;
442 /* Check to see if the system user needs upgrading */
443 if (context->user.usernum == 0)
444 { /* old system user with number 0, upgrade it */
445 context->user.usernum = get_new_user_number();
446 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
447 /* add user to the database */
448 CtdlPutUser(&(context->user));
449 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
454 * Cleanup any contexts that are left lying around
456 void context_cleanup(void)
458 CitContext *ptr = NULL;
459 CitContext *rem = NULL;
462 * Clean up the contexts.
463 * There are no threads so no critical_section stuff is needed.
467 /* We need to update the ContextList because some modules may want to itterate it
468 * Question is should we NULL it before iterating here or should we just keep updating it
469 * as we remove items?
471 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
475 /* Remove the session from the active list */
479 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
489 * Terminate another session.
490 * (This could justifiably be moved out of sysdep.c because it
491 * no longer does anything that is system-dependent.)
493 void kill_session(int session_to_kill) {
496 begin_critical_section(S_SESSION_TABLE);
497 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
498 if (ptr->cs_pid == session_to_kill) {
502 end_critical_section(S_SESSION_TABLE);
506 * Purge all sessions which have the 'kill_me' flag set.
507 * This function has code to prevent it from running more than once every
508 * few seconds, because running it after every single unbind would waste a lot
509 * of CPU time and keep the context list locked too much. To force it to run
510 * anyway, set "force" to nonzero.
512 void dead_session_purge(int force) {
513 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
514 CitContext *rem = NULL; /* list of sessions to be destroyed */
517 if ( (time(NULL) - last_purge) < 5 ) {
518 return; /* Too soon, go away */
523 if (try_critical_section(S_SESSION_TABLE))
531 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
532 /* Remove the session from the active list */
534 ptr2->prev->next = ptr2->next;
537 ContextList = ptr2->next;
540 ptr2->next->prev = ptr2->prev;
544 /* And put it on our to-be-destroyed list */
549 end_critical_section(S_SESSION_TABLE);
551 /* Now that we no longer have the session list locked, we can take
552 * our time and destroy any sessions on the to-be-killed list, which
553 * is allocated privately on this thread's stack.
555 while (rem != NULL) {
556 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
569 * masterCC is the context we use when not attached to a session. This
570 * function initializes it.
572 void InitializeMasterCC(void) {
573 memset(&masterCC, 0, sizeof( CitContext));
574 masterCC.internal_pgm = 1;
582 * Bind a thread to a context. (It's inline merely to speed things up.)
584 INLINE void become_session(CitContext *which_con) {
585 citthread_setspecific(MyConKey, (void *)which_con );
590 * Set the "async waiting" flag for a session, if applicable
592 void set_async_waiting(struct CitContext *ccptr)
594 CtdlLogPrintf(CTDL_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
595 if (ccptr->is_async) {
596 ccptr->async_waiting++;
597 if (ccptr->state == CON_IDLE) {
598 ccptr->state = CON_READY;