Revert "Replaced cached_msglist array with a btree persistent through the session."
[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-2010 by the citadel.org team
6  *
7  * This program is free 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 citthread_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 = 1;
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
263         register CitContext *c;
264
265         return ((c = (CitContext *) citthread_getspecific(MyConKey),
266                 c == NULL) ? &masterCC : c
267         );
268 }
269
270
271
272
273 /*
274  * Terminate idle sessions.  This function pounds through the session table
275  * comparing the current time to each session's time-of-last-command.  If an
276  * idle session is found it is terminated, then the search restarts at the
277  * beginning because the pointer to our place in the list becomes invalid.
278  */
279 void terminate_idle_sessions(void)
280 {
281         CitContext *ccptr;
282         time_t now;
283         int session_to_kill;
284         int killed = 0;
285         int longrunners = 0;
286
287         now = time(NULL);
288         session_to_kill = 0;
289         begin_critical_section(S_SESSION_TABLE);
290         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
291                 if (  (ccptr!=CC)
292                 && (config.c_sleeping > 0)
293                 && (now - (ccptr->lastcmd) > config.c_sleeping) ) {
294                         if (!ccptr->dont_term) {
295                                 ccptr->kill_me = 1;
296                                 ++killed;
297                         }
298                         else 
299                                 longrunners ++;
300                 }
301         }
302         end_critical_section(S_SESSION_TABLE);
303         if (killed > 0)
304                 syslog(LOG_INFO, "Scheduled %d idle sessions for termination\n", killed);
305         if (longrunners > 0)
306                 syslog(LOG_INFO, "Didn't terminate %d protected idle sessions;\n", killed);
307 }
308
309 void terminate_stuck_sessions(void)
310 {
311         CitContext *ccptr;
312         int killed = 0;
313
314         begin_critical_section(S_SESSION_TABLE);
315         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
316                 if (ccptr->client_socket != -1)
317                 {
318                         close(ccptr->client_socket);
319                         ccptr->client_socket = -1;
320                         killed++;
321                 }
322         }
323         end_critical_section(S_SESSION_TABLE);
324         if (killed > 0)
325                 syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
326 }
327
328
329
330 /*
331  * Terminate a session.
332  */
333 void RemoveContext (CitContext *con)
334 {
335         if (con==NULL) {
336                 syslog(LOG_ERR,
337                         "WARNING: RemoveContext() called with NULL!\n");
338                 return;
339         }
340         syslog(LOG_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
341
342         /* Run any cleanup routines registered by loadable modules.
343          * Note: We have to "become_session()" because the cleanup functions
344          *       might make references to "CC" assuming it's the right one.
345          */
346         become_session(con);
347         CtdlUserLogout();
348         PerformSessionHooks(EVT_STOP);
349         become_session(NULL);
350
351         syslog(LOG_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
352
353         /* 
354          * If the client is still connected, blow 'em away. 
355          * if the socket is 0, its already gone or was never there.
356          */
357         if (con->client_socket != 0)
358         {
359                 syslog(LOG_DEBUG, "Closing socket %d\n", con->client_socket);
360                 close(con->client_socket);
361         }
362
363         /* If using AUTHMODE_LDAP, free the DN */
364         if (con->ldap_dn) {
365                 free(con->ldap_dn);
366                 con->ldap_dn = NULL;
367         }
368
369         FreeStrBuf(&con->MigrateBuf);
370         FreeStrBuf(&con->RecvBuf.Buf);
371         if (con->cached_msglist) {
372                 free(con->cached_msglist);
373         }
374
375         syslog(LOG_DEBUG, "Done with RemoveContext()\n");
376 }
377
378
379
380
381 /*
382  * Initialize a new context and place it in the list.  The session number
383  * used to be the PID (which is why it's called cs_pid), but that was when we
384  * had one process per session.  Now we just assign them sequentially, starting
385  * at 1 (don't change it to 0 because masterCC uses 0).
386  */
387 CitContext *CreateNewContext(void) {
388         CitContext *me;
389         static int next_pid = 0;
390
391         me = (CitContext *) malloc(sizeof(CitContext));
392         if (me == NULL) {
393                 syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
394                 return NULL;
395         }
396         memset(me, 0, sizeof(CitContext));
397         /* Give the contaxt a name. Hopefully makes it easier to track */
398         strcpy (me->user.fullname, "SYS_notauth");
399         
400         /* The new context will be created already in the CON_EXECUTING state
401          * in order to prevent another thread from grabbing it while it's
402          * being set up.
403          */
404         me->state = CON_EXECUTING;
405         /*
406          * Generate a unique session number and insert this context into
407          * the list.
408          */
409         me->MigrateBuf = NewStrBuf();
410         me->RecvBuf.Buf = NewStrBuf();
411         begin_critical_section(S_SESSION_TABLE);
412         me->cs_pid = ++next_pid;
413         me->prev = NULL;
414         me->next = ContextList;
415         me->lastcmd = time(NULL);       /* set lastcmd to now to prevent idle timer infanticide */
416         ContextList = me;
417         if (me->next != NULL) {
418                 me->next->prev = me;
419         }
420         ++num_sessions;
421         end_critical_section(S_SESSION_TABLE);
422         return (me);
423 }
424
425
426 /*
427  * Initialize a new context and place it in the list.  The session number
428  * used to be the PID (which is why it's called cs_pid), but that was when we
429  * had one process per session.  Now we just assign them sequentially, starting
430  * at 1 (don't change it to 0 because masterCC uses 0).
431  */
432 CitContext *CloneContext(CitContext *CloneMe) {
433         CitContext *me;
434         static int next_pid = 0;
435
436         me = (CitContext *) malloc(sizeof(CitContext));
437         if (me == NULL) {
438                 syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
439                 return NULL;
440         }
441         memcpy(me, CloneMe, sizeof(CitContext));
442
443         memset(&me->RecvBuf, 0, sizeof(IOBuffer));
444         memset(&me->SendBuf, 0, sizeof(IOBuffer));
445         memset(&me->SBuf, 0, sizeof(IOBuffer));
446         me->MigrateBuf = NULL;
447         me->sMigrateBuf = NULL;
448         me->redirect_buffer = NULL;
449 #ifdef HAVE_OPENSSL
450         me->ssl = NULL;
451 #endif
452
453         me->download_fp = NULL;
454         me->upload_fp = NULL;
455         /// TODO: what about the room/user?
456         me->ma = NULL;
457         me->openid_data = NULL;
458         me->ldap_dn = NULL;
459         me->session_specific_data = NULL;
460
461         me->download_fp = NULL;
462         me->upload_fp = NULL;
463         me->client_socket = 0;
464
465         me->MigrateBuf = NewStrBuf();
466         me->RecvBuf.Buf = NewStrBuf();
467         
468         begin_critical_section(S_SESSION_TABLE);
469         {
470                 me->cs_pid = ++next_pid;
471                 me->prev = NULL;
472                 me->next = ContextList;
473                 me->lastcmd = time(NULL);       /* set lastcmd to now to prevent idle timer infanticide */
474                 ContextList = me;
475                 if (me->next != NULL) {
476                         me->next->prev = me;
477                 }
478                 ++num_sessions;
479         }
480         end_critical_section(S_SESSION_TABLE);
481         return (me);
482 }
483
484
485 /*
486  * Return an array containing a copy of the context list.
487  * This allows worker threads to perform "for each context" operations without
488  * having to lock and traverse the live list.
489  */
490 CitContext *CtdlGetContextArray(int *count)
491 {
492         int nContexts, i;
493         CitContext *nptr, *cptr;
494         
495         nContexts = num_sessions;
496         nptr = malloc(sizeof(CitContext) * nContexts);
497         if (!nptr) {
498                 *count = 0;
499                 return NULL;
500         }
501         begin_critical_section(S_SESSION_TABLE);
502         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
503                 memcpy(&nptr[i], cptr, sizeof (CitContext));
504         }
505         end_critical_section (S_SESSION_TABLE);
506         
507         *count = i;
508         return nptr;
509 }
510
511
512
513 /*
514  * This function fills in a context and its user field correctly
515  * Then creates/loads that user
516  */
517 void CtdlFillSystemContext(CitContext *context, char *name)
518 {
519         char sysname[SIZ];
520         long len;
521
522         memset(context, 0, sizeof(CitContext));
523         context->internal_pgm = 1;
524         context->cs_pid = 0;
525         strcpy (sysname, "SYS_");
526         strcat (sysname, name);
527         len = cutuserkey(sysname);
528         memcpy(context->curr_user, sysname, len + 1);
529         context->client_socket = (-1);
530         context->state = CON_SYS;
531         context->ServiceName = name;
532
533         /* internal_create_user has the side effect of loading the user regardless of wether they
534          * already existed or needed to be created
535          */
536         internal_create_user (sysname, len, &(context->user), -1) ;
537         
538         /* Check to see if the system user needs upgrading */
539         if (context->user.usernum == 0)
540         {       /* old system user with number 0, upgrade it */
541                 context->user.usernum = get_new_user_number();
542                 syslog(LOG_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
543                 /* add user to the database */
544                 CtdlPutUser(&(context->user));
545                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
546         }
547 }
548
549 /*
550  * flush it again...
551  */
552 void CtdlClearSystemContext(void)
553 {
554         CitContext *CCC = MyContext();
555
556         memset(CCC, 0, sizeof(CitContext));
557         citthread_setspecific(MyConKey, NULL);
558 }
559
560 /*
561  * Cleanup any contexts that are left lying around
562  */
563 void context_cleanup(void)
564 {
565         CitContext *ptr = NULL;
566         CitContext *rem = NULL;
567
568         /*
569          * Clean up the contexts.
570          * There are no threads so no critical_section stuff is needed.
571          */
572         ptr = ContextList;
573         
574         /* We need to update the ContextList because some modules may want to itterate it
575          * Question is should we NULL it before iterating here or should we just keep updating it
576          * as we remove items?
577          *
578          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
579          */
580         ContextList=NULL;
581         while (ptr != NULL){
582                 /* Remove the session from the active list */
583                 rem = ptr->next;
584                 --num_sessions;
585
586                 syslog(LOG_DEBUG, "Purging session #%d %s\n", ptr->cs_pid, ptr->ServiceName);
587                 RemoveContext(ptr);
588                 free (ptr);
589                 ptr = rem;
590         }
591 }
592
593
594
595 /*
596  * Terminate another session.
597  * (This could justifiably be moved out of sysdep.c because it
598  * no longer does anything that is system-dependent.)
599  */
600 void kill_session(int session_to_kill) {
601         CitContext *ptr;
602
603         begin_critical_section(S_SESSION_TABLE);
604         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
605                 if (ptr->cs_pid == session_to_kill) {
606                         ptr->kill_me = 1;
607                 }
608         }
609         end_critical_section(S_SESSION_TABLE);
610 }
611
612 /*
613  * Purge all sessions which have the 'kill_me' flag set.
614  * This function has code to prevent it from running more than once every
615  * few seconds, because running it after every single unbind would waste a lot
616  * of CPU time and keep the context list locked too much.  To force it to run
617  * anyway, set "force" to nonzero.
618  */
619 void dead_session_purge(int force) {
620         CitContext *ptr, *ptr2;         /* general-purpose utility pointer */
621         CitContext *rem = NULL; /* list of sessions to be destroyed */
622         
623         if (force == 0) {
624                 if ( (time(NULL) - last_purge) < 5 ) {
625                         return; /* Too soon, go away */
626                 }
627         }
628         time(&last_purge);
629
630         if (try_critical_section(S_SESSION_TABLE))
631                 return;
632                 
633         ptr = ContextList;
634         while (ptr) {
635                 ptr2 = ptr;
636                 ptr = ptr->next;
637                 
638                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
639                         /* Remove the session from the active list */
640                         if (ptr2->prev) {
641                                 ptr2->prev->next = ptr2->next;
642                         }
643                         else {
644                                 ContextList = ptr2->next;
645                         }
646                         if (ptr2->next) {
647                                 ptr2->next->prev = ptr2->prev;
648                         }
649
650                         --num_sessions;
651                         /* And put it on our to-be-destroyed list */
652                         ptr2->next = rem;
653                         rem = ptr2;
654                 }
655         }
656         end_critical_section(S_SESSION_TABLE);
657
658         /* Now that we no longer have the session list locked, we can take
659          * our time and destroy any sessions on the to-be-killed list, which
660          * is allocated privately on this thread's stack.
661          */
662         while (rem != NULL) {
663                 syslog(LOG_DEBUG, "Purging session %d\n", rem->cs_pid);
664                 RemoveContext(rem);
665                 ptr = rem;
666                 rem = rem->next;
667                 free(ptr);
668         }
669 }
670
671
672
673
674
675 /*
676  * masterCC is the context we use when not attached to a session.  This
677  * function initializes it.
678  */
679 void InitializeMasterCC(void) {
680         memset(&masterCC, 0, sizeof( CitContext));
681         masterCC.internal_pgm = 1;
682         masterCC.cs_pid = 0;
683 }
684
685
686
687
688
689 /*
690  * Set the "async waiting" flag for a session, if applicable
691  */
692 void set_async_waiting(struct CitContext *ccptr)
693 {
694         syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
695         if (ccptr->is_async) {
696                 ccptr->async_waiting++;
697                 if (ccptr->state == CON_IDLE) {
698                         ccptr->state = CON_READY;
699                 }
700         }
701 }