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