2 * $Id: sysdep.c 7989 2009-10-31 15:29:37Z davew $
4 * Citadel context management stuff.
5 * See COPYING for copyright information.
7 * Here's where we (hopefully) have all the code that manipulates contexts.
18 #include <sys/types.h>
21 #include <sys/socket.h>
23 #include <sys/syslog.h>
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
30 # include <sys/time.h>
37 #include <sys/resource.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <arpa/inet.h>
48 #include <libcitadel.h>
51 #include "sysdep_decls.h"
52 #include "citserver.h"
56 #include "housekeeping.h"
57 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
60 #ifdef HAVE_SYS_SELECT_H
61 #include <sys/select.h>
68 #include "ctdl_module.h"
75 citthread_key_t MyConKey; /* TSD key for MyContext() */
79 CitContext *ContextList = NULL;
81 time_t last_purge = 0; /* Last dead session purge */
82 int num_sessions = 0; /* Current number of sessions */
84 /* Flag for single user mode */
85 static int want_single_user = 0;
87 /* Try to go single user */
89 int CtdlTrySingleUser(void)
93 begin_critical_section(S_SINGLE_USER);
101 end_critical_section(S_SINGLE_USER);
105 void CtdlEndSingleUser(void)
107 begin_critical_section(S_SINGLE_USER);
108 want_single_user = 0;
109 end_critical_section(S_SINGLE_USER);
113 int CtdlWantSingleUser(void)
115 return want_single_user;
118 int CtdlIsSingleUser(void)
120 if (want_single_user)
122 /* check for only one context here */
123 if (num_sessions == 1)
134 * Locate a context by its session number and terminate it if the user is able.
135 * User can NOT terminate their current session.
136 * User CAN terminate any other session that has them logged in.
137 * Aide CAN terminate any session except the current one.
139 int CtdlTerminateOtherSession (int session_num)
144 if (session_num == CC->cs_pid) {
145 return TERM_NOTALLOWED;
148 CtdlLogPrintf(CTDL_DEBUG, "Locating session to kill\n");
149 begin_critical_section(S_SESSION_TABLE);
150 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
151 if (session_num == ccptr->cs_pid) {
153 if ((ccptr->user.usernum == CC->user.usernum)
154 || (CC->user.axlevel >= 6)) {
160 end_critical_section(S_SESSION_TABLE);
167 * Check to see if the user who we just sent mail to is logged in. If yes,
168 * bump the 'new mail' counter for their session. That enables them to
169 * receive a new mail notification without having to hit the database.
171 void BumpNewMailCounter(long which_user)
173 CtdlBumpNewMailCounter(which_user);
176 void CtdlBumpNewMailCounter(long which_user)
180 begin_critical_section(S_SESSION_TABLE);
182 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
183 if (ptr->user.usernum == which_user) {
188 end_critical_section(S_SESSION_TABLE);
193 * Check to see if a user is currently logged in
194 * Take care with what you do as a result of this test.
195 * The user may not have been logged in when this function was called BUT
196 * because of threading the user might be logged in before you test the result.
198 int CtdlIsUserLoggedIn (char *user_name)
203 begin_critical_section (S_SESSION_TABLE);
204 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
205 if (!strcasecmp(cptr->user.fullname, user_name)) {
210 end_critical_section(S_SESSION_TABLE);
217 * Check to see if a user is currently logged in.
218 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
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 CtdlIsUserLoggedInByNum (long usernum)
228 begin_critical_section(S_SESSION_TABLE);
229 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
230 if (cptr->user.usernum == usernum) {
234 end_critical_section(S_SESSION_TABLE);
241 * Return a pointer to the CitContext structure bound to the thread which
242 * called this function. If there's no such binding (for example, if it's
243 * called by the housekeeper thread) then a generic 'master' CC is returned.
245 * This function is used *VERY* frequently and must be kept small.
247 CitContext *MyContext(void) {
249 register CitContext *c;
251 return ((c = (CitContext *) citthread_getspecific(MyConKey),
252 c == NULL) ? &masterCC : c
260 * Terminate idle sessions. This function pounds through the session table
261 * comparing the current time to each session's time-of-last-command. If an
262 * idle session is found it is terminated, then the search restarts at the
263 * beginning because the pointer to our place in the list becomes invalid.
265 void terminate_idle_sessions(void)
275 begin_critical_section(S_SESSION_TABLE);
276 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
278 && (config.c_sleeping > 0)
279 && (now - (ccptr->lastcmd) > config.c_sleeping) ) {
280 if (!ccptr->dont_term) {
288 end_critical_section(S_SESSION_TABLE);
290 CtdlLogPrintf(CTDL_INFO, "Terminated %d idle sessions\n", killed);
292 CtdlLogPrintf(CTDL_INFO, "Didn't terminate %d protected idle sessions;\n", killed);
298 * Terminate a session.
300 void RemoveContext (CitContext *con)
303 CtdlLogPrintf(CTDL_ERR,
304 "WARNING: RemoveContext() called with NULL!\n");
307 CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
309 /* Run any cleanup routines registered by loadable modules.
310 * Note: We have to "become_session()" because the cleanup functions
311 * might make references to "CC" assuming it's the right one.
315 PerformSessionHooks(EVT_STOP);
316 become_session(NULL);
318 CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
320 /* If the client is still connected, blow 'em away. */
321 CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
322 close(con->client_socket);
324 /* If using AUTHMODE_LDAP, free the DN */
330 CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
337 * Initialize a new context and place it in the list. The session number
338 * used to be the PID (which is why it's called cs_pid), but that was when we
339 * had one process per session. Now we just assign them sequentially, starting
340 * at 1 (don't change it to 0 because masterCC uses 0).
342 CitContext *CreateNewContext(void) {
344 static int next_pid = 0;
346 me = (CitContext *) malloc(sizeof(CitContext));
348 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
351 memset(me, 0, sizeof(CitContext));
353 /* Give the contaxt a name. Hopefully makes it easier to track */
354 strcpy (me->user.fullname, "SYS_notauth");
356 /* The new context will be created already in the CON_EXECUTING state
357 * in order to prevent another thread from grabbing it while it's
360 me->state = CON_EXECUTING;
362 * Generate a unique session number and insert this context into
365 begin_critical_section(S_SESSION_TABLE);
366 me->cs_pid = ++next_pid;
368 me->next = ContextList;
370 if (me->next != NULL) {
374 end_critical_section(S_SESSION_TABLE);
379 CitContext *CtdlGetContextArray(int *count)
382 CitContext *nptr, *cptr;
384 nContexts = num_sessions;
385 nptr = malloc(sizeof(CitContext) * nContexts);
388 begin_critical_section(S_SESSION_TABLE);
389 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
390 memcpy(&nptr[i], cptr, sizeof (CitContext));
391 end_critical_section (S_SESSION_TABLE);
400 * This function fills in a context and its user field correctly
401 * Then creates/loads that user
403 void CtdlFillSystemContext(CitContext *context, char *name)
405 char sysname[USERNAME_SIZE];
407 memset(context, 0, sizeof(CitContext));
408 context->internal_pgm = 1;
410 strcpy (sysname, "SYS_");
411 strcat (sysname, name);
412 /* internal_create_user has the side effect of loading the user regardless of wether they
413 * already existed or needed to be created
415 internal_create_user (sysname, &(context->user), -1) ;
417 /* Check to see if the system user needs upgrading */
418 if (context->user.usernum == 0)
419 { /* old system user with number 0, upgrade it */
420 context->user.usernum = get_new_user_number();
421 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
422 /* add user to the database */
423 CtdlPutUser(&(context->user));
424 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
429 * Cleanup any contexts that are left lying around
431 void context_cleanup(void)
433 CitContext *ptr = NULL;
434 CitContext *rem = NULL;
437 * Clean up the contexts.
438 * There are no threads so no critical_section stuff is needed.
442 /* We need to update the ContextList because some modules may want to itterate it
443 * Question is should we NULL it before iterating here or should we just keep updating it
444 * as we remove items?
446 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
450 /* Remove the session from the active list */
454 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
464 * Terminate another session.
465 * (This could justifiably be moved out of sysdep.c because it
466 * no longer does anything that is system-dependent.)
468 void kill_session(int session_to_kill) {
471 begin_critical_section(S_SESSION_TABLE);
472 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
473 if (ptr->cs_pid == session_to_kill) {
477 end_critical_section(S_SESSION_TABLE);
481 * Purge all sessions which have the 'kill_me' flag set.
482 * This function has code to prevent it from running more than once every
483 * few seconds, because running it after every single unbind would waste a lot
484 * of CPU time and keep the context list locked too much. To force it to run
485 * anyway, set "force" to nonzero.
487 void dead_session_purge(int force) {
488 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
489 CitContext *rem = NULL; /* list of sessions to be destroyed */
492 if ( (time(NULL) - last_purge) < 5 ) {
493 return; /* Too soon, go away */
498 if (try_critical_section(S_SESSION_TABLE))
506 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
507 /* Remove the session from the active list */
509 ptr2->prev->next = ptr2->next;
512 ContextList = ptr2->next;
515 ptr2->next->prev = ptr2->prev;
519 /* And put it on our to-be-destroyed list */
524 end_critical_section(S_SESSION_TABLE);
526 /* Now that we no longer have the session list locked, we can take
527 * our time and destroy any sessions on the to-be-killed list, which
528 * is allocated privately on this thread's stack.
530 while (rem != NULL) {
531 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
544 * masterCC is the context we use when not attached to a session. This
545 * function initializes it.
547 void InitializeMasterCC(void) {
548 memset(&masterCC, 0, sizeof( CitContext));
549 masterCC.internal_pgm = 1;
557 * Bind a thread to a context. (It's inline merely to speed things up.)
559 INLINE void become_session(CitContext *which_con) {
560 citthread_setspecific(MyConKey, (void *)which_con );