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