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 #include <sys/syscall.h>
41 #if TIME_WITH_SYS_TIME
42 # include <sys/time.h>
46 # include <sys/time.h>
53 #include <sys/resource.h>
54 #include <netinet/in.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
64 #include <libcitadel.h>
67 #include "sysdep_decls.h"
68 #include "citserver.h"
72 #include "housekeeping.h"
73 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
76 #ifdef HAVE_SYS_SELECT_H
77 #include <sys/select.h>
84 #include "ctdl_module.h"
91 citthread_key_t MyConKey; /* TSD key for MyContext() */
95 CitContext *ContextList = NULL;
97 time_t last_purge = 0; /* Last dead session purge */
98 int num_sessions = 0; /* Current number of sessions */
100 /* Flag for single user mode */
101 static int want_single_user = 0;
103 /* Try to go single user */
105 int CtdlTrySingleUser(void)
109 begin_critical_section(S_SINGLE_USER);
110 if (want_single_user)
115 want_single_user = 1;
117 end_critical_section(S_SINGLE_USER);
121 void CtdlEndSingleUser(void)
123 begin_critical_section(S_SINGLE_USER);
124 want_single_user = 0;
125 end_critical_section(S_SINGLE_USER);
129 int CtdlWantSingleUser(void)
131 return want_single_user;
134 int CtdlIsSingleUser(void)
136 if (want_single_user)
138 /* check for only one context here */
139 if (num_sessions == 1)
150 * Locate a context by its session number and terminate it if the user is able.
151 * User can NOT terminate their current session.
152 * User CAN terminate any other session that has them logged in.
153 * Aide CAN terminate any session except the current one.
155 int CtdlTerminateOtherSession (int session_num)
160 if (session_num == CC->cs_pid) {
161 return TERM_NOTALLOWED;
164 CtdlLogPrintf(CTDL_DEBUG, "Locating session to kill\n");
165 begin_critical_section(S_SESSION_TABLE);
166 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
167 if (session_num == ccptr->cs_pid) {
169 if ((ccptr->user.usernum == CC->user.usernum)
170 || (CC->user.axlevel >= AxAideU)) {
176 end_critical_section(S_SESSION_TABLE);
183 * Check to see if the user who we just sent mail to is logged in. If yes,
184 * bump the 'new mail' counter for their session. That enables them to
185 * receive a new mail notification without having to hit the database.
187 void BumpNewMailCounter(long which_user)
189 CtdlBumpNewMailCounter(which_user);
192 void CtdlBumpNewMailCounter(long which_user)
196 begin_critical_section(S_SESSION_TABLE);
198 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
199 if (ptr->user.usernum == which_user) {
204 end_critical_section(S_SESSION_TABLE);
209 * Check to see if a user is currently logged in
210 * Take care with what you do as a result of this test.
211 * The user may not have been logged in when this function was called BUT
212 * because of threading the user might be logged in before you test the result.
214 int CtdlIsUserLoggedIn (char *user_name)
219 begin_critical_section (S_SESSION_TABLE);
220 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
221 if (!strcasecmp(cptr->user.fullname, user_name)) {
226 end_critical_section(S_SESSION_TABLE);
233 * Check to see if a user is currently logged in.
234 * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
235 * Take care with what you do as a result of this test.
236 * The user may not have been logged in when this function was called BUT
237 * because of threading the user might be logged in before you test the result.
239 int CtdlIsUserLoggedInByNum (long usernum)
244 begin_critical_section(S_SESSION_TABLE);
245 for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
246 if (cptr->user.usernum == usernum) {
250 end_critical_section(S_SESSION_TABLE);
257 * Return a pointer to the CitContext structure bound to the thread which
258 * called this function. If there's no such binding (for example, if it's
259 * called by the housekeeper thread) then a generic 'master' CC is returned.
261 * This function is used *VERY* frequently and must be kept small.
263 CitContext *MyContext(void) {
265 register CitContext *c;
267 return ((c = (CitContext *) citthread_getspecific(MyConKey),
268 c == NULL) ? &masterCC : c
276 * Terminate idle sessions. This function pounds through the session table
277 * comparing the current time to each session's time-of-last-command. If an
278 * idle session is found it is terminated, then the search restarts at the
279 * beginning because the pointer to our place in the list becomes invalid.
281 void terminate_idle_sessions(void)
291 begin_critical_section(S_SESSION_TABLE);
292 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
294 && (config.c_sleeping > 0)
295 && (now - (ccptr->lastcmd) > config.c_sleeping) ) {
296 if (!ccptr->dont_term) {
304 end_critical_section(S_SESSION_TABLE);
306 CtdlLogPrintf(CTDL_INFO, "Terminated %d idle sessions\n", killed);
308 CtdlLogPrintf(CTDL_INFO, "Didn't terminate %d protected idle sessions;\n", killed);
314 * Terminate a session.
316 void RemoveContext (CitContext *con)
319 CtdlLogPrintf(CTDL_ERR,
320 "WARNING: RemoveContext() called with NULL!\n");
323 CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
325 /* Run any cleanup routines registered by loadable modules.
326 * Note: We have to "become_session()" because the cleanup functions
327 * might make references to "CC" assuming it's the right one.
331 PerformSessionHooks(EVT_STOP);
332 become_session(NULL);
334 CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
336 /* If the client is still connected, blow 'em away. */
337 CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
338 close(con->client_socket);
340 /* If using AUTHMODE_LDAP, free the DN */
346 FreeStrBuf(&con->MigrateBuf);
347 FreeStrBuf(&con->ReadBuf);
348 CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
355 * Initialize a new context and place it in the list. The session number
356 * used to be the PID (which is why it's called cs_pid), but that was when we
357 * had one process per session. Now we just assign them sequentially, starting
358 * at 1 (don't change it to 0 because masterCC uses 0).
360 CitContext *CreateNewContext(void) {
362 static int next_pid = 0;
364 me = (CitContext *) malloc(sizeof(CitContext));
366 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
369 memset(me, 0, sizeof(CitContext));
371 /* Give the contaxt a name. Hopefully makes it easier to track */
372 strcpy (me->user.fullname, "SYS_notauth");
374 /* The new context will be created already in the CON_EXECUTING state
375 * in order to prevent another thread from grabbing it while it's
378 me->state = CON_EXECUTING;
380 * Generate a unique session number and insert this context into
383 me->MigrateBuf = NewStrBuf();
384 me->ReadBuf = NewStrBuf();
385 begin_critical_section(S_SESSION_TABLE);
386 me->cs_pid = ++next_pid;
388 me->next = ContextList;
390 if (me->next != NULL) {
394 end_critical_section(S_SESSION_TABLE);
400 * Return an array containing a copy of the context list.
401 * This allows worker threads to perform "for each context" operations without
402 * having to lock and traverse the live list.
404 CitContext *CtdlGetContextArray(int *count)
407 CitContext *nptr, *cptr;
409 nContexts = num_sessions;
410 nptr = malloc(sizeof(CitContext) * nContexts);
415 begin_critical_section(S_SESSION_TABLE);
416 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
417 memcpy(&nptr[i], cptr, sizeof (CitContext));
419 end_critical_section (S_SESSION_TABLE);
428 * This function fills in a context and its user field correctly
429 * Then creates/loads that user
431 void CtdlFillSystemContext(CitContext *context, char *name)
436 memset(context, 0, sizeof(CitContext));
437 context->internal_pgm = 1;
439 strcpy (sysname, "SYS_");
440 strcat (sysname, name);
441 len = cutuserkey(sysname);
442 /* internal_create_user has the side effect of loading the user regardless of wether they
443 * already existed or needed to be created
445 internal_create_user (sysname, len, &(context->user), -1) ;
447 /* Check to see if the system user needs upgrading */
448 if (context->user.usernum == 0)
449 { /* old system user with number 0, upgrade it */
450 context->user.usernum = get_new_user_number();
451 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
452 /* add user to the database */
453 CtdlPutUser(&(context->user));
454 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
459 * Cleanup any contexts that are left lying around
461 void context_cleanup(void)
463 CitContext *ptr = NULL;
464 CitContext *rem = NULL;
467 * Clean up the contexts.
468 * There are no threads so no critical_section stuff is needed.
472 /* We need to update the ContextList because some modules may want to itterate it
473 * Question is should we NULL it before iterating here or should we just keep updating it
474 * as we remove items?
476 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
480 /* Remove the session from the active list */
484 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
494 * Terminate another session.
495 * (This could justifiably be moved out of sysdep.c because it
496 * no longer does anything that is system-dependent.)
498 void kill_session(int session_to_kill) {
501 begin_critical_section(S_SESSION_TABLE);
502 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
503 if (ptr->cs_pid == session_to_kill) {
507 end_critical_section(S_SESSION_TABLE);
511 * Purge all sessions which have the 'kill_me' flag set.
512 * This function has code to prevent it from running more than once every
513 * few seconds, because running it after every single unbind would waste a lot
514 * of CPU time and keep the context list locked too much. To force it to run
515 * anyway, set "force" to nonzero.
517 void dead_session_purge(int force) {
518 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
519 CitContext *rem = NULL; /* list of sessions to be destroyed */
522 if ( (time(NULL) - last_purge) < 5 ) {
523 return; /* Too soon, go away */
528 if (try_critical_section(S_SESSION_TABLE))
536 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
537 /* Remove the session from the active list */
539 ptr2->prev->next = ptr2->next;
542 ContextList = ptr2->next;
545 ptr2->next->prev = ptr2->prev;
549 /* And put it on our to-be-destroyed list */
554 end_critical_section(S_SESSION_TABLE);
556 /* Now that we no longer have the session list locked, we can take
557 * our time and destroy any sessions on the to-be-killed list, which
558 * is allocated privately on this thread's stack.
560 while (rem != NULL) {
561 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
574 * masterCC is the context we use when not attached to a session. This
575 * function initializes it.
577 void InitializeMasterCC(void) {
578 memset(&masterCC, 0, sizeof( CitContext));
579 masterCC.internal_pgm = 1;
588 * Set the "async waiting" flag for a session, if applicable
590 void set_async_waiting(struct CitContext *ccptr)
592 CtdlLogPrintf(CTDL_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
593 if (ccptr->is_async) {
594 ccptr->async_waiting++;
595 if (ccptr->state == CON_IDLE) {
596 ccptr->state = CON_READY;