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