Back to index

citadel  8.12
context.c
Go to the documentation of this file.
00001 /*
00002  * Citadel context management stuff.
00003  * Here's where we (hopefully) have all the code that manipulates contexts.
00004  *
00005  * Copyright (c) 1987-2011 by the citadel.org team
00006  *
00007  * This program is open source software; you can redistribute it and/or modify
00008  * it under the terms of the GNU General Public License as published by
00009  * the Free Software Foundation; either version 3 of the License, or
00010  * (at your option) any later version.
00011  *
00012  * This program is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  * GNU General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the Free Software
00019  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
00020  */
00021 
00022 #include "sysdep.h"
00023 #include <stdlib.h>
00024 #include <unistd.h>
00025 #include <stdio.h>
00026 #include <fcntl.h>
00027 #include <ctype.h>
00028 #include <signal.h>
00029 #include <sys/types.h>
00030 #include <sys/stat.h>
00031 #include <sys/wait.h>
00032 #include <sys/socket.h>
00033 #include <syslog.h>
00034 #include <sys/syslog.h>
00035 /*
00036 #include <sys/syscall.h>
00037 */
00038 
00039 #if TIME_WITH_SYS_TIME
00040 # include <sys/time.h>
00041 # include <time.h>
00042 #else
00043 # if HAVE_SYS_TIME_H
00044 #  include <sys/time.h>
00045 # else
00046 #  include <time.h>
00047 # endif
00048 #endif
00049 
00050 #include <limits.h>
00051 #include <sys/resource.h>
00052 #include <netinet/in.h>
00053 #include <netinet/tcp.h>
00054 #include <arpa/inet.h>
00055 #include <netdb.h>
00056 #include <sys/un.h>
00057 #include <string.h>
00058 #include <pwd.h>
00059 #include <errno.h>
00060 #include <stdarg.h>
00061 #include <grp.h>
00062 #include <libcitadel.h>
00063 #include "citadel.h"
00064 #include "server.h"
00065 #include "sysdep_decls.h"
00066 #include "citserver.h"
00067 #include "support.h"
00068 #include "config.h"
00069 #include "database.h"
00070 #include "housekeeping.h"
00071 #include "modules/crypto/serv_crypto.h"   /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
00072 #include "ecrash.h"
00073 
00074 #ifdef HAVE_SYS_SELECT_H
00075 #include <sys/select.h>
00076 #endif
00077 
00078 #ifndef HAVE_SNPRINTF
00079 #include "snprintf.h"
00080 #endif
00081 
00082 #include "ctdl_module.h"
00083 #include "threads.h"
00084 #include "user_ops.h"
00085 #include "control.h"
00086 
00087 int DebugSession = 0;
00088 
00089 pthread_key_t MyConKey;                          /* TSD key for MyContext() */
00090 
00091 
00092 CitContext masterCC;
00093 CitContext *ContextList = NULL;
00094 
00095 time_t last_purge = 0;                           /* Last dead session purge */
00096 int num_sessions = 0;                            /* Current number of sessions */
00097 
00098 /* Flag for single user mode */
00099 static int want_single_user = 0;
00100 
00101 /* Try to go single user */
00102 
00103 int CtdlTrySingleUser(void)
00104 {
00105        int can_do = 0;
00106        
00107        begin_critical_section(S_SINGLE_USER);
00108        if (want_single_user)
00109               can_do = 0;
00110        else
00111        {
00112               can_do = 1;
00113               want_single_user = 1;
00114        }
00115        end_critical_section(S_SINGLE_USER);
00116        return can_do;
00117 }
00118 
00119 void CtdlEndSingleUser(void)
00120 {
00121        begin_critical_section(S_SINGLE_USER);
00122        want_single_user = 0;
00123        end_critical_section(S_SINGLE_USER);
00124 }
00125 
00126 
00127 int CtdlWantSingleUser(void)
00128 {
00129        return want_single_user;
00130 }
00131 
00132 int CtdlIsSingleUser(void)
00133 {
00134        if (want_single_user)
00135        {
00136               /* check for only one context here */
00137               if (num_sessions == 1)
00138                      return TRUE;
00139        }
00140        return FALSE;
00141 }
00142 
00143 
00144 
00145 
00146 
00147 /*
00148  * Locate a context by its session number and terminate it if the user is able.
00149  * User can NOT terminate their current session.
00150  * User CAN terminate any other session that has them logged in.
00151  * Aide CAN terminate any session except the current one.
00152  */
00153 int CtdlTerminateOtherSession (int session_num)
00154 {
00155        int ret = 0;
00156        CitContext *ccptr;
00157 
00158        if (session_num == CC->cs_pid) {
00159               return TERM_NOTALLOWED;
00160        }
00161 
00162        CONM_syslog(LOG_DEBUG, "Locating session to kill\n");
00163        begin_critical_section(S_SESSION_TABLE);
00164        for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
00165               if (session_num == ccptr->cs_pid) {
00166                      ret |= TERM_FOUND;
00167                      if ((ccptr->user.usernum == CC->user.usernum)
00168                         || (CC->user.axlevel >= AxAideU)) {
00169                             ret |= TERM_ALLOWED;
00170                             ccptr->kill_me = KILLME_ADMIN_TERMINATE;
00171                      }
00172               }
00173        }
00174        end_critical_section(S_SESSION_TABLE);
00175        return ret;
00176 }
00177 
00178 
00179 
00180 /*
00181  * Check to see if the user who we just sent mail to is logged in.  If yes,
00182  * bump the 'new mail' counter for their session.  That enables them to
00183  * receive a new mail notification without having to hit the database.
00184  */
00185 void BumpNewMailCounter(long which_user) 
00186 {
00187        CtdlBumpNewMailCounter(which_user);
00188 }
00189 
00190 void CtdlBumpNewMailCounter(long which_user)
00191 {
00192        CitContext *ptr;
00193 
00194        begin_critical_section(S_SESSION_TABLE);
00195 
00196        for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
00197               if (ptr->user.usernum == which_user) {
00198                      ptr->newmail += 1;
00199               }
00200        }
00201 
00202        end_critical_section(S_SESSION_TABLE);
00203 }
00204 
00205 
00206 /*
00207  * Check to see if a user is currently logged in
00208  * Take care with what you do as a result of this test.
00209  * The user may not have been logged in when this function was called BUT
00210  * because of threading the user might be logged in before you test the result.
00211  */
00212 int CtdlIsUserLoggedIn (char *user_name)
00213 {
00214        CitContext *cptr;
00215        int ret = 0;
00216 
00217        begin_critical_section (S_SESSION_TABLE);
00218        for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
00219               if (!strcasecmp(cptr->user.fullname, user_name)) {
00220                      ret = 1;
00221                      break;
00222               }
00223        }
00224        end_critical_section(S_SESSION_TABLE);
00225        return ret;
00226 }
00227 
00228 
00229 
00230 /*
00231  * Check to see if a user is currently logged in.
00232  * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
00233  * Take care with what you do as a result of this test.
00234  * The user may not have been logged in when this function was called BUT
00235  * because of threading the user might be logged in before you test the result.
00236  */
00237 int CtdlIsUserLoggedInByNum (long usernum)
00238 {
00239        CitContext *cptr;
00240        int ret = 0;
00241 
00242        begin_critical_section(S_SESSION_TABLE);
00243        for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
00244               if (cptr->user.usernum == usernum) {
00245                      ret = 1;
00246               }
00247        }
00248        end_critical_section(S_SESSION_TABLE);
00249        return ret;
00250 }
00251 
00252 
00253 
00254 /*
00255  * Return a pointer to the CitContext structure bound to the thread which
00256  * called this function.  If there's no such binding (for example, if it's
00257  * called by the housekeeper thread) then a generic 'master' CC is returned.
00258  *
00259  * This function is used *VERY* frequently and must be kept small.
00260  */
00261 CitContext *MyContext(void) {
00262        register CitContext *c;
00263        return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
00264 }
00265 
00266 
00267 
00268 
00269 /*
00270  * Terminate idle sessions.  This function pounds through the session table
00271  * comparing the current time to each session's time-of-last-command.  If an
00272  * idle session is found it is terminated, then the search restarts at the
00273  * beginning because the pointer to our place in the list becomes invalid.
00274  */
00275 void terminate_idle_sessions(void)
00276 {
00277        CitContext *ccptr;
00278        time_t now;
00279        int killed = 0;
00280        int longrunners = 0;
00281 
00282        now = time(NULL);
00283        begin_critical_section(S_SESSION_TABLE);
00284        for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
00285               if (
00286                      (ccptr != CC)
00287                      && (config.c_sleeping > 0)
00288                      && (now - (ccptr->lastcmd) > config.c_sleeping)
00289               ) {
00290                      if (!ccptr->dont_term) {
00291                             ccptr->kill_me = KILLME_IDLE;
00292                             ++killed;
00293                      }
00294                      else {
00295                             ++longrunners;
00296                      }
00297               }
00298        }
00299        end_critical_section(S_SESSION_TABLE);
00300        if (killed > 0)
00301               CON_syslog(LOG_INFO, "Scheduled %d idle sessions for termination\n", killed);
00302        if (longrunners > 0)
00303               CON_syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
00304 }
00305 
00306 
00307 /*
00308  * During shutdown, close the sockets of any sessions still connected.
00309  */
00310 void terminate_all_sessions(void)
00311 {
00312        CitContext *ccptr;
00313        int killed = 0;
00314 
00315        begin_critical_section(S_SESSION_TABLE);
00316        for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
00317               if (ccptr->client_socket != -1)
00318               {
00319                      CON_syslog(LOG_INFO, "terminate_all_sessions() is murdering %s", ccptr->curr_user);
00320                      close(ccptr->client_socket);
00321                      ccptr->client_socket = -1;
00322                      killed++;
00323               }
00324        }
00325        end_critical_section(S_SESSION_TABLE);
00326        if (killed > 0) {
00327               CON_syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
00328        }
00329 }
00330 
00331 
00332 
00333 /*
00334  * Terminate a session.
00335  */
00336 void RemoveContext (CitContext *con)
00337 {
00338        const char *c;
00339        if (con == NULL) {
00340               CONM_syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
00341               return;
00342        }
00343        c = con->ServiceName;
00344        if (c == NULL) {
00345               c = "WTF?";
00346        }
00347        CON_syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
00349 
00350        /* Run any cleanup routines registered by loadable modules.
00351         * Note: We have to "become_session()" because the cleanup functions
00352         *       might make references to "CC" assuming it's the right one.
00353         */
00354        become_session(con);
00355        CtdlUserLogout();
00356        PerformSessionHooks(EVT_STOP);
00357        client_close();                           /* If the client is still connected, blow 'em away. */
00358        become_session(NULL);
00359 
00360        CON_syslog(LOG_NOTICE, "[%3d]SRV[%s] Session ended.", con->cs_pid, c);
00361 
00362        /* 
00363         * If the client is still connected, blow 'em away. 
00364         * if the socket is 0 or -1, its already gone or was never there.
00365         */
00366        if (con->client_socket > 0)
00367        {
00368               CON_syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
00369               close(con->client_socket);
00370        }
00371 
00372        /* If using AUTHMODE_LDAP, free the DN */
00373        if (con->ldap_dn) {
00374               free(con->ldap_dn);
00375               con->ldap_dn = NULL;
00376        }
00377        FreeStrBuf(&con->StatusMessage);
00378        FreeStrBuf(&con->MigrateBuf);
00379        FreeStrBuf(&con->RecvBuf.Buf);
00380        if (con->cached_msglist) {
00381               free(con->cached_msglist);
00382        }
00383 
00384        CONM_syslog(LOG_DEBUG, "Done with RemoveContext()");
00385 }
00386 
00387 
00388 
00389 /*
00390  * Initialize a new context and place it in the list.  The session number
00391  * used to be the PID (which is why it's called cs_pid), but that was when we
00392  * had one process per session.  Now we just assign them sequentially, starting
00393  * at 1 (don't change it to 0 because masterCC uses 0).
00394  */
00395 CitContext *CreateNewContext(void) {
00396        CitContext *me;
00397        static int next_pid = 0;
00398 
00399        me = (CitContext *) malloc(sizeof(CitContext));
00400        if (me == NULL) {
00401               CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
00402               return NULL;
00403        }
00404        memset(me, 0, sizeof(CitContext));
00405 
00406        /* Give the context a name. Hopefully makes it easier to track */
00407        strcpy (me->user.fullname, "SYS_notauth");
00408        
00409        /* The new context will be created already in the CON_EXECUTING state
00410         * in order to prevent another thread from grabbing it while it's
00411         * being set up.
00412         */
00413        me->state = CON_EXECUTING;
00414        /*
00415         * Generate a unique session number and insert this context into
00416         * the list.
00417         */
00418        me->MigrateBuf = NewStrBuf();
00419 
00420        me->RecvBuf.Buf = NewStrBuf();
00421 
00422        me->lastcmd = time(NULL);   /* set lastcmd to now to prevent idle timer infanticide TODO: if we have a valid IO, use that to set the timer. */
00423 
00424 
00425        begin_critical_section(S_SESSION_TABLE);
00426        me->cs_pid = ++next_pid;
00427        me->prev = NULL;
00428        me->next = ContextList;
00429        ContextList = me;
00430        if (me->next != NULL) {
00431               me->next->prev = me;
00432        }
00433        ++num_sessions;
00434        end_critical_section(S_SESSION_TABLE);
00435        return (me);
00436 }
00437 
00438 
00439 /*
00440  * Initialize a new context and place it in the list.  The session number
00441  * used to be the PID (which is why it's called cs_pid), but that was when we
00442  * had one process per session.  Now we just assign them sequentially, starting
00443  * at 1 (don't change it to 0 because masterCC uses 0).
00444  */
00445 CitContext *CloneContext(CitContext *CloneMe) {
00446        CitContext *me;
00447        static int next_pid = 0;
00448 
00449        me = (CitContext *) malloc(sizeof(CitContext));
00450        if (me == NULL) {
00451               CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
00452               return NULL;
00453        }
00454        memcpy(me, CloneMe, sizeof(CitContext));
00455 
00456        memset(&me->RecvBuf, 0, sizeof(IOBuffer));
00457        memset(&me->SendBuf, 0, sizeof(IOBuffer));
00458        memset(&me->SBuf, 0, sizeof(IOBuffer));
00459        me->MigrateBuf = NULL;
00460        me->sMigrateBuf = NULL;
00461        me->redirect_buffer = NULL;
00462 #ifdef HAVE_OPENSSL
00463        me->ssl = NULL;
00464 #endif
00465 
00466        me->download_fp = NULL;
00467        me->upload_fp = NULL;
00469        me->ma = NULL;
00470        me->openid_data = NULL;
00471        me->ldap_dn = NULL;
00472        me->session_specific_data = NULL;
00473 
00474        me->download_fp = NULL;
00475        me->upload_fp = NULL;
00476        me->client_socket = 0;
00477 
00478        me->MigrateBuf = NewStrBuf();
00479        me->RecvBuf.Buf = NewStrBuf();
00480        
00481        begin_critical_section(S_SESSION_TABLE);
00482        {
00483               me->cs_pid = ++next_pid;
00484               me->prev = NULL;
00485               me->next = ContextList;
00486               me->lastcmd = time(NULL);   /* set lastcmd to now to prevent idle timer infanticide */
00487               ContextList = me;
00488               if (me->next != NULL) {
00489                      me->next->prev = me;
00490               }
00491               ++num_sessions;
00492        }
00493        end_critical_section(S_SESSION_TABLE);
00494        return (me);
00495 }
00496 
00497 
00498 /*
00499  * Return an array containing a copy of the context list.
00500  * This allows worker threads to perform "for each context" operations without
00501  * having to lock and traverse the live list.
00502  */
00503 CitContext *CtdlGetContextArray(int *count)
00504 {
00505        int nContexts, i;
00506        CitContext *nptr, *cptr;
00507        
00508        nContexts = num_sessions;
00509        nptr = malloc(sizeof(CitContext) * nContexts);
00510        if (!nptr) {
00511               *count = 0;
00512               return NULL;
00513        }
00514        begin_critical_section(S_SESSION_TABLE);
00515        for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
00516               memcpy(&nptr[i], cptr, sizeof (CitContext));
00517        }
00518        end_critical_section (S_SESSION_TABLE);
00519        
00520        *count = i;
00521        return nptr;
00522 }
00523 
00524 
00525 
00526 /*
00527  * This function fills in a context and its user field correctly
00528  * Then creates/loads that user
00529  */
00530 void CtdlFillSystemContext(CitContext *context, char *name)
00531 {
00532        char sysname[SIZ];
00533        long len;
00534 
00535        memset(context, 0, sizeof(CitContext));
00536        context->internal_pgm = 1;
00537        context->cs_pid = 0;
00538        strcpy (sysname, "SYS_");
00539        strcat (sysname, name);
00540        len = cutuserkey(sysname);
00541        memcpy(context->curr_user, sysname, len + 1);
00542        context->client_socket = (-1);
00543        context->state = CON_SYS;
00544        context->ServiceName = name;
00545 
00546        /* internal_create_user has the side effect of loading the user regardless of wether they
00547         * already existed or needed to be created
00548         */
00549        internal_create_user (sysname, len, &(context->user), -1) ;
00550        
00551        /* Check to see if the system user needs upgrading */
00552        if (context->user.usernum == 0)
00553        {      /* old system user with number 0, upgrade it */
00554               context->user.usernum = get_new_user_number();
00555               CON_syslog(LOG_INFO, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
00556               /* add user to the database */
00557               CtdlPutUser(&(context->user));
00558               cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
00559        }
00560 }
00561 
00562 
00563 /*
00564  * Cleanup any contexts that are left lying around
00565  */
00566 void context_cleanup(void)
00567 {
00568        CitContext *ptr = NULL;
00569        CitContext *rem = NULL;
00570 
00571        /*
00572         * Clean up the contexts.
00573         * There are no threads so no critical_section stuff is needed.
00574         */
00575        ptr = ContextList;
00576        
00577        /* We need to update the ContextList because some modules may want to itterate it
00578         * Question is should we NULL it before iterating here or should we just keep updating it
00579         * as we remove items?
00580         *
00581         * Answer is to NULL it first to prevent modules from doing any actions on the list at all
00582         */
00583        ContextList=NULL;
00584        while (ptr != NULL){
00585               /* Remove the session from the active list */
00586               rem = ptr->next;
00587               --num_sessions;
00588 
00589               CON_syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
00590               RemoveContext(ptr);
00591               free (ptr);
00592               ptr = rem;
00593        }
00594 }
00595 
00596 
00597 
00598 /*
00599  * Purge all sessions which have the 'kill_me' flag set.
00600  * This function has code to prevent it from running more than once every
00601  * few seconds, because running it after every single unbind would waste a lot
00602  * of CPU time and keep the context list locked too much.  To force it to run
00603  * anyway, set "force" to nonzero.
00604  */
00605 void dead_session_purge(int force) {
00606        CitContext *ptr, *ptr2;            /* general-purpose utility pointer */
00607        CitContext *rem = NULL;            /* list of sessions to be destroyed */
00608        
00609        if (force == 0) {
00610               if ( (time(NULL) - last_purge) < 5 ) {
00611                      return;       /* Too soon, go away */
00612               }
00613        }
00614        time(&last_purge);
00615 
00616        if (try_critical_section(S_SESSION_TABLE))
00617               return;
00618               
00619        ptr = ContextList;
00620        while (ptr) {
00621               ptr2 = ptr;
00622               ptr = ptr->next;
00623               
00624               if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
00625                      /* Remove the session from the active list */
00626                      if (ptr2->prev) {
00627                             ptr2->prev->next = ptr2->next;
00628                      }
00629                      else {
00630                             ContextList = ptr2->next;
00631                      }
00632                      if (ptr2->next) {
00633                             ptr2->next->prev = ptr2->prev;
00634                      }
00635 
00636                      --num_sessions;
00637                      /* And put it on our to-be-destroyed list */
00638                      ptr2->next = rem;
00639                      rem = ptr2;
00640               }
00641        }
00642        end_critical_section(S_SESSION_TABLE);
00643 
00644        /* Now that we no longer have the session list locked, we can take
00645         * our time and destroy any sessions on the to-be-killed list, which
00646         * is allocated privately on this thread's stack.
00647         */
00648        while (rem != NULL) {
00649               CON_syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
00650               RemoveContext(rem);
00651               ptr = rem;
00652               rem = rem->next;
00653               free(ptr);
00654        }
00655 }
00656 
00657 
00658 
00659 
00660 
00661 /*
00662  * masterCC is the context we use when not attached to a session.  This
00663  * function initializes it.
00664  */
00665 void InitializeMasterCC(void) {
00666        memset(&masterCC, 0, sizeof(struct CitContext));
00667        masterCC.internal_pgm = 1;
00668        masterCC.cs_pid = 0;
00669 }
00670 
00671 
00672 
00673 
00674 
00675 /*
00676  * Set the "async waiting" flag for a session, if applicable
00677  */
00678 void set_async_waiting(struct CitContext *ccptr)
00679 {
00680        CON_syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
00681        if (ccptr->is_async) {
00682               ccptr->async_waiting++;
00683               if (ccptr->state == CON_IDLE) {
00684                      ccptr->state = CON_READY;
00685               }
00686        }
00687 }
00688 
00689 
00690 void DebugSessionEnable(const int n)
00691 {
00692        DebugSession = n;
00693 }
00694 CTDL_MODULE_INIT(session)
00695 {
00696        if (!threading) {
00697               CtdlRegisterDebugFlagHook(HKEY("session"), DebugSessionEnable, &DebugSession);
00698        }
00699        return "session";
00700 }