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