off-by-one fix in siteconfig
[citadel.git] / citadel / context.c
1 /*
2  * Citadel context management stuff.
3  * Here's where we (hopefully) have all the code that manipulates contexts.
4  *
5  * Copyright (c) 1987-2011 by the citadel.org team
6  *
7  * This program is open source 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.
11  *
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.
16  *
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
20  */
21
22 #include "sysdep.h"
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <ctype.h>
28 #include <signal.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32 #include <sys/socket.h>
33 #include <syslog.h>
34 #include <sys/syslog.h>
35 /*
36 #include <sys/syscall.h>
37 */
38
39 #if TIME_WITH_SYS_TIME
40 # include <sys/time.h>
41 # include <time.h>
42 #else
43 # if HAVE_SYS_TIME_H
44 #  include <sys/time.h>
45 # else
46 #  include <time.h>
47 # endif
48 #endif
49
50 #include <limits.h>
51 #include <sys/resource.h>
52 #include <netinet/in.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
55 #include <netdb.h>
56 #include <sys/un.h>
57 #include <string.h>
58 #include <pwd.h>
59 #include <errno.h>
60 #include <stdarg.h>
61 #include <grp.h>
62 #include <libcitadel.h>
63 #include "citadel.h"
64 #include "server.h"
65 #include "sysdep_decls.h"
66 #include "citserver.h"
67 #include "support.h"
68 #include "config.h"
69 #include "database.h"
70 #include "housekeeping.h"
71 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
72 #include "ecrash.h"
73
74 #ifdef HAVE_SYS_SELECT_H
75 #include <sys/select.h>
76 #endif
77
78 #ifndef HAVE_SNPRINTF
79 #include "snprintf.h"
80 #endif
81
82 #include "ctdl_module.h"
83 #include "threads.h"
84 #include "user_ops.h"
85 #include "control.h"
86
87
88
89 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
90
91
92 CitContext masterCC;
93 CitContext *ContextList = NULL;
94
95 time_t last_purge = 0;                          /* Last dead session purge */
96 int num_sessions = 0;                           /* Current number of sessions */
97
98 /* Flag for single user mode */
99 static int want_single_user = 0;
100
101 /* Try to go single user */
102
103 int CtdlTrySingleUser(void)
104 {
105         int can_do = 0;
106         
107         begin_critical_section(S_SINGLE_USER);
108         if (want_single_user)
109                 can_do = 0;
110         else
111         {
112                 can_do = 1;
113                 want_single_user = 1;
114         }
115         end_critical_section(S_SINGLE_USER);
116         return can_do;
117 }
118
119 void CtdlEndSingleUser(void)
120 {
121         begin_critical_section(S_SINGLE_USER);
122         want_single_user = 0;
123         end_critical_section(S_SINGLE_USER);
124 }
125
126
127 int CtdlWantSingleUser(void)
128 {
129         return want_single_user;
130 }
131
132 int CtdlIsSingleUser(void)
133 {
134         if (want_single_user)
135         {
136                 /* check for only one context here */
137                 if (num_sessions == 1)
138                         return TRUE;
139         }
140         return FALSE;
141 }
142
143
144
145
146
147 /*
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.
152  */
153 int CtdlTerminateOtherSession (int session_num)
154 {
155         int ret = 0;
156         CitContext *ccptr;
157
158         if (session_num == CC->cs_pid) {
159                 return TERM_NOTALLOWED;
160         }
161
162         syslog(LOG_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) {
166                         ret |= TERM_FOUND;
167                         if ((ccptr->user.usernum == CC->user.usernum)
168                            || (CC->user.axlevel >= AxAideU)) {
169                                 ret |= TERM_ALLOWED;
170                                 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
171                         }
172                 }
173         }
174         end_critical_section(S_SESSION_TABLE);
175         return ret;
176 }
177
178
179
180 /*
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.
184  */
185 void BumpNewMailCounter(long which_user) 
186 {
187         CtdlBumpNewMailCounter(which_user);
188 }
189
190 void CtdlBumpNewMailCounter(long which_user)
191 {
192         CitContext *ptr;
193
194         begin_critical_section(S_SESSION_TABLE);
195
196         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
197                 if (ptr->user.usernum == which_user) {
198                         ptr->newmail += 1;
199                 }
200         }
201
202         end_critical_section(S_SESSION_TABLE);
203 }
204
205
206 /*
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.
211  */
212 int CtdlIsUserLoggedIn (char *user_name)
213 {
214         CitContext *cptr;
215         int ret = 0;
216
217         begin_critical_section (S_SESSION_TABLE);
218         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
219                 if (!strcasecmp(cptr->user.fullname, user_name)) {
220                         ret = 1;
221                         break;
222                 }
223         }
224         end_critical_section(S_SESSION_TABLE);
225         return ret;
226 }
227
228
229
230 /*
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.
236  */
237 int CtdlIsUserLoggedInByNum (long usernum)
238 {
239         CitContext *cptr;
240         int ret = 0;
241
242         begin_critical_section(S_SESSION_TABLE);
243         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
244                 if (cptr->user.usernum == usernum) {
245                         ret = 1;
246                 }
247         }
248         end_critical_section(S_SESSION_TABLE);
249         return ret;
250 }
251
252
253
254 /*
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.
258  *
259  * This function is used *VERY* frequently and must be kept small.
260  */
261 CitContext *MyContext(void) {
262         register CitContext *c;
263         return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
264 }
265
266
267
268
269 /*
270  * Terminate idle sessions.  This function pounds through the session table
271  * comparing the current time to each session's time-of-last-command.  If an
272  * idle session is found it is terminated, then the search restarts at the
273  * beginning because the pointer to our place in the list becomes invalid.
274  */
275 void terminate_idle_sessions(void)
276 {
277         CitContext *ccptr;
278         time_t now;
279         int killed = 0;
280         int longrunners = 0;
281
282         now = time(NULL);
283         begin_critical_section(S_SESSION_TABLE);
284         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
285                 if (
286                         (ccptr != CC)
287                         && (config.c_sleeping > 0)
288                         && (now - (ccptr->lastcmd) > config.c_sleeping)
289                 ) {
290                         if (!ccptr->dont_term) {
291                                 ccptr->kill_me = KILLME_IDLE;
292                                 ++killed;
293                         }
294                         else {
295                                 ++longrunners;
296                         }
297                 }
298         }
299         end_critical_section(S_SESSION_TABLE);
300         if (killed > 0)
301                 syslog(LOG_INFO, "Terminated %d idle sessions", killed);
302         if (longrunners > 0)
303                 syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
304 }
305
306
307 /*
308  * During shutdown, close the sockets of any sessions still connected.
309  */
310 void terminate_all_sessions(void)
311 {
312         CitContext *ccptr;
313         int killed = 0;
314
315         begin_critical_section(S_SESSION_TABLE);
316         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
317                 if (ccptr->client_socket != -1)
318                 {
319                         syslog(LOG_INFO, "terminate_all_sessions() is murdering %s", ccptr->curr_user);
320                         close(ccptr->client_socket);
321                         ccptr->client_socket = -1;
322                         killed++;
323                 }
324         }
325         end_critical_section(S_SESSION_TABLE);
326         if (killed > 0) {
327                 syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
328         }
329 }
330
331
332
333 /*
334  * Terminate a session.
335  */
336 void RemoveContext (CitContext *con)
337 {
338         const char *c;
339         if (con == NULL) {
340                 syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
341                 return;
342         }
343         c = con->ServiceName;
344         if (c == NULL) {
345                 c = "WTF?";
346         }
347         syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
348         cit_backtrace();
349
350         /* Run any cleanup routines registered by loadable modules.
351          * Note: We have to "become_session()" because the cleanup functions
352          *       might make references to "CC" assuming it's the right one.
353          */
354         become_session(con);
355         CtdlUserLogout();
356         PerformSessionHooks(EVT_STOP);
357         client_close();                         /* If the client is still connected, blow 'em away. */
358         become_session(NULL);
359
360         syslog(LOG_NOTICE, "[%3d] Session ended.", con->cs_pid);
361
362         /* 
363          * If the client is still connected, blow 'em away. 
364          * if the socket is 0 or -1, its already gone or was never there.
365          */
366         if (con->client_socket > 0)
367         {
368                 syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
369                 close(con->client_socket);
370         }
371
372         /* If using AUTHMODE_LDAP, free the DN */
373         if (con->ldap_dn) {
374                 free(con->ldap_dn);
375                 con->ldap_dn = NULL;
376         }
377
378         FreeStrBuf(&con->MigrateBuf);
379         FreeStrBuf(&con->ReadBuf);
380         if (con->cached_msglist) {
381                 free(con->cached_msglist);
382         }
383
384         syslog(LOG_DEBUG, "Done with RemoveContext()");
385 }
386
387
388
389 /*
390  * Initialize a new context and place it in the list.  The session number
391  * used to be the PID (which is why it's called cs_pid), but that was when we
392  * had one process per session.  Now we just assign them sequentially, starting
393  * at 1 (don't change it to 0 because masterCC uses 0).
394  */
395 CitContext *CreateNewContext(void) {
396         CitContext *me;
397         static int next_pid = 0;
398
399         me = (CitContext *) malloc(sizeof(CitContext));
400         if (me == NULL) {
401                 syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
402                 return NULL;
403         }
404         memset(me, 0, sizeof(CitContext));
405
406         /* Give the context a name. Hopefully makes it easier to track */
407         strcpy (me->user.fullname, "SYS_notauth");
408         
409         /* The new context will be created already in the CON_EXECUTING state
410          * in order to prevent another thread from grabbing it while it's
411          * being set up.
412          */
413         me->state = CON_EXECUTING;
414         /*
415          * Generate a unique session number and insert this context into
416          * the list.
417          */
418         me->MigrateBuf = NewStrBuf();
419         me->ReadBuf = NewStrBuf();
420         me->lastcmd = time(NULL);       /* set lastcmd to now to prevent idle timer infanticide */
421
422         begin_critical_section(S_SESSION_TABLE);
423         me->cs_pid = ++next_pid;
424         me->prev = NULL;
425         me->next = ContextList;
426         ContextList = me;
427         if (me->next != NULL) {
428                 me->next->prev = me;
429         }
430         ++num_sessions;
431         end_critical_section(S_SESSION_TABLE);
432         return (me);
433 }
434
435
436 /*
437  * Return an array containing a copy of the context list.
438  * This allows worker threads to perform "for each context" operations without
439  * having to lock and traverse the live list.
440  */
441 CitContext *CtdlGetContextArray(int *count)
442 {
443         int nContexts, i;
444         CitContext *nptr, *cptr;
445         
446         nContexts = num_sessions;
447         nptr = malloc(sizeof(CitContext) * nContexts);
448         if (!nptr) {
449                 *count = 0;
450                 return NULL;
451         }
452         begin_critical_section(S_SESSION_TABLE);
453         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
454                 memcpy(&nptr[i], cptr, sizeof (CitContext));
455         }
456         end_critical_section (S_SESSION_TABLE);
457         
458         *count = i;
459         return nptr;
460 }
461
462
463 /*
464  * Cleanup any contexts that are left lying around
465  */
466 void context_cleanup(void)
467 {
468         CitContext *ptr = NULL;
469         CitContext *rem = NULL;
470
471         /*
472          * Clean up the contexts.
473          * There are no threads so no critical_section stuff is needed.
474          */
475         ptr = ContextList;
476         
477         /* We need to update the ContextList because some modules may want to itterate it
478          * Question is should we NULL it before iterating here or should we just keep updating it
479          * as we remove items?
480          *
481          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
482          */
483         ContextList=NULL;
484         while (ptr != NULL){
485                 /* Remove the session from the active list */
486                 rem = ptr->next;
487                 --num_sessions;
488                 
489                 syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
490                 RemoveContext(ptr);
491                 free (ptr);
492                 ptr = rem;
493         }
494 }
495
496
497
498 /*
499  * Purge all sessions which have the 'kill_me' flag set.
500  * This function has code to prevent it from running more than once every
501  * few seconds, because running it after every single unbind would waste a lot
502  * of CPU time and keep the context list locked too much.  To force it to run
503  * anyway, set "force" to nonzero.
504  */
505 void dead_session_purge(int force) {
506         CitContext *ptr, *ptr2;         /* general-purpose utility pointer */
507         CitContext *rem = NULL;         /* list of sessions to be destroyed */
508         
509         if (force == 0) {
510                 if ( (time(NULL) - last_purge) < 5 ) {
511                         return; /* Too soon, go away */
512                 }
513         }
514         time(&last_purge);
515
516         if (try_critical_section(S_SESSION_TABLE))
517                 return;
518                 
519         ptr = ContextList;
520         while (ptr) {
521                 ptr2 = ptr;
522                 ptr = ptr->next;
523                 
524                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
525                         /* Remove the session from the active list */
526                         if (ptr2->prev) {
527                                 ptr2->prev->next = ptr2->next;
528                         }
529                         else {
530                                 ContextList = ptr2->next;
531                         }
532                         if (ptr2->next) {
533                                 ptr2->next->prev = ptr2->prev;
534                         }
535
536                         --num_sessions;
537                         /* And put it on our to-be-destroyed list */
538                         ptr2->next = rem;
539                         rem = ptr2;
540                 }
541         }
542         end_critical_section(S_SESSION_TABLE);
543
544         /* Now that we no longer have the session list locked, we can take
545          * our time and destroy any sessions on the to-be-killed list, which
546          * is allocated privately on this thread's stack.
547          */
548         while (rem != NULL) {
549                 syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
550                 RemoveContext(rem);
551                 ptr = rem;
552                 rem = rem->next;
553                 free(ptr);
554         }
555 }
556
557
558
559
560
561 /*
562  * masterCC is the context we use when not attached to a session.  This
563  * function initializes it.
564  */
565 void InitializeMasterCC(void) {
566         memset(&masterCC, 0, sizeof(struct CitContext));
567         masterCC.internal_pgm = 1;
568         masterCC.cs_pid = 0;
569 }
570
571
572
573
574
575 /*
576  * Set the "async waiting" flag for a session, if applicable
577  */
578 void set_async_waiting(struct CitContext *ccptr)
579 {
580         syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
581         if (ccptr->is_async) {
582                 ccptr->async_waiting++;
583                 if (ccptr->state == CON_IDLE) {
584                         ccptr->state = CON_READY;
585                 }
586         }
587 }