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