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