c7902af980ad2fb743d8927f7529b3074e72fbfa
[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  * See COPYING for copyright information.
6  *
7  * Here's where we (hopefully) have all the code that manipulates contexts.
8  *
9  */
10
11 #include "sysdep.h"
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <stdio.h>
15 #include <fcntl.h>
16 #include <ctype.h>
17 #include <signal.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/wait.h>
21 #include <sys/socket.h>
22 #include <syslog.h>
23 #include <sys/syslog.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35
36 #include <limits.h>
37 #include <sys/resource.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <arpa/inet.h>
41 #include <netdb.h>
42 #include <sys/un.h>
43 #include <string.h>
44 #include <pwd.h>
45 #include <errno.h>
46 #include <stdarg.h>
47 #include <grp.h>
48 #include <libcitadel.h>
49 #include "citadel.h"
50 #include "server.h"
51 #include "sysdep_decls.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "database.h"
56 #include "housekeeping.h"
57 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
58 #include "ecrash.h"
59
60 #ifdef HAVE_SYS_SELECT_H
61 #include <sys/select.h>
62 #endif
63
64 #ifndef HAVE_SNPRINTF
65 #include "snprintf.h"
66 #endif
67
68 #include "ctdl_module.h"
69 #include "threads.h"
70 #include "user_ops.h"
71 #include "control.h"
72
73
74
75 citthread_key_t MyConKey;                               /* TSD key for MyContext() */
76
77
78 CitContext masterCC;
79 CitContext *ContextList = NULL;
80
81 time_t last_purge = 0;                          /* Last dead session purge */
82 int num_sessions = 0;                           /* Current number of sessions */
83
84 /* Flag for single user mode */
85 static int want_single_user = 0;
86
87 /* Try to go single user */
88
89 int CtdlTrySingleUser(void)
90 {
91         int can_do = 0;
92         
93         begin_critical_section(S_SINGLE_USER);
94         if (want_single_user)
95                 can_do = 0;
96         else
97         {
98                 can_do = 1;
99                 want_single_user = 1;
100         }
101         end_critical_section(S_SINGLE_USER);
102         return can_do;
103 }
104
105 void CtdlEndSingleUser(void)
106 {
107         begin_critical_section(S_SINGLE_USER);
108         want_single_user = 0;
109         end_critical_section(S_SINGLE_USER);
110 }
111
112
113 int CtdlWantSingleUser(void)
114 {
115         return want_single_user;
116 }
117
118 int CtdlIsSingleUser(void)
119 {
120         if (want_single_user)
121         {
122                 /* check for only one context here */
123                 if (num_sessions == 1)
124                         return TRUE;
125         }
126         return FALSE;
127 }
128
129
130
131
132 /*
133  * Check to see if the user who we just sent mail to is logged in.  If yes,
134  * bump the 'new mail' counter for their session.  That enables them to
135  * receive a new mail notification without having to hit the database.
136  */
137 void BumpNewMailCounter(long which_user) 
138 {
139         CtdlBumpNewMailCounter(which_user);
140 }
141
142 void CtdlBumpNewMailCounter(long which_user)
143 {
144         CitContext *ptr;
145
146         begin_critical_section(S_SESSION_TABLE);
147
148         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
149                 if (ptr->user.usernum == which_user) {
150                         ptr->newmail += 1;
151                 }
152         }
153
154         end_critical_section(S_SESSION_TABLE);
155 }
156
157
158 /*
159  * Check to see if a user is currently logged in
160  * Take care with what you do as a result of this test.
161  * The user may not have been logged in when this function was called BUT
162  * because of threading the user might be logged in before you test the result.
163  */
164 int CtdlIsUserLoggedIn (char *user_name)
165 {
166         CitContext *cptr;
167         int ret = 0;
168
169         begin_critical_section (S_SESSION_TABLE);
170         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
171                 if (!strcasecmp(cptr->user.fullname, user_name)) {
172                         ret = 1;
173                         break;
174                 }
175         }
176         end_critical_section(S_SESSION_TABLE);
177         return ret;
178 }
179
180
181
182 /*
183  * Check to see if a user is currently logged in.
184  * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
185  * Take care with what you do as a result of this test.
186  * The user may not have been logged in when this function was called BUT
187  * because of threading the user might be logged in before you test the result.
188  */
189 int CtdlIsUserLoggedInByNum (long usernum)
190 {
191         CitContext *cptr;
192         int ret = 0;
193
194         begin_critical_section(S_SESSION_TABLE);
195         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
196                 if (cptr->user.usernum == usernum) {
197                         ret = 1;
198                 }
199         }
200         end_critical_section(S_SESSION_TABLE);
201         return ret;
202 }
203
204
205
206 /*
207  * Return a pointer to the CitContext structure bound to the thread which
208  * called this function.  If there's no such binding (for example, if it's
209  * called by the housekeeper thread) then a generic 'master' CC is returned.
210  *
211  * This function is used *VERY* frequently and must be kept small.
212  */
213 CitContext *MyContext(void) {
214
215         register CitContext *c;
216
217         return ((c = (CitContext *) citthread_getspecific(MyConKey),
218                 c == NULL) ? &masterCC : c
219         );
220 }
221
222
223
224
225 /*
226  * Terminate a session.
227  */
228 void RemoveContext (CitContext *con)
229 {
230         if (con==NULL) {
231                 CtdlLogPrintf(CTDL_ERR,
232                         "WARNING: RemoveContext() called with NULL!\n");
233                 return;
234         }
235         CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
236
237         /* Run any cleanup routines registered by loadable modules.
238          * Note: We have to "become_session()" because the cleanup functions
239          *       might make references to "CC" assuming it's the right one.
240          */
241         become_session(con);
242         logout();
243         PerformSessionHooks(EVT_STOP);
244         become_session(NULL);
245
246         CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
247
248         /* If the client is still connected, blow 'em away. */
249         CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
250         close(con->client_socket);
251
252         /* If using AUTHMODE_LDAP, free the DN */
253         if (con->ldap_dn) {
254                 free(con->ldap_dn);
255                 con->ldap_dn = NULL;
256         }
257
258         CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
259 }
260
261
262
263
264 /*
265  * Initialize a new context and place it in the list.  The session number
266  * used to be the PID (which is why it's called cs_pid), but that was when we
267  * had one process per session.  Now we just assign them sequentially, starting
268  * at 1 (don't change it to 0 because masterCC uses 0).
269  */
270 CitContext *CreateNewContext(void) {
271         CitContext *me;
272         static int next_pid = 0;
273
274         me = (CitContext *) malloc(sizeof(CitContext));
275         if (me == NULL) {
276                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
277                 return NULL;
278         }
279         memset(me, 0, sizeof(CitContext));
280         
281         /* Give the contaxt a name. Hopefully makes it easier to track */
282         strcpy (me->user.fullname, "SYS_notauth");
283         
284         /* The new context will be created already in the CON_EXECUTING state
285          * in order to prevent another thread from grabbing it while it's
286          * being set up.
287          */
288         me->state = CON_EXECUTING;
289         /*
290          * Generate a unique session number and insert this context into
291          * the list.
292          */
293         begin_critical_section(S_SESSION_TABLE);
294         me->cs_pid = ++next_pid;
295         me->prev = NULL;
296         me->next = ContextList;
297         ContextList = me;
298         if (me->next != NULL) {
299                 me->next->prev = me;
300         }
301         ++num_sessions;
302         end_critical_section(S_SESSION_TABLE);
303         return (me);
304 }
305
306
307 CitContext *CtdlGetContextArray(int *count)
308 {
309         int nContexts, i;
310         CitContext *nptr, *cptr;
311         
312         nContexts = num_sessions;
313         nptr = malloc(sizeof(CitContext) * nContexts);
314         if (!nptr)
315                 return NULL;
316         begin_critical_section(S_SESSION_TABLE);
317         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
318                 memcpy(&nptr[i], cptr, sizeof (CitContext));
319         end_critical_section (S_SESSION_TABLE);
320         
321         *count = i;
322         return nptr;
323 }
324
325
326
327 /**
328  * This function fills in a context and its user field correctly
329  * Then creates/loads that user
330  */
331 void CtdlFillSystemContext(CitContext *context, char *name)
332 {
333         char sysname[USERNAME_SIZE];
334
335         memset(context, 0, sizeof(CitContext));
336         context->internal_pgm = 1;
337         context->cs_pid = 0;
338         strcpy (sysname, "SYS_");
339         strcat (sysname, name);
340         /* internal_create_user has the side effect of loading the user regardless of wether they
341          * already existed or needed to be created
342          */
343         internal_create_user (sysname, &(context->user), -1) ;
344         
345         /* Check to see if the system user needs upgrading */
346         if (context->user.usernum == 0)
347         {       /* old system user with number 0, upgrade it */
348                 context->user.usernum = get_new_user_number();
349                 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
350                 /* add user to the database */
351                 CtdlPutUser(&(context->user));
352                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
353         }
354 }
355
356 /*
357  * Cleanup any contexts that are left lying around
358  */
359 void context_cleanup(void)
360 {
361         CitContext *ptr = NULL;
362         CitContext *rem = NULL;
363
364         /*
365          * Clean up the contexts.
366          * There are no threads so no critical_section stuff is needed.
367          */
368         ptr = ContextList;
369         
370         /* We need to update the ContextList because some modules may want to itterate it
371          * Question is should we NULL it before iterating here or should we just keep updating it
372          * as we remove items?
373          *
374          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
375          */
376         ContextList=NULL;
377         while (ptr != NULL){
378                 /* Remove the session from the active list */
379                 rem = ptr->next;
380                 --num_sessions;
381                 
382                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
383                 RemoveContext(ptr);
384                 free (ptr);
385                 ptr = rem;
386         }
387 }
388
389
390
391 /*
392  * Terminate another session.
393  * (This could justifiably be moved out of sysdep.c because it
394  * no longer does anything that is system-dependent.)
395  */
396 void kill_session(int session_to_kill) {
397         CitContext *ptr;
398
399         begin_critical_section(S_SESSION_TABLE);
400         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
401                 if (ptr->cs_pid == session_to_kill) {
402                         ptr->kill_me = 1;
403                 }
404         }
405         end_critical_section(S_SESSION_TABLE);
406 }
407
408 /*
409  * Purge all sessions which have the 'kill_me' flag set.
410  * This function has code to prevent it from running more than once every
411  * few seconds, because running it after every single unbind would waste a lot
412  * of CPU time and keep the context list locked too much.  To force it to run
413  * anyway, set "force" to nonzero.
414  */
415 void dead_session_purge(int force) {
416         CitContext *ptr, *ptr2;         /* general-purpose utility pointer */
417         CitContext *rem = NULL; /* list of sessions to be destroyed */
418         
419         if (force == 0) {
420                 if ( (time(NULL) - last_purge) < 5 ) {
421                         return; /* Too soon, go away */
422                 }
423         }
424         time(&last_purge);
425
426         if (try_critical_section(S_SESSION_TABLE))
427                 return;
428                 
429         ptr = ContextList;
430         while (ptr) {
431                 ptr2 = ptr;
432                 ptr = ptr->next;
433                 
434                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
435                         /* Remove the session from the active list */
436                         if (ptr2->prev) {
437                                 ptr2->prev->next = ptr2->next;
438                         }
439                         else {
440                                 ContextList = ptr2->next;
441                         }
442                         if (ptr2->next) {
443                                 ptr2->next->prev = ptr2->prev;
444                         }
445
446                         --num_sessions;
447                         /* And put it on our to-be-destroyed list */
448                         ptr2->next = rem;
449                         rem = ptr2;
450                 }
451         }
452         end_critical_section(S_SESSION_TABLE);
453
454         /* Now that we no longer have the session list locked, we can take
455          * our time and destroy any sessions on the to-be-killed list, which
456          * is allocated privately on this thread's stack.
457          */
458         while (rem != NULL) {
459                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
460                 RemoveContext(rem);
461                 ptr = rem;
462                 rem = rem->next;
463                 free(ptr);
464         }
465 }
466
467
468
469
470
471 /*
472  * masterCC is the context we use when not attached to a session.  This
473  * function initializes it.
474  */
475 void InitializeMasterCC(void) {
476         memset(&masterCC, 0, sizeof( CitContext));
477         masterCC.internal_pgm = 1;
478         masterCC.cs_pid = 0;
479 }
480
481
482
483
484 /*
485  * Bind a thread to a context.  (It's inline merely to speed things up.)
486  */
487 INLINE void become_session(CitContext *which_con) {
488         citthread_setspecific(MyConKey, (void *)which_con );
489 }
490
491
492