* vCtdlLogPrintf(): add the userID when reporting from a system thread
[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         FreeStrBuf(&con->lBuf);
349         CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
350 }
351
352
353
354
355 /*
356  * Initialize a new context and place it in the list.  The session number
357  * used to be the PID (which is why it's called cs_pid), but that was when we
358  * had one process per session.  Now we just assign them sequentially, starting
359  * at 1 (don't change it to 0 because masterCC uses 0).
360  */
361 CitContext *CreateNewContext(void) {
362         CitContext *me;
363         static int next_pid = 0;
364
365         me = (CitContext *) malloc(sizeof(CitContext));
366         if (me == NULL) {
367                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
368                 return NULL;
369         }
370         memset(me, 0, sizeof(CitContext));
371         me->lBuf = NewStrBufPlain(NULL, SIZ);
372         /* Give the contaxt a name. Hopefully makes it easier to track */
373         strcpy (me->user.fullname, "SYS_notauth");
374         
375         /* The new context will be created already in the CON_EXECUTING state
376          * in order to prevent another thread from grabbing it while it's
377          * being set up.
378          */
379         me->state = CON_EXECUTING;
380         /*
381          * Generate a unique session number and insert this context into
382          * the list.
383          */
384         me->MigrateBuf = NewStrBuf();
385         me->ReadBuf = NewStrBuf();
386         begin_critical_section(S_SESSION_TABLE);
387         me->cs_pid = ++next_pid;
388         me->prev = NULL;
389         me->next = ContextList;
390         ContextList = me;
391         if (me->next != NULL) {
392                 me->next->prev = me;
393         }
394         ++num_sessions;
395         end_critical_section(S_SESSION_TABLE);
396         return (me);
397 }
398
399
400 /*
401  * Return an array containing a copy of the context list.
402  * This allows worker threads to perform "for each context" operations without
403  * having to lock and traverse the live list.
404  */
405 CitContext *CtdlGetContextArray(int *count)
406 {
407         int nContexts, i;
408         CitContext *nptr, *cptr;
409         
410         nContexts = num_sessions;
411         nptr = malloc(sizeof(CitContext) * nContexts);
412         if (!nptr) {
413                 *count = 0;
414                 return NULL;
415         }
416         begin_critical_section(S_SESSION_TABLE);
417         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
418                 memcpy(&nptr[i], cptr, sizeof (CitContext));
419         }
420         end_critical_section (S_SESSION_TABLE);
421         
422         *count = i;
423         return nptr;
424 }
425
426
427
428 /*
429  * This function fills in a context and its user field correctly
430  * Then creates/loads that user
431  */
432 void CtdlFillSystemContext(CitContext *context, char *name)
433 {
434         char sysname[SIZ];
435         long len;
436
437         memset(context, 0, sizeof(CitContext));
438         context->lBuf = NewStrBuf();
439         context->internal_pgm = 1;
440         context->cs_pid = 0;
441         strcpy (sysname, "SYS_");
442         strcat (sysname, name);
443         len = cutuserkey(sysname);
444         memcpy(context->curr_user, sysname, len + 1);
445
446         /* internal_create_user has the side effect of loading the user regardless of wether they
447          * already existed or needed to be created
448          */
449         internal_create_user (sysname, len, &(context->user), -1) ;
450         
451         /* Check to see if the system user needs upgrading */
452         if (context->user.usernum == 0)
453         {       /* old system user with number 0, upgrade it */
454                 context->user.usernum = get_new_user_number();
455                 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
456                 /* add user to the database */
457                 CtdlPutUser(&(context->user));
458                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
459         }
460 }
461
462 /*
463  * Cleanup any contexts that are left lying around
464  */
465 void context_cleanup(void)
466 {
467         CitContext *ptr = NULL;
468         CitContext *rem = NULL;
469
470         /*
471          * Clean up the contexts.
472          * There are no threads so no critical_section stuff is needed.
473          */
474         ptr = ContextList;
475         
476         /* We need to update the ContextList because some modules may want to itterate it
477          * Question is should we NULL it before iterating here or should we just keep updating it
478          * as we remove items?
479          *
480          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
481          */
482         ContextList=NULL;
483         while (ptr != NULL){
484                 /* Remove the session from the active list */
485                 rem = ptr->next;
486                 --num_sessions;
487                 
488                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
489                 RemoveContext(ptr);
490                 free (ptr);
491                 ptr = rem;
492         }
493 }
494
495
496
497 /*
498  * Terminate another session.
499  * (This could justifiably be moved out of sysdep.c because it
500  * no longer does anything that is system-dependent.)
501  */
502 void kill_session(int session_to_kill) {
503         CitContext *ptr;
504
505         begin_critical_section(S_SESSION_TABLE);
506         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
507                 if (ptr->cs_pid == session_to_kill) {
508                         ptr->kill_me = 1;
509                 }
510         }
511         end_critical_section(S_SESSION_TABLE);
512 }
513
514 /*
515  * Purge all sessions which have the 'kill_me' flag set.
516  * This function has code to prevent it from running more than once every
517  * few seconds, because running it after every single unbind would waste a lot
518  * of CPU time and keep the context list locked too much.  To force it to run
519  * anyway, set "force" to nonzero.
520  */
521 void dead_session_purge(int force) {
522         CitContext *ptr, *ptr2;         /* general-purpose utility pointer */
523         CitContext *rem = NULL; /* list of sessions to be destroyed */
524         
525         if (force == 0) {
526                 if ( (time(NULL) - last_purge) < 5 ) {
527                         return; /* Too soon, go away */
528                 }
529         }
530         time(&last_purge);
531
532         if (try_critical_section(S_SESSION_TABLE))
533                 return;
534                 
535         ptr = ContextList;
536         while (ptr) {
537                 ptr2 = ptr;
538                 ptr = ptr->next;
539                 
540                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
541                         /* Remove the session from the active list */
542                         if (ptr2->prev) {
543                                 ptr2->prev->next = ptr2->next;
544                         }
545                         else {
546                                 ContextList = ptr2->next;
547                         }
548                         if (ptr2->next) {
549                                 ptr2->next->prev = ptr2->prev;
550                         }
551
552                         --num_sessions;
553                         /* And put it on our to-be-destroyed list */
554                         ptr2->next = rem;
555                         rem = ptr2;
556                 }
557         }
558         end_critical_section(S_SESSION_TABLE);
559
560         /* Now that we no longer have the session list locked, we can take
561          * our time and destroy any sessions on the to-be-killed list, which
562          * is allocated privately on this thread's stack.
563          */
564         while (rem != NULL) {
565                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
566                 RemoveContext(rem);
567                 ptr = rem;
568                 rem = rem->next;
569                 free(ptr);
570         }
571 }
572
573
574
575
576
577 /*
578  * masterCC is the context we use when not attached to a session.  This
579  * function initializes it.
580  */
581 void InitializeMasterCC(void) {
582         memset(&masterCC, 0, sizeof( CitContext));
583         masterCC.internal_pgm = 1;
584         masterCC.cs_pid = 0;
585         masterCC.lBuf = NewStrBuf ();
586 }
587
588
589
590
591
592 /*
593  * Set the "async waiting" flag for a session, if applicable
594  */
595 void set_async_waiting(struct CitContext *ccptr)
596 {
597         CtdlLogPrintf(CTDL_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
598         if (ccptr->is_async) {
599                 ccptr->async_waiting++;
600                 if (ccptr->state == CON_IDLE) {
601                         ccptr->state = CON_READY;
602                 }
603         }
604 }