f7eea71f09b9de706afac9ea7ec7fb5bd9ccc85d
[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         int longrunners = 0;
188
189         now = time(NULL);
190         begin_critical_section(S_SESSION_TABLE);
191         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
192                 if (
193                         (ccptr != CC)
194                         && (CtdlGetConfigLong("c_sleeping") > 0)
195                         && (now - (ccptr->lastcmd) > CtdlGetConfigLong("c_sleeping"))
196                 ) {
197                         if (!ccptr->dont_term) {
198                                 ccptr->kill_me = KILLME_IDLE;
199                                 ++killed;
200                         }
201                         else {
202                                 ++longrunners;
203                         }
204                 }
205         }
206         end_critical_section(S_SESSION_TABLE);
207         if (killed > 0) {
208                 syslog(LOG_INFO, "context: scheduled %d idle sessions for termination", killed);
209         }
210         if (longrunners > 0) {
211                 syslog(LOG_INFO, "context: did not terminate %d protected idle sessions", longrunners);
212         }
213 }
214
215
216 // During shutdown, close the sockets of any sessions still connected.
217 void terminate_all_sessions(void) {
218         CitContext *ccptr;
219         int killed = 0;
220
221         begin_critical_section(S_SESSION_TABLE);
222         for (ccptr = ContextList; ccptr != NULL; ccptr = ccptr->next) {
223                 if (ccptr->client_socket != -1)
224                 {
225                         syslog(LOG_INFO, "context: terminate_all_sessions() is murdering %s CC[%d]", ccptr->curr_user, ccptr->cs_pid);
226                         close(ccptr->client_socket);
227                         ccptr->client_socket = -1;
228                         killed++;
229                 }
230         }
231         end_critical_section(S_SESSION_TABLE);
232         if (killed > 0) {
233                 syslog(LOG_INFO, "context: flushed %d stuck sessions", killed);
234         }
235 }
236
237
238 // Terminate a session.
239 void RemoveContext(CitContext *con) {
240         const char *c;
241         if (con == NULL) {
242                 syslog(LOG_ERR, "context: RemoveContext() called with NULL, this should not happen");
243                 return;
244         }
245         c = con->ServiceName;
246         if (c == NULL) {
247                 c = "(unknown)";
248         }
249         syslog(LOG_DEBUG, "context: RemoveContext(%s) session %d", c, con->cs_pid);
250
251         // Run any cleanup routines registered by loadable modules.
252         // Note: We have to "become_session()" because the cleanup functions might make references to "CC" assuming it's the right one.
253         become_session(con);
254         CtdlUserLogout();
255         PerformSessionHooks(EVT_STOP);          // hooks may free some data structures, close SSL, etc.
256         client_close();                         // If the client is still connected, disconnect them immediately.
257         become_session(NULL);
258         syslog(LOG_INFO, "context: session %d (%s) ended.", con->cs_pid, c);
259
260         /* If using AUTHMODE_LDAP, free the DN */
261         if (con->ldap_dn) {
262                 free(con->ldap_dn);
263                 con->ldap_dn = NULL;
264         }
265         FreeStrBuf(&con->StatusMessage);
266         FreeStrBuf(&con->MigrateBuf);
267         FreeStrBuf(&con->RecvBuf.Buf);
268         if (con->cached_msglist) {
269                 free(con->cached_msglist);
270         }
271
272         syslog(LOG_DEBUG, "context: done with RemoveContext()");
273 }
274
275
276 // Initialize a new context and place it in the list.  The session number
277 // used to be the PID (which is why it's called cs_pid), but that was when we
278 // had one process per session.  Now we just assign them sequentially, starting
279 // at 1 (don't change it to 0 because masterCC uses 0).
280 CitContext *CreateNewContext(void) {
281         CitContext *me;
282
283         me = (CitContext *) malloc(sizeof(CitContext));
284         if (me == NULL) {
285                 syslog(LOG_ERR, "citserver: malloc() failed: %m");
286                 return NULL;
287         }
288         memset(me, 0, sizeof(CitContext));
289
290         // Give the context a name. Hopefully makes it easier to track
291         strcpy (me->user.fullname, "SYS_notauth");
292         
293         me->state = CON_EXECUTING;      // Create new context already in CON_EXECUTING so another thread doesn't grab it.
294         me->MigrateBuf = NewStrBuf();   // Generate a unique session number
295         me->RecvBuf.Buf = NewStrBuf();
296         me->lastcmd = time(NULL);       // set lastcmd to now to prevent idle timer infanticide
297
298         begin_critical_section(S_SESSION_TABLE);
299         me->cs_pid = ++next_pid;
300         me->prev = NULL;
301         me->next = ContextList;
302         ContextList = me;
303         if (me->next != NULL) {
304                 me->next->prev = me;
305         }
306         ++num_sessions;
307         end_critical_section(S_SESSION_TABLE);
308         return (me);
309 }
310
311
312 // Initialize a new context and place it in the list.  The session number
313 // used to be the PID (which is why it's called cs_pid), but that was when we
314 // had one process per session.  Now we just assign them sequentially, starting
315 // at 1 (don't change it to 0 because masterCC uses 0).
316 CitContext *CloneContext(CitContext *CloneMe) {
317         CitContext *me;
318
319         me = (CitContext *) malloc(sizeof(CitContext));
320         if (me == NULL) {
321                 syslog(LOG_ERR, "citserver: malloc() failed: %m");
322                 return NULL;
323         }
324         memcpy(me, CloneMe, sizeof(CitContext));
325
326         memset(&me->RecvBuf, 0, sizeof(IOBuffer));
327         memset(&me->SendBuf, 0, sizeof(IOBuffer));
328         memset(&me->SBuf, 0, sizeof(IOBuffer));
329         me->MigrateBuf = NULL;
330         me->sMigrateBuf = NULL;
331         me->redirect_buffer = NULL;
332 #ifdef HAVE_OPENSSL
333         me->ssl = NULL;
334 #endif
335
336         me->download_fp = NULL;
337         me->upload_fp = NULL;
338         me->ma = NULL;
339         me->ldap_dn = NULL;
340         me->session_specific_data = NULL;
341         
342         me->CIT_ICAL = NULL;
343
344         me->cached_msglist = NULL;
345         me->download_fp = NULL;
346         me->upload_fp = NULL;
347         me->client_socket = 0;
348
349         me->MigrateBuf = NewStrBuf();
350         me->RecvBuf.Buf = NewStrBuf();
351         
352         begin_critical_section(S_SESSION_TABLE);
353
354         me->cs_pid = ++next_pid;
355         me->prev = NULL;
356         me->next = ContextList;
357         me->lastcmd = time(NULL);       // set lastcmd to now to prevent idle timer infanticide
358         ContextList = me;
359         if (me->next != NULL) {
360                 me->next->prev = me;
361         }
362         ++num_sessions;
363
364         end_critical_section(S_SESSION_TABLE);
365         return (me);
366 }
367
368
369 // Return an array containing a copy of the context list.
370 // This allows worker threads to perform "for each context" operations without
371 // having to lock and traverse the live list.
372 CitContext *CtdlGetContextArray(int *count) {
373         int nContexts, i;
374         CitContext *nptr, *cptr;
375         
376         nContexts = num_sessions;
377         nptr = malloc(sizeof(CitContext) * nContexts);
378         if (!nptr) {
379                 *count = 0;
380                 return NULL;
381         }
382         begin_critical_section(S_SESSION_TABLE);
383         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++) {
384                 memcpy(&nptr[i], cptr, sizeof (CitContext));
385         }
386         end_critical_section (S_SESSION_TABLE);
387         
388         *count = i;
389         return nptr;
390 }
391
392
393 // Back-end function for starting a session
394 void begin_session(CitContext *con) {
395
396         // Initialize some variables specific to our context.
397         con->logged_in = 0;
398         con->internal_pgm = 0;
399         con->download_fp = NULL;
400         con->upload_fp = NULL;
401         con->cached_msglist = NULL;
402         con->cached_num_msgs = 0;
403         con->FirstExpressMessage = NULL;
404         time(&con->lastcmd);
405         time(&con->lastidle);
406         strcpy(con->lastcmdname, "    ");
407         strcpy(con->cs_clientname, "(unknown)");
408         strcpy(con->curr_user, NLI);
409         *con->cs_clientinfo = '\0';
410         safestrncpy(con->cs_host, CtdlGetConfigStr("c_fqdn"), sizeof con->cs_host);
411         safestrncpy(con->cs_addr, "", sizeof con->cs_addr);
412         con->cs_UDSclientUID = -1;
413         con->cs_host[sizeof con->cs_host - 1] = 0;
414         if (!CC->is_local_client) {
415                 locate_host(con->cs_host, sizeof con->cs_host,
416                         con->cs_addr, sizeof con->cs_addr,
417                         con->client_socket
418                 );
419         }
420         else {
421                 con->cs_host[0] = 0;
422                 con->cs_addr[0] = 0;
423         }
424         con->cs_flags = 0;
425         con->nologin = 0;
426
427         if (((CtdlGetConfigInt("c_maxsessions") > 0)&&(num_sessions > CtdlGetConfigInt("c_maxsessions"))) || CtdlWantSingleUser()) {
428                 con->nologin = 1;
429         }
430
431         syslog(LOG_INFO, "context: session (%s) started from %s (%s) uid=%d",
432                 con->ServiceName, con->cs_host, con->cs_addr, con->cs_UDSclientUID
433         );
434
435         /* Run any session startup routines registered by loadable modules */
436         PerformSessionHooks(EVT_START);
437 }
438
439
440 // This function fills in a context and its user field correctly
441 // Then creates/loads that user
442 void CtdlFillSystemContext(CitContext *context, char *name) {
443         char sysname[SIZ];
444         long len;
445
446         memset(context, 0, sizeof(CitContext));
447         context->internal_pgm = 1;
448         context->cs_pid = 0;
449         strcpy (sysname, "SYS_");
450         strcat (sysname, name);
451         len = strlen(sysname);
452         memcpy(context->curr_user, sysname, len + 1);
453         context->client_socket = (-1);
454         context->state = CON_SYS;
455         context->ServiceName = name;
456
457         // internal_create_user has the side effect of loading the user regardless of whether they
458         // already existed or needed to be created
459         internal_create_user(sysname, &(context->user), -1) ;
460         
461         // Check to see if the system user needs upgrading
462         if (context->user.usernum == 0) {       // old system user with number 0, upgrade it
463                 context->user.usernum = get_new_user_number();
464                 syslog(LOG_INFO, "context: upgrading system user \"%s\" from user number 0 to user number %ld", context->user.fullname, context->user.usernum);
465                 // add user to the database
466                 CtdlPutUser(&(context->user));
467                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
468         }
469 }
470
471
472 // Cleanup any contexts that are left lying around
473 void context_cleanup(void) {
474         CitContext *ptr = NULL;
475         CitContext *rem = NULL;
476
477         // Clean up the contexts.
478         // There are no threads so no critical_section stuff is needed.
479         ptr = ContextList;
480         
481         // We need to update the ContextList because some modules may want to iterate it
482         // Question is should we NULL it before iterating here or should we just keep updating it as we remove items?
483         // Answer is to NULL it first to prevent modules from doing any actions on the list at all.
484         ContextList=NULL;
485         while (ptr != NULL){
486                 // Remove the session from the active list
487                 rem = ptr->next;
488                 --num_sessions;
489
490                 syslog(LOG_DEBUG, "context: context_cleanup() purging session %d", ptr->cs_pid);
491                 RemoveContext(ptr);
492                 free (ptr);
493                 ptr = rem;
494         }
495 }
496
497
498 // Purge all sessions which have the 'kill_me' flag set.
499 // This function has code to prevent it from running more than once every
500 // few seconds, because running it after every single unbind would waste a lot
501 // of CPU time and keep the context list locked too much.  To force it to run
502 // anyway, set "force" to nonzero.
503 void dead_session_purge(int force) {
504         CitContext *ptr, *ptr2;         // general-purpose utility pointer
505         CitContext *rem = NULL;         // list of sessions to be destroyed
506         
507         if (force == 0) {
508                 if ( (time(NULL) - last_purge) < 5 ) {
509                         return;         // Too soon, go away
510                 }
511         }
512         time(&last_purge);
513
514         begin_critical_section(S_SESSION_TABLE);
515         ptr = ContextList;
516         while (ptr) {
517                 ptr2 = ptr;
518                 ptr = ptr->next;
519                 
520                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
521                         // Remove the session from the active list
522                         if (ptr2->prev) {
523                                 ptr2->prev->next = ptr2->next;
524                         }
525                         else {
526                                 ContextList = ptr2->next;
527                         }
528                         if (ptr2->next) {
529                                 ptr2->next->prev = ptr2->prev;
530                         }
531
532                         --num_sessions;
533                         /* And put it on our to-be-destroyed list */
534                         ptr2->next = rem;
535                         rem = ptr2;
536                 }
537                 //else if (ptr2->kill_me) {
538                         //syslog(LOG_DEBUG, "context: session %d is timed out but non-idle", ptr->cs_pid);
539                 //}
540         }
541         end_critical_section(S_SESSION_TABLE);
542
543         // Now that we no longer have the session list locked, we can take
544         // our time and destroy any sessions on the to-be-killed list, which
545         // is allocated privately on this thread's stack.
546         while (rem != NULL) {
547                 syslog(LOG_DEBUG, "context: dead_session_purge() purging session %d, reason=%d", rem->cs_pid, rem->kill_me);
548                 RemoveContext(rem);
549                 ptr = rem;
550                 rem = rem->next;
551                 free(ptr);
552         }
553 }
554
555
556 // masterCC is the context we use when not attached to a session.  This function initializes it.
557 void InitializeMasterCC(void) {
558         memset(&masterCC, 0, sizeof(struct CitContext));
559         masterCC.internal_pgm = 1;
560         masterCC.cs_pid = 0;
561 }
562
563
564 // Set the "async waiting" flag for a session, if applicable
565 void set_async_waiting(struct CitContext *ccptr) {
566         syslog(LOG_DEBUG, "context: setting async_waiting flag for session %d", ccptr->cs_pid);
567         if (ccptr->is_async) {
568                 ccptr->async_waiting++;
569                 if (ccptr->state == CON_IDLE) {
570                         ccptr->state = CON_READY;
571                 }
572         }
573 }
574
575
576 CTDL_MODULE_INIT(session) {
577         if (!threading) {
578         }
579         return "session";
580 }