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