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