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