2 * Citadel context management stuff.
3 * Here's where we (hopefully) have all the code that manipulates contexts.
5 * Copyright (c) 1987-2010 by the citadel.org team
7 * This program is free 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 citthread_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 CtdlLogPrintf(CTDL_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)) {
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) {
263 register CitContext *c;
265 return ((c = (CitContext *) citthread_getspecific(MyConKey),
266 c == NULL) ? &masterCC : c
274 * Terminate idle sessions. This function pounds through the session table
275 * comparing the current time to each session's time-of-last-command. If an
276 * idle session is found it is terminated, then the search restarts at the
277 * beginning because the pointer to our place in the list becomes invalid.
279 void terminate_idle_sessions(void)
289 begin_critical_section(S_SESSION_TABLE);
290 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
292 && (config.c_sleeping > 0)
293 && (now - (ccptr->lastcmd) > config.c_sleeping) ) {
294 if (!ccptr->dont_term) {
302 end_critical_section(S_SESSION_TABLE);
304 CtdlLogPrintf(CTDL_INFO, "Terminated %d idle sessions\n", killed);
306 CtdlLogPrintf(CTDL_INFO, "Didn't terminate %d protected idle sessions;\n", killed);
309 void terminate_stuck_sessions(void)
314 begin_critical_section(S_SESSION_TABLE);
315 for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
316 if (ccptr->client_socket != -1)
318 close(ccptr->client_socket);
319 ccptr->client_socket = -1;
323 end_critical_section(S_SESSION_TABLE);
325 CtdlLogPrintf(CTDL_INFO, "Flushed %d stuck sessions\n", killed);
331 * Terminate a session.
333 void RemoveContext (CitContext *con)
336 CtdlLogPrintf(CTDL_ERR,
337 "WARNING: RemoveContext() called with NULL!\n");
340 CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
342 /* Run any cleanup routines registered by loadable modules.
343 * Note: We have to "become_session()" because the cleanup functions
344 * might make references to "CC" assuming it's the right one.
348 PerformSessionHooks(EVT_STOP);
349 become_session(NULL);
351 CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
354 * If the client is still connected, blow 'em away.
355 * if the socket is 0, its already gone or was never there.
357 if (con->client_socket != 0)
359 CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
360 close(con->client_socket);
363 /* If using AUTHMODE_LDAP, free the DN */
369 FreeStrBuf(&con->MigrateBuf);
370 FreeStrBuf(&con->RecvBuf.Buf);
371 CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
378 * Initialize a new context and place it in the list. The session number
379 * used to be the PID (which is why it's called cs_pid), but that was when we
380 * had one process per session. Now we just assign them sequentially, starting
381 * at 1 (don't change it to 0 because masterCC uses 0).
383 CitContext *CreateNewContext(void) {
385 static int next_pid = 0;
387 me = (CitContext *) malloc(sizeof(CitContext));
389 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
392 memset(me, 0, sizeof(CitContext));
393 /* Give the contaxt a name. Hopefully makes it easier to track */
394 strcpy (me->user.fullname, "SYS_notauth");
396 /* The new context will be created already in the CON_EXECUTING state
397 * in order to prevent another thread from grabbing it while it's
400 me->state = CON_EXECUTING;
402 * Generate a unique session number and insert this context into
405 me->MigrateBuf = NewStrBuf();
406 me->RecvBuf.Buf = NewStrBuf();
407 begin_critical_section(S_SESSION_TABLE);
408 me->cs_pid = ++next_pid;
410 me->next = ContextList;
411 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
413 if (me->next != NULL) {
417 end_critical_section(S_SESSION_TABLE);
423 * Initialize a new context and place it in the list. The session number
424 * used to be the PID (which is why it's called cs_pid), but that was when we
425 * had one process per session. Now we just assign them sequentially, starting
426 * at 1 (don't change it to 0 because masterCC uses 0).
428 CitContext *CloneContext(CitContext *CloneMe) {
430 static int next_pid = 0;
432 me = (CitContext *) malloc(sizeof(CitContext));
434 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
437 memcpy(me, CloneMe, sizeof(CitContext));
439 memset(&me->RecvBuf, 0, sizeof(IOBuffer));
440 memset(&me->SendBuf, 0, sizeof(IOBuffer));
441 memset(&me->SBuf, 0, sizeof(IOBuffer));
442 me->MigrateBuf = NULL;
443 me->sMigrateBuf = NULL;
444 me->redirect_buffer = NULL;
449 me->download_fp = NULL;
450 me->upload_fp = NULL;
451 /// TODO: what about the room/user?
453 me->openid_data = NULL;
455 me->session_specific_data = NULL;
457 me->MigrateBuf = NewStrBuf();
458 me->RecvBuf.Buf = NewStrBuf();
460 begin_critical_section(S_SESSION_TABLE);
462 me->cs_pid = ++next_pid;
464 me->next = ContextList;
465 me->lastcmd = time(NULL); /* set lastcmd to now to prevent idle timer infanticide */
467 if (me->next != NULL) {
472 end_critical_section(S_SESSION_TABLE);
478 * Return an array containing a copy of the context list.
479 * This allows worker threads to perform "for each context" operations without
480 * having to lock and traverse the live list.
482 CitContext *CtdlGetContextArray(int *count)
485 CitContext *nptr, *cptr;
487 nContexts = num_sessions;
488 nptr = malloc(sizeof(CitContext) * nContexts);
493 begin_critical_section(S_SESSION_TABLE);
494 for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
495 memcpy(&nptr[i], cptr, sizeof (CitContext));
497 end_critical_section (S_SESSION_TABLE);
506 * This function fills in a context and its user field correctly
507 * Then creates/loads that user
509 void CtdlFillSystemContext(CitContext *context, char *name)
514 memset(context, 0, sizeof(CitContext));
515 context->internal_pgm = 1;
517 strcpy (sysname, "SYS_");
518 strcat (sysname, name);
519 len = cutuserkey(sysname);
520 memcpy(context->curr_user, sysname, len + 1);
521 context->client_socket = (-1);
523 /* internal_create_user has the side effect of loading the user regardless of wether they
524 * already existed or needed to be created
526 internal_create_user (sysname, len, &(context->user), -1) ;
528 /* Check to see if the system user needs upgrading */
529 if (context->user.usernum == 0)
530 { /* old system user with number 0, upgrade it */
531 context->user.usernum = get_new_user_number();
532 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
533 /* add user to the database */
534 CtdlPutUser(&(context->user));
535 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
542 void CtdlClearSystemContext(void)
544 CitContext *CCC = MyContext();
546 memset(CCC, 0, sizeof(CitContext));
547 citthread_setspecific(MyConKey, NULL);
551 * Cleanup any contexts that are left lying around
553 void context_cleanup(void)
555 CitContext *ptr = NULL;
556 CitContext *rem = NULL;
559 * Clean up the contexts.
560 * There are no threads so no critical_section stuff is needed.
564 /* We need to update the ContextList because some modules may want to itterate it
565 * Question is should we NULL it before iterating here or should we just keep updating it
566 * as we remove items?
568 * Answer is to NULL it first to prevent modules from doing any actions on the list at all
572 /* Remove the session from the active list */
576 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
586 * Terminate another session.
587 * (This could justifiably be moved out of sysdep.c because it
588 * no longer does anything that is system-dependent.)
590 void kill_session(int session_to_kill) {
593 begin_critical_section(S_SESSION_TABLE);
594 for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
595 if (ptr->cs_pid == session_to_kill) {
599 end_critical_section(S_SESSION_TABLE);
603 * Purge all sessions which have the 'kill_me' flag set.
604 * This function has code to prevent it from running more than once every
605 * few seconds, because running it after every single unbind would waste a lot
606 * of CPU time and keep the context list locked too much. To force it to run
607 * anyway, set "force" to nonzero.
609 void dead_session_purge(int force) {
610 CitContext *ptr, *ptr2; /* general-purpose utility pointer */
611 CitContext *rem = NULL; /* list of sessions to be destroyed */
614 if ( (time(NULL) - last_purge) < 5 ) {
615 return; /* Too soon, go away */
620 if (try_critical_section(S_SESSION_TABLE))
628 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
629 /* Remove the session from the active list */
631 ptr2->prev->next = ptr2->next;
634 ContextList = ptr2->next;
637 ptr2->next->prev = ptr2->prev;
641 /* And put it on our to-be-destroyed list */
646 end_critical_section(S_SESSION_TABLE);
648 /* Now that we no longer have the session list locked, we can take
649 * our time and destroy any sessions on the to-be-killed list, which
650 * is allocated privately on this thread's stack.
652 while (rem != NULL) {
653 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
666 * masterCC is the context we use when not attached to a session. This
667 * function initializes it.
669 void InitializeMasterCC(void) {
670 memset(&masterCC, 0, sizeof( CitContext));
671 masterCC.internal_pgm = 1;
680 * Set the "async waiting" flag for a session, if applicable
682 void set_async_waiting(struct CitContext *ccptr)
684 CtdlLogPrintf(CTDL_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
685 if (ccptr->is_async) {
686 ccptr->async_waiting++;
687 if (ccptr->state == CON_IDLE) {
688 ccptr->state = CON_READY;