* start migration to buffered I/O
[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 /*
134  * Locate a context by its session number and terminate it if the user is able.
135  * User can NOT terminate their current session.
136  * User CAN terminate any other session that has them logged in.
137  * Aide CAN terminate any session except the current one.
138  */
139 int CtdlTerminateOtherSession (int session_num)
140 {
141         int ret = 0;
142         CitContext *ccptr;
143
144         if (session_num == CC->cs_pid) {
145                 return TERM_NOTALLOWED;
146         }
147
148         CtdlLogPrintf(CTDL_DEBUG, "Locating session to kill\n");
149         begin_critical_section(S_SESSION_TABLE);
150         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
151                 if (session_num == ccptr->cs_pid) {
152                         ret |= TERM_FOUND;
153                         if ((ccptr->user.usernum == CC->user.usernum)
154                            || (CC->user.axlevel >= 6)) {
155                                 ret |= TERM_ALLOWED;
156                                 ccptr->kill_me = 1;
157                         }
158                 }
159         }
160         end_critical_section(S_SESSION_TABLE);
161         return ret;
162 }
163
164
165
166 /*
167  * Check to see if the user who we just sent mail to is logged in.  If yes,
168  * bump the 'new mail' counter for their session.  That enables them to
169  * receive a new mail notification without having to hit the database.
170  */
171 void BumpNewMailCounter(long which_user) 
172 {
173         CtdlBumpNewMailCounter(which_user);
174 }
175
176 void CtdlBumpNewMailCounter(long which_user)
177 {
178         CitContext *ptr;
179
180         begin_critical_section(S_SESSION_TABLE);
181
182         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
183                 if (ptr->user.usernum == which_user) {
184                         ptr->newmail += 1;
185                 }
186         }
187
188         end_critical_section(S_SESSION_TABLE);
189 }
190
191
192 /*
193  * Check to see if a user is currently logged in
194  * Take care with what you do as a result of this test.
195  * The user may not have been logged in when this function was called BUT
196  * because of threading the user might be logged in before you test the result.
197  */
198 int CtdlIsUserLoggedIn (char *user_name)
199 {
200         CitContext *cptr;
201         int ret = 0;
202
203         begin_critical_section (S_SESSION_TABLE);
204         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
205                 if (!strcasecmp(cptr->user.fullname, user_name)) {
206                         ret = 1;
207                         break;
208                 }
209         }
210         end_critical_section(S_SESSION_TABLE);
211         return ret;
212 }
213
214
215
216 /*
217  * Check to see if a user is currently logged in.
218  * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
219  * Take care with what you do as a result of this test.
220  * The user may not have been logged in when this function was called BUT
221  * because of threading the user might be logged in before you test the result.
222  */
223 int CtdlIsUserLoggedInByNum (long usernum)
224 {
225         CitContext *cptr;
226         int ret = 0;
227
228         begin_critical_section(S_SESSION_TABLE);
229         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
230                 if (cptr->user.usernum == usernum) {
231                         ret = 1;
232                 }
233         }
234         end_critical_section(S_SESSION_TABLE);
235         return ret;
236 }
237
238
239
240 /*
241  * Return a pointer to the CitContext structure bound to the thread which
242  * called this function.  If there's no such binding (for example, if it's
243  * called by the housekeeper thread) then a generic 'master' CC is returned.
244  *
245  * This function is used *VERY* frequently and must be kept small.
246  */
247 CitContext *MyContext(void) {
248
249         register CitContext *c;
250
251         return ((c = (CitContext *) citthread_getspecific(MyConKey),
252                 c == NULL) ? &masterCC : c
253         );
254 }
255
256
257
258
259 /*
260  * Terminate idle sessions.  This function pounds through the session table
261  * comparing the current time to each session's time-of-last-command.  If an
262  * idle session is found it is terminated, then the search restarts at the
263  * beginning because the pointer to our place in the list becomes invalid.
264  */
265 void terminate_idle_sessions(void)
266 {
267         CitContext *ccptr;
268         time_t now;
269         int session_to_kill;
270         int killed = 0;
271         int longrunners = 0;
272
273         now = time(NULL);
274         session_to_kill = 0;
275         begin_critical_section(S_SESSION_TABLE);
276         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
277                 if (  (ccptr!=CC)
278                 && (config.c_sleeping > 0)
279                 && (now - (ccptr->lastcmd) > config.c_sleeping) ) {
280                         if (!ccptr->dont_term) {
281                                 ccptr->kill_me = 1;
282                                 ++killed;
283                         }
284                         else 
285                                 longrunners ++;
286                 }
287         }
288         end_critical_section(S_SESSION_TABLE);
289         if (killed > 0)
290                 CtdlLogPrintf(CTDL_INFO, "Terminated %d idle sessions\n", killed);
291         if (longrunners > 0)
292                 CtdlLogPrintf(CTDL_INFO, "Didn't terminate %d protected idle sessions;\n", killed);
293 }
294
295
296
297 /*
298  * Terminate a session.
299  */
300 void RemoveContext (CitContext *con)
301 {
302         if (con==NULL) {
303                 CtdlLogPrintf(CTDL_ERR,
304                         "WARNING: RemoveContext() called with NULL!\n");
305                 return;
306         }
307         CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
308
309         /* Run any cleanup routines registered by loadable modules.
310          * Note: We have to "become_session()" because the cleanup functions
311          *       might make references to "CC" assuming it's the right one.
312          */
313         become_session(con);
314         CtdlUserLogout();
315         PerformSessionHooks(EVT_STOP);
316         become_session(NULL);
317
318         CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
319
320         /* If the client is still connected, blow 'em away. */
321         CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
322         close(con->client_socket);
323
324         /* If using AUTHMODE_LDAP, free the DN */
325         if (con->ldap_dn) {
326                 free(con->ldap_dn);
327                 con->ldap_dn = NULL;
328         }
329
330         FreeStrBuf(&con->MigrateBuf);
331         FreeStrBuf(&con->ReadBuf);
332         CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
333 }
334
335
336
337
338 /*
339  * Initialize a new context and place it in the list.  The session number
340  * used to be the PID (which is why it's called cs_pid), but that was when we
341  * had one process per session.  Now we just assign them sequentially, starting
342  * at 1 (don't change it to 0 because masterCC uses 0).
343  */
344 CitContext *CreateNewContext(void) {
345         CitContext *me;
346         static int next_pid = 0;
347
348         me = (CitContext *) malloc(sizeof(CitContext));
349         if (me == NULL) {
350                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
351                 return NULL;
352         }
353         memset(me, 0, sizeof(CitContext));
354         
355         /* Give the contaxt a name. Hopefully makes it easier to track */
356         strcpy (me->user.fullname, "SYS_notauth");
357         
358         /* The new context will be created already in the CON_EXECUTING state
359          * in order to prevent another thread from grabbing it while it's
360          * being set up.
361          */
362         me->state = CON_EXECUTING;
363         /*
364          * Generate a unique session number and insert this context into
365          * the list.
366          */
367         me->MigrateBuf = NewStrBuf();
368         me->ReadBuf = NewStrBuf();
369         begin_critical_section(S_SESSION_TABLE);
370         me->cs_pid = ++next_pid;
371         me->prev = NULL;
372         me->next = ContextList;
373         ContextList = me;
374         if (me->next != NULL) {
375                 me->next->prev = me;
376         }
377         ++num_sessions;
378         end_critical_section(S_SESSION_TABLE);
379         return (me);
380 }
381
382
383 CitContext *CtdlGetContextArray(int *count)
384 {
385         int nContexts, i;
386         CitContext *nptr, *cptr;
387         
388         nContexts = num_sessions;
389         nptr = malloc(sizeof(CitContext) * nContexts);
390         if (!nptr)
391                 return NULL;
392         begin_critical_section(S_SESSION_TABLE);
393         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
394                 memcpy(&nptr[i], cptr, sizeof (CitContext));
395         end_critical_section (S_SESSION_TABLE);
396         
397         *count = i;
398         return nptr;
399 }
400
401
402
403 /**
404  * This function fills in a context and its user field correctly
405  * Then creates/loads that user
406  */
407 void CtdlFillSystemContext(CitContext *context, char *name)
408 {
409         char sysname[USERNAME_SIZE];
410
411         memset(context, 0, sizeof(CitContext));
412         context->internal_pgm = 1;
413         context->cs_pid = 0;
414         strcpy (sysname, "SYS_");
415         strcat (sysname, name);
416         /* internal_create_user has the side effect of loading the user regardless of wether they
417          * already existed or needed to be created
418          */
419         internal_create_user (sysname, &(context->user), -1) ;
420         
421         /* Check to see if the system user needs upgrading */
422         if (context->user.usernum == 0)
423         {       /* old system user with number 0, upgrade it */
424                 context->user.usernum = get_new_user_number();
425                 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
426                 /* add user to the database */
427                 CtdlPutUser(&(context->user));
428                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
429         }
430 }
431
432 /*
433  * Cleanup any contexts that are left lying around
434  */
435 void context_cleanup(void)
436 {
437         CitContext *ptr = NULL;
438         CitContext *rem = NULL;
439
440         /*
441          * Clean up the contexts.
442          * There are no threads so no critical_section stuff is needed.
443          */
444         ptr = ContextList;
445         
446         /* We need to update the ContextList because some modules may want to itterate it
447          * Question is should we NULL it before iterating here or should we just keep updating it
448          * as we remove items?
449          *
450          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
451          */
452         ContextList=NULL;
453         while (ptr != NULL){
454                 /* Remove the session from the active list */
455                 rem = ptr->next;
456                 --num_sessions;
457                 
458                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
459                 RemoveContext(ptr);
460                 free (ptr);
461                 ptr = rem;
462         }
463 }
464
465
466
467 /*
468  * Terminate another session.
469  * (This could justifiably be moved out of sysdep.c because it
470  * no longer does anything that is system-dependent.)
471  */
472 void kill_session(int session_to_kill) {
473         CitContext *ptr;
474
475         begin_critical_section(S_SESSION_TABLE);
476         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
477                 if (ptr->cs_pid == session_to_kill) {
478                         ptr->kill_me = 1;
479                 }
480         }
481         end_critical_section(S_SESSION_TABLE);
482 }
483
484 /*
485  * Purge all sessions which have the 'kill_me' flag set.
486  * This function has code to prevent it from running more than once every
487  * few seconds, because running it after every single unbind would waste a lot
488  * of CPU time and keep the context list locked too much.  To force it to run
489  * anyway, set "force" to nonzero.
490  */
491 void dead_session_purge(int force) {
492         CitContext *ptr, *ptr2;         /* general-purpose utility pointer */
493         CitContext *rem = NULL; /* list of sessions to be destroyed */
494         
495         if (force == 0) {
496                 if ( (time(NULL) - last_purge) < 5 ) {
497                         return; /* Too soon, go away */
498                 }
499         }
500         time(&last_purge);
501
502         if (try_critical_section(S_SESSION_TABLE))
503                 return;
504                 
505         ptr = ContextList;
506         while (ptr) {
507                 ptr2 = ptr;
508                 ptr = ptr->next;
509                 
510                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
511                         /* Remove the session from the active list */
512                         if (ptr2->prev) {
513                                 ptr2->prev->next = ptr2->next;
514                         }
515                         else {
516                                 ContextList = ptr2->next;
517                         }
518                         if (ptr2->next) {
519                                 ptr2->next->prev = ptr2->prev;
520                         }
521
522                         --num_sessions;
523                         /* And put it on our to-be-destroyed list */
524                         ptr2->next = rem;
525                         rem = ptr2;
526                 }
527         }
528         end_critical_section(S_SESSION_TABLE);
529
530         /* Now that we no longer have the session list locked, we can take
531          * our time and destroy any sessions on the to-be-killed list, which
532          * is allocated privately on this thread's stack.
533          */
534         while (rem != NULL) {
535                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
536                 RemoveContext(rem);
537                 ptr = rem;
538                 rem = rem->next;
539                 free(ptr);
540         }
541 }
542
543
544
545
546
547 /*
548  * masterCC is the context we use when not attached to a session.  This
549  * function initializes it.
550  */
551 void InitializeMasterCC(void) {
552         memset(&masterCC, 0, sizeof( CitContext));
553         masterCC.internal_pgm = 1;
554         masterCC.cs_pid = 0;
555 }
556
557
558
559
560 /*
561  * Bind a thread to a context.  (It's inline merely to speed things up.)
562  */
563 INLINE void become_session(CitContext *which_con) {
564         citthread_setspecific(MyConKey, (void *)which_con );
565 }
566
567
568