Updated the copyright declaration in several modules, removing any language which...
[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-2011 by the citadel.org team
6  *
7  * This program is open source software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License, version 3.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 #include "sysdep.h"
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <signal.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
26 #include <sys/socket.h>
27 #include <syslog.h>
28 #include <sys/syslog.h>
29 /*
30 #include <sys/syscall.h>
31 */
32
33 #if TIME_WITH_SYS_TIME
34 # include <sys/time.h>
35 # include <time.h>
36 #else
37 # if HAVE_SYS_TIME_H
38 #  include <sys/time.h>
39 # else
40 #  include <time.h>
41 # endif
42 #endif
43
44 #include <limits.h>
45 #include <sys/resource.h>
46 #include <netinet/in.h>
47 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
49 #include <netdb.h>
50 #include <sys/un.h>
51 #include <string.h>
52 #include <pwd.h>
53 #include <errno.h>
54 #include <stdarg.h>
55 #include <grp.h>
56 #include <libcitadel.h>
57 #include "citadel.h"
58 #include "server.h"
59 #include "sysdep_decls.h"
60 #include "citserver.h"
61 #include "support.h"
62 #include "config.h"
63 #include "database.h"
64 #include "housekeeping.h"
65 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
66 #include "ecrash.h"
67
68 #ifdef HAVE_SYS_SELECT_H
69 #include <sys/select.h>
70 #endif
71
72 #ifndef HAVE_SNPRINTF
73 #include "snprintf.h"
74 #endif
75
76 #include "ctdl_module.h"
77 #include "threads.h"
78 #include "user_ops.h"
79 #include "control.h"
80
81 int DebugSession = 0;
82
83 pthread_key_t MyConKey;                         /* TSD key for MyContext() */
84
85
86 CitContext masterCC;
87 CitContext *ContextList = NULL;
88
89 time_t last_purge = 0;                          /* Last dead session purge */
90 int num_sessions = 0;                           /* Current number of sessions */
91
92 /* Flag for single user mode */
93 static int want_single_user = 0;
94
95 /* Try to go single user */
96
97 int CtdlTrySingleUser(void)
98 {
99         int can_do = 0;
100         
101         begin_critical_section(S_SINGLE_USER);
102         if (want_single_user)
103                 can_do = 0;
104         else
105         {
106                 can_do = 1;
107                 want_single_user = 1;
108         }
109         end_critical_section(S_SINGLE_USER);
110         return can_do;
111 }
112
113 void CtdlEndSingleUser(void)
114 {
115         begin_critical_section(S_SINGLE_USER);
116         want_single_user = 0;
117         end_critical_section(S_SINGLE_USER);
118 }
119
120
121 int CtdlWantSingleUser(void)
122 {
123         return want_single_user;
124 }
125
126 int CtdlIsSingleUser(void)
127 {
128         if (want_single_user)
129         {
130                 /* check for only one context here */
131                 if (num_sessions == 1)
132                         return TRUE;
133         }
134         return FALSE;
135 }
136
137
138
139
140
141 /*
142  * Locate a context by its session number and terminate it if the user is able.
143  * User can NOT terminate their current session.
144  * User CAN terminate any other session that has them logged in.
145  * Aide CAN terminate any session except the current one.
146  */
147 int CtdlTerminateOtherSession (int session_num)
148 {
149         int ret = 0;
150         CitContext *ccptr;
151
152         if (session_num == CC->cs_pid) {
153                 return TERM_NOTALLOWED;
154         }
155
156         CONM_syslog(LOG_DEBUG, "Locating session to kill\n");
157         begin_critical_section(S_SESSION_TABLE);
158         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
159                 if (session_num == ccptr->cs_pid) {
160                         ret |= TERM_FOUND;
161                         if ((ccptr->user.usernum == CC->user.usernum)
162                            || (CC->user.axlevel >= AxAideU)) {
163                                 ret |= TERM_ALLOWED;
164                                 ccptr->kill_me = KILLME_ADMIN_TERMINATE;
165                         }
166                 }
167         }
168         end_critical_section(S_SESSION_TABLE);
169         return ret;
170 }
171
172
173
174 /*
175  * Check to see if the user who we just sent mail to is logged in.  If yes,
176  * bump the 'new mail' counter for their session.  That enables them to
177  * receive a new mail notification without having to hit the database.
178  */
179 void BumpNewMailCounter(long which_user) 
180 {
181         CtdlBumpNewMailCounter(which_user);
182 }
183
184 void CtdlBumpNewMailCounter(long which_user)
185 {
186         CitContext *ptr;
187
188         begin_critical_section(S_SESSION_TABLE);
189
190         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
191                 if (ptr->user.usernum == which_user) {
192                         ptr->newmail += 1;
193                 }
194         }
195
196         end_critical_section(S_SESSION_TABLE);
197 }
198
199
200 /*
201  * Check to see if a user is currently logged in
202  * Take care with what you do as a result of this test.
203  * The user may not have been logged in when this function was called BUT
204  * because of threading the user might be logged in before you test the result.
205  */
206 int CtdlIsUserLoggedIn (char *user_name)
207 {
208         CitContext *cptr;
209         int ret = 0;
210
211         begin_critical_section (S_SESSION_TABLE);
212         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
213                 if (!strcasecmp(cptr->user.fullname, user_name)) {
214                         ret = 1;
215                         break;
216                 }
217         }
218         end_critical_section(S_SESSION_TABLE);
219         return ret;
220 }
221
222
223
224 /*
225  * Check to see if a user is currently logged in.
226  * Basically same as CtdlIsUserLoggedIn() but uses the user number instead.
227  * Take care with what you do as a result of this test.
228  * The user may not have been logged in when this function was called BUT
229  * because of threading the user might be logged in before you test the result.
230  */
231 int CtdlIsUserLoggedInByNum (long usernum)
232 {
233         CitContext *cptr;
234         int ret = 0;
235
236         begin_critical_section(S_SESSION_TABLE);
237         for (cptr = ContextList; cptr != NULL; cptr = cptr->next) {
238                 if (cptr->user.usernum == usernum) {
239                         ret = 1;
240                 }
241         }
242         end_critical_section(S_SESSION_TABLE);
243         return ret;
244 }
245
246
247
248 /*
249  * Return a pointer to the CitContext structure bound to the thread which
250  * called this function.  If there's no such binding (for example, if it's
251  * called by the housekeeper thread) then a generic 'master' CC is returned.
252  *
253  * This function is used *VERY* frequently and must be kept small.
254  */
255 CitContext *MyContext(void) {
256         register CitContext *c;
257         return ((c = (CitContext *) pthread_getspecific(MyConKey), c == NULL) ? &masterCC : c);
258 }
259
260
261
262
263 /*
264  * Terminate idle sessions.  This function pounds through the session table
265  * comparing the current time to each session's time-of-last-command.  If an
266  * idle session is found it is terminated, then the search restarts at the
267  * beginning because the pointer to our place in the list becomes invalid.
268  */
269 void terminate_idle_sessions(void)
270 {
271         CitContext *ccptr;
272         time_t now;
273         int killed = 0;
274         int longrunners = 0;
275
276         now = time(NULL);
277         begin_critical_section(S_SESSION_TABLE);
278         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
279                 if (
280                         (ccptr != CC)
281                         && (config.c_sleeping > 0)
282                         && (now - (ccptr->lastcmd) > config.c_sleeping)
283                 ) {
284                         if (!ccptr->dont_term) {
285                                 ccptr->kill_me = KILLME_IDLE;
286                                 ++killed;
287                         }
288                         else {
289                                 ++longrunners;
290                         }
291                 }
292         }
293         end_critical_section(S_SESSION_TABLE);
294         if (killed > 0)
295                 CON_syslog(LOG_INFO, "Scheduled %d idle sessions for termination\n", killed);
296         if (longrunners > 0)
297                 CON_syslog(LOG_INFO, "Didn't terminate %d protected idle sessions", longrunners);
298 }
299
300
301 /*
302  * During shutdown, close the sockets of any sessions still connected.
303  */
304 void terminate_all_sessions(void)
305 {
306         CitContext *ccptr;
307         int killed = 0;
308
309         begin_critical_section(S_SESSION_TABLE);
310         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
311                 if (ccptr->client_socket != -1)
312                 {
313                         CON_syslog(LOG_INFO, "terminate_all_sessions() is murdering %s", ccptr->curr_user);
314                         close(ccptr->client_socket);
315                         ccptr->client_socket = -1;
316                         killed++;
317                 }
318         }
319         end_critical_section(S_SESSION_TABLE);
320         if (killed > 0) {
321                 CON_syslog(LOG_INFO, "Flushed %d stuck sessions\n", killed);
322         }
323 }
324
325
326
327 /*
328  * Terminate a session.
329  */
330 void RemoveContext (CitContext *con)
331 {
332         const char *c;
333         if (con == NULL) {
334                 CONM_syslog(LOG_ERR, "WARNING: RemoveContext() called with NULL!");
335                 return;
336         }
337         c = con->ServiceName;
338         if (c == NULL) {
339                 c = "WTF?";
340         }
341         CON_syslog(LOG_DEBUG, "RemoveContext(%s) session %d", c, con->cs_pid);
342 ///     cit_backtrace();
343
344         /* Run any cleanup routines registered by loadable modules.
345          * Note: We have to "become_session()" because the cleanup functions
346          *       might make references to "CC" assuming it's the right one.
347          */
348         become_session(con);
349         CtdlUserLogout();
350         PerformSessionHooks(EVT_STOP);
351         client_close();                         /* If the client is still connected, blow 'em away. */
352         become_session(NULL);
353
354         CON_syslog(LOG_NOTICE, "[%3d]SRV[%s] Session ended.", con->cs_pid, c);
355
356         /* 
357          * If the client is still connected, blow 'em away. 
358          * if the socket is 0 or -1, its already gone or was never there.
359          */
360         if (con->client_socket > 0)
361         {
362                 CON_syslog(LOG_NOTICE, "Closing socket %d", con->client_socket);
363                 close(con->client_socket);
364         }
365
366         /* If using AUTHMODE_LDAP, free the DN */
367         if (con->ldap_dn) {
368                 free(con->ldap_dn);
369                 con->ldap_dn = NULL;
370         }
371         FreeStrBuf(&con->StatusMessage);
372         FreeStrBuf(&con->MigrateBuf);
373         FreeStrBuf(&con->RecvBuf.Buf);
374         if (con->cached_msglist) {
375                 free(con->cached_msglist);
376         }
377
378         CONM_syslog(LOG_DEBUG, "Done with RemoveContext()");
379 }
380
381
382
383 /*
384  * Initialize a new context and place it in the list.  The session number
385  * used to be the PID (which is why it's called cs_pid), but that was when we
386  * had one process per session.  Now we just assign them sequentially, starting
387  * at 1 (don't change it to 0 because masterCC uses 0).
388  */
389 CitContext *CreateNewContext(void) {
390         CitContext *me;
391         static int next_pid = 0;
392
393         me = (CitContext *) malloc(sizeof(CitContext));
394         if (me == NULL) {
395                 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
396                 return NULL;
397         }
398         memset(me, 0, sizeof(CitContext));
399
400         /* Give the context a name. Hopefully makes it easier to track */
401         strcpy (me->user.fullname, "SYS_notauth");
402         
403         /* The new context will be created already in the CON_EXECUTING state
404          * in order to prevent another thread from grabbing it while it's
405          * being set up.
406          */
407         me->state = CON_EXECUTING;
408         /*
409          * Generate a unique session number and insert this context into
410          * the list.
411          */
412         me->MigrateBuf = NewStrBuf();
413
414         me->RecvBuf.Buf = NewStrBuf();
415
416         me->lastcmd = time(NULL);       /* set lastcmd to now to prevent idle timer infanticide TODO: if we have a valid IO, use that to set the timer. */
417
418
419         begin_critical_section(S_SESSION_TABLE);
420         me->cs_pid = ++next_pid;
421         me->prev = NULL;
422         me->next = ContextList;
423         ContextList = me;
424         if (me->next != NULL) {
425                 me->next->prev = me;
426         }
427         ++num_sessions;
428         end_critical_section(S_SESSION_TABLE);
429         return (me);
430 }
431
432
433 /*
434  * Initialize a new context and place it in the list.  The session number
435  * used to be the PID (which is why it's called cs_pid), but that was when we
436  * had one process per session.  Now we just assign them sequentially, starting
437  * at 1 (don't change it to 0 because masterCC uses 0).
438  */
439 CitContext *CloneContext(CitContext *CloneMe) {
440         CitContext *me;
441         static int next_pid = 0;
442
443         me = (CitContext *) malloc(sizeof(CitContext));
444         if (me == NULL) {
445                 CONM_syslog(LOG_ALERT, "citserver: can't allocate memory!!\n");
446                 return NULL;
447         }
448         memcpy(me, CloneMe, sizeof(CitContext));
449
450         memset(&me->RecvBuf, 0, sizeof(IOBuffer));
451         memset(&me->SendBuf, 0, sizeof(IOBuffer));
452         memset(&me->SBuf, 0, sizeof(IOBuffer));
453         me->MigrateBuf = NULL;
454         me->sMigrateBuf = NULL;
455         me->redirect_buffer = NULL;
456 #ifdef HAVE_OPENSSL
457         me->ssl = NULL;
458 #endif
459
460         me->download_fp = NULL;
461         me->upload_fp = NULL;
462         /// TODO: what about the room/user?
463         me->ma = NULL;
464         me->openid_data = NULL;
465         me->ldap_dn = NULL;
466         me->session_specific_data = NULL;
467
468         me->download_fp = NULL;
469         me->upload_fp = NULL;
470         me->client_socket = 0;
471
472         me->MigrateBuf = NewStrBuf();
473         me->RecvBuf.Buf = NewStrBuf();
474         
475         begin_critical_section(S_SESSION_TABLE);
476         {
477                 me->cs_pid = ++next_pid;
478                 me->prev = NULL;
479                 me->next = ContextList;
480                 me->lastcmd = time(NULL);       /* set lastcmd to now to prevent idle timer infanticide */
481                 ContextList = me;
482                 if (me->next != NULL) {
483                         me->next->prev = me;
484                 }
485                 ++num_sessions;
486         }
487         end_critical_section(S_SESSION_TABLE);
488         return (me);
489 }
490
491
492 /*
493  * Return an array containing a copy of the context list.
494  * This allows worker threads to perform "for each context" operations without
495  * having to lock and traverse the live list.
496  */
497 CitContext *CtdlGetContextArray(int *count)
498 {
499         int nContexts, i;
500         CitContext *nptr, *cptr;
501         
502         nContexts = num_sessions;
503         nptr = malloc(sizeof(CitContext) * nContexts);
504         if (!nptr) {
505                 *count = 0;
506                 return NULL;
507         }
508         begin_critical_section(S_SESSION_TABLE);
509         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
510                 memcpy(&nptr[i], cptr, sizeof (CitContext));
511         }
512         end_critical_section (S_SESSION_TABLE);
513         
514         *count = i;
515         return nptr;
516 }
517
518
519
520 /*
521  * This function fills in a context and its user field correctly
522  * Then creates/loads that user
523  */
524 void CtdlFillSystemContext(CitContext *context, char *name)
525 {
526         char sysname[SIZ];
527         long len;
528
529         memset(context, 0, sizeof(CitContext));
530         context->internal_pgm = 1;
531         context->cs_pid = 0;
532         strcpy (sysname, "SYS_");
533         strcat (sysname, name);
534         len = cutuserkey(sysname);
535         memcpy(context->curr_user, sysname, len + 1);
536         context->client_socket = (-1);
537         context->state = CON_SYS;
538         context->ServiceName = name;
539
540         /* internal_create_user has the side effect of loading the user regardless of wether they
541          * already existed or needed to be created
542          */
543         internal_create_user (sysname, len, &(context->user), -1) ;
544         
545         /* Check to see if the system user needs upgrading */
546         if (context->user.usernum == 0)
547         {       /* old system user with number 0, upgrade it */
548                 context->user.usernum = get_new_user_number();
549                 CON_syslog(LOG_INFO, "Upgrading system user \"%s\" from user number 0 to user number %ld\n", context->user.fullname, context->user.usernum);
550                 /* add user to the database */
551                 CtdlPutUser(&(context->user));
552                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
553         }
554 }
555
556
557 /*
558  * Cleanup any contexts that are left lying around
559  */
560 void context_cleanup(void)
561 {
562         CitContext *ptr = NULL;
563         CitContext *rem = NULL;
564
565         /*
566          * Clean up the contexts.
567          * There are no threads so no critical_section stuff is needed.
568          */
569         ptr = ContextList;
570         
571         /* We need to update the ContextList because some modules may want to itterate it
572          * Question is should we NULL it before iterating here or should we just keep updating it
573          * as we remove items?
574          *
575          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
576          */
577         ContextList=NULL;
578         while (ptr != NULL){
579                 /* Remove the session from the active list */
580                 rem = ptr->next;
581                 --num_sessions;
582
583                 CON_syslog(LOG_DEBUG, "context_cleanup(): purging session %d\n", ptr->cs_pid);
584                 RemoveContext(ptr);
585                 free (ptr);
586                 ptr = rem;
587         }
588 }
589
590
591
592 /*
593  * Purge all sessions which have the 'kill_me' flag set.
594  * This function has code to prevent it from running more than once every
595  * few seconds, because running it after every single unbind would waste a lot
596  * of CPU time and keep the context list locked too much.  To force it to run
597  * anyway, set "force" to nonzero.
598  */
599 void dead_session_purge(int force) {
600         CitContext *ptr, *ptr2;         /* general-purpose utility pointer */
601         CitContext *rem = NULL;         /* list of sessions to be destroyed */
602         
603         if (force == 0) {
604                 if ( (time(NULL) - last_purge) < 5 ) {
605                         return; /* Too soon, go away */
606                 }
607         }
608         time(&last_purge);
609
610         if (try_critical_section(S_SESSION_TABLE))
611                 return;
612                 
613         ptr = ContextList;
614         while (ptr) {
615                 ptr2 = ptr;
616                 ptr = ptr->next;
617                 
618                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
619                         /* Remove the session from the active list */
620                         if (ptr2->prev) {
621                                 ptr2->prev->next = ptr2->next;
622                         }
623                         else {
624                                 ContextList = ptr2->next;
625                         }
626                         if (ptr2->next) {
627                                 ptr2->next->prev = ptr2->prev;
628                         }
629
630                         --num_sessions;
631                         /* And put it on our to-be-destroyed list */
632                         ptr2->next = rem;
633                         rem = ptr2;
634                 }
635         }
636         end_critical_section(S_SESSION_TABLE);
637
638         /* Now that we no longer have the session list locked, we can take
639          * our time and destroy any sessions on the to-be-killed list, which
640          * is allocated privately on this thread's stack.
641          */
642         while (rem != NULL) {
643                 CON_syslog(LOG_DEBUG, "dead_session_purge(): purging session %d, reason=%d\n", rem->cs_pid, rem->kill_me);
644                 RemoveContext(rem);
645                 ptr = rem;
646                 rem = rem->next;
647                 free(ptr);
648         }
649 }
650
651
652
653
654
655 /*
656  * masterCC is the context we use when not attached to a session.  This
657  * function initializes it.
658  */
659 void InitializeMasterCC(void) {
660         memset(&masterCC, 0, sizeof(struct CitContext));
661         masterCC.internal_pgm = 1;
662         masterCC.cs_pid = 0;
663 }
664
665
666
667
668
669 /*
670  * Set the "async waiting" flag for a session, if applicable
671  */
672 void set_async_waiting(struct CitContext *ccptr)
673 {
674         CON_syslog(LOG_DEBUG, "Setting async_waiting flag for session %d\n", ccptr->cs_pid);
675         if (ccptr->is_async) {
676                 ccptr->async_waiting++;
677                 if (ccptr->state == CON_IDLE) {
678                         ccptr->state = CON_READY;
679                 }
680         }
681 }
682
683
684 void DebugSessionEnable(const int n)
685 {
686         DebugSession = n;
687 }
688 CTDL_MODULE_INIT(session)
689 {
690         if (!threading) {
691                 CtdlRegisterDebugFlagHook(HKEY("session"), DebugSessionEnable, &DebugSession);
692         }
693         return "session";
694 }