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