Fixed the bug that prevented DOWN from working properly.
[citadel.git] / citadel / context.c
1 /*
2  * $Id: sysdep.c 7989 2009-10-31 15:29:37Z davew $
3  *
4  * Citadel context management stuff.
5  * See COPYING for copyright information.
6  *
7  * Here's where we (hopefully) have all the code that manipulates contexts.
8  *
9  */
10
11 #include "sysdep.h"
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <stdio.h>
15 #include <fcntl.h>
16 #include <ctype.h>
17 #include <signal.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/wait.h>
21 #include <sys/socket.h>
22 #include <syslog.h>
23 #include <sys/syslog.h>
24
25 #if TIME_WITH_SYS_TIME
26 # include <sys/time.h>
27 # include <time.h>
28 #else
29 # if HAVE_SYS_TIME_H
30 #  include <sys/time.h>
31 # else
32 #  include <time.h>
33 # endif
34 #endif
35
36 #include <limits.h>
37 #include <sys/resource.h>
38 #include <netinet/in.h>
39 #include <netinet/tcp.h>
40 #include <arpa/inet.h>
41 #include <netdb.h>
42 #include <sys/un.h>
43 #include <string.h>
44 #include <pwd.h>
45 #include <errno.h>
46 #include <stdarg.h>
47 #include <grp.h>
48 #include <libcitadel.h>
49 #include "citadel.h"
50 #include "server.h"
51 #include "sysdep_decls.h"
52 #include "citserver.h"
53 #include "support.h"
54 #include "config.h"
55 #include "database.h"
56 #include "housekeeping.h"
57 #include "modules/crypto/serv_crypto.h" /* Needed for init_ssl, client_write_ssl, client_read_ssl, destruct_ssl */
58 #include "ecrash.h"
59
60 #ifdef HAVE_SYS_SELECT_H
61 #include <sys/select.h>
62 #endif
63
64 #ifndef HAVE_SNPRINTF
65 #include "snprintf.h"
66 #endif
67
68 #include "ctdl_module.h"
69 #include "threads.h"
70 #include "user_ops.h"
71 #include "control.h"
72
73
74
75 citthread_key_t MyConKey;                               /* TSD key for MyContext() */
76
77
78 struct CitContext masterCC;
79 struct CitContext *ContextList = NULL;
80 // struct CitContext* next_session = NULL;
81
82 time_t last_purge = 0;                          /* Last dead session purge */
83 int num_sessions = 0;                           /* Current number of sessions */
84
85 /* Flag for single user mode */
86 static int want_single_user = 0;
87
88 /* Try to go single user */
89
90 int CtdlTrySingleUser(void)
91 {
92         int can_do = 0;
93         
94         begin_critical_section(S_SINGLE_USER);
95         if (want_single_user)
96                 can_do = 0;
97         else
98         {
99                 can_do = 1;
100                 want_single_user = 1;
101         }
102         end_critical_section(S_SINGLE_USER);
103         return can_do;
104 }
105
106 void CtdlEndSingleUser(void)
107 {
108         begin_critical_section(S_SINGLE_USER);
109         want_single_user = 0;
110         end_critical_section(S_SINGLE_USER);
111 }
112
113
114 int CtdlWantSingleUser(void)
115 {
116         return want_single_user;
117 }
118
119 int CtdlIsSingleUser(void)
120 {
121         if (want_single_user)
122         {
123                 /* check for only one context here */
124                 if (num_sessions == 1)
125                         return TRUE;
126         }
127         return FALSE;
128 }
129
130
131 /*
132  * Return a pointer to the CitContext structure bound to the thread which
133  * called this function.  If there's no such binding (for example, if it's
134  * called by the housekeeper thread) then a generic 'master' CC is returned.
135  *
136  * This function is used *VERY* frequently and must be kept small.
137  */
138 struct CitContext *MyContext(void) {
139
140         register struct CitContext *c;
141
142         return ((c = (struct CitContext *) citthread_getspecific(MyConKey),
143                 c == NULL) ? &masterCC : c
144         );
145 }
146
147
148
149
150 /*
151  * Terminate a session.
152  */
153 void RemoveContext (struct CitContext *con)
154 {
155         if (con==NULL) {
156                 CtdlLogPrintf(CTDL_ERR,
157                         "WARNING: RemoveContext() called with NULL!\n");
158                 return;
159         }
160         CtdlLogPrintf(CTDL_DEBUG, "RemoveContext() session %d\n", con->cs_pid);
161
162         /* Run any cleanup routines registered by loadable modules.
163          * Note: We have to "become_session()" because the cleanup functions
164          *       might make references to "CC" assuming it's the right one.
165          */
166         become_session(con);
167         logout();
168         PerformSessionHooks(EVT_STOP);
169         become_session(NULL);
170
171         CtdlLogPrintf(CTDL_NOTICE, "[%3d] Session ended.\n", con->cs_pid);
172
173         /* If the client is still connected, blow 'em away. */
174         CtdlLogPrintf(CTDL_DEBUG, "Closing socket %d\n", con->client_socket);
175         close(con->client_socket);
176
177         /* If using AUTHMODE_LDAP, free the DN */
178         if (con->ldap_dn) {
179                 free(con->ldap_dn);
180                 con->ldap_dn = NULL;
181         }
182
183         CtdlLogPrintf(CTDL_DEBUG, "Done with RemoveContext()\n");
184 }
185
186
187
188
189
190 /*
191  * Initialize a new context and place it in the list.  The session number
192  * used to be the PID (which is why it's called cs_pid), but that was when we
193  * had one process per session.  Now we just assign them sequentially, starting
194  * at 1 (don't change it to 0 because masterCC uses 0).
195  */
196 struct CitContext *CreateNewContext(void) {
197         struct CitContext *me;
198         static int next_pid = 0;
199
200         me = (struct CitContext *) malloc(sizeof(struct CitContext));
201         if (me == NULL) {
202                 CtdlLogPrintf(CTDL_ALERT, "citserver: can't allocate memory!!\n");
203                 return NULL;
204         }
205
206         memset(me, 0, sizeof(struct CitContext));
207         
208         /* Give the contaxt a name. Hopefully makes it easier to track */
209         strcpy (me->user.fullname, "SYS_notauth");
210         
211         /* The new context will be created already in the CON_EXECUTING state
212          * in order to prevent another thread from grabbing it while it's
213          * being set up.
214          */
215         me->state = CON_EXECUTING;
216         /*
217          * Generate a unique session number and insert this context into
218          * the list.
219          */
220         begin_critical_section(S_SESSION_TABLE);
221         me->cs_pid = ++next_pid;
222         me->prev = NULL;
223         me->next = ContextList;
224         ContextList = me;
225         if (me->next != NULL) {
226                 me->next->prev = me;
227         }
228         ++num_sessions;
229         end_critical_section(S_SESSION_TABLE);
230         return (me);
231 }
232
233
234 struct CitContext *CtdlGetContextArray(int *count)
235 {
236         int nContexts, i;
237         struct CitContext *nptr, *cptr;
238         
239         nContexts = num_sessions;
240         nptr = malloc(sizeof(struct CitContext) * nContexts);
241         if (!nptr)
242                 return NULL;
243         begin_critical_section(S_SESSION_TABLE);
244         for (cptr = ContextList, i=0; cptr != NULL && i < nContexts; cptr = cptr->next, i++)
245                 memcpy(&nptr[i], cptr, sizeof (struct CitContext));
246         end_critical_section (S_SESSION_TABLE);
247         
248         *count = i;
249         return nptr;
250 }
251
252
253
254 /**
255  * This function fills in a context and its user field correctly
256  * Then creates/loads that user
257  */
258 void CtdlFillSystemContext(struct CitContext *context, char *name)
259 {
260         char sysname[USERNAME_SIZE];
261
262         memset(context, 0, sizeof(struct CitContext));
263         context->internal_pgm = 1;
264         context->cs_pid = 0;
265         strcpy (sysname, "SYS_");
266         strcat (sysname, name);
267         /* internal_create_user has the side effect of loading the user regardless of wether they
268          * already existed or needed to be created
269          */
270         internal_create_user (sysname, &(context->user), -1) ;
271         
272         /* Check to see if the system user needs upgrading */
273         if (context->user.usernum == 0)
274         {       /* old system user with number 0, upgrade it */
275                 context->user.usernum = get_new_user_number();
276                 CtdlLogPrintf(CTDL_DEBUG, "Upgrading system user \"%s\" from user number 0 to user number %d\n", context->user.fullname, context->user.usernum);
277                 /* add user to the database */
278                 CtdlPutUser(&(context->user));
279                 cdb_store(CDB_USERSBYNUMBER, &(context->user.usernum), sizeof(long), context->user.fullname, strlen(context->user.fullname)+1);
280         }
281 }
282
283 /*
284  * Cleanup any contexts that are left lying around
285  */
286 void context_cleanup(void)
287 {
288         struct CitContext *ptr = NULL;
289         struct CitContext *rem = NULL;
290
291         /*
292          * Clean up the contexts.
293          * There are no threads so no critical_section stuff is needed.
294          */
295         ptr = ContextList;
296         
297         /* We need to update the ContextList because some modules may want to itterate it
298          * Question is should we NULL it before iterating here or should we just keep updating it
299          * as we remove items?
300          *
301          * Answer is to NULL it first to prevent modules from doing any actions on the list at all
302          */
303         ContextList=NULL;
304         while (ptr != NULL){
305                 /* Remove the session from the active list */
306                 rem = ptr->next;
307                 --num_sessions;
308                 
309                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", ptr->cs_pid);
310                 RemoveContext(ptr);
311                 free (ptr);
312                 ptr = rem;
313         }
314 }
315
316
317
318 /*
319  * Terminate another session.
320  * (This could justifiably be moved out of sysdep.c because it
321  * no longer does anything that is system-dependent.)
322  */
323 void kill_session(int session_to_kill) {
324         struct CitContext *ptr;
325
326         begin_critical_section(S_SESSION_TABLE);
327         for (ptr = ContextList; ptr != NULL; ptr = ptr->next) {
328                 if (ptr->cs_pid == session_to_kill) {
329                         ptr->kill_me = 1;
330                 }
331         }
332         end_critical_section(S_SESSION_TABLE);
333 }
334
335 /*
336  * Purge all sessions which have the 'kill_me' flag set.
337  * This function has code to prevent it from running more than once every
338  * few seconds, because running it after every single unbind would waste a lot
339  * of CPU time and keep the context list locked too much.  To force it to run
340  * anyway, set "force" to nonzero.
341  */
342 void dead_session_purge(int force) {
343         struct CitContext *ptr, *ptr2;          /* general-purpose utility pointer */
344         struct CitContext *rem = NULL;  /* list of sessions to be destroyed */
345         
346         if (force == 0) {
347                 if ( (time(NULL) - last_purge) < 5 ) {
348                         return; /* Too soon, go away */
349                 }
350         }
351         time(&last_purge);
352
353         if (try_critical_section(S_SESSION_TABLE))
354                 return;
355                 
356         ptr = ContextList;
357         while (ptr) {
358                 ptr2 = ptr;
359                 ptr = ptr->next;
360                 
361                 if ( (ptr2->state == CON_IDLE) && (ptr2->kill_me) ) {
362                         /* Remove the session from the active list */
363                         if (ptr2->prev) {
364                                 ptr2->prev->next = ptr2->next;
365                         }
366                         else {
367                                 ContextList = ptr2->next;
368                         }
369                         if (ptr2->next) {
370                                 ptr2->next->prev = ptr2->prev;
371                         }
372
373                         --num_sessions;
374                         /* And put it on our to-be-destroyed list */
375                         ptr2->next = rem;
376                         rem = ptr2;
377                 }
378         }
379         end_critical_section(S_SESSION_TABLE);
380
381         /* Now that we no longer have the session list locked, we can take
382          * our time and destroy any sessions on the to-be-killed list, which
383          * is allocated privately on this thread's stack.
384          */
385         while (rem != NULL) {
386                 CtdlLogPrintf(CTDL_DEBUG, "Purging session %d\n", rem->cs_pid);
387                 RemoveContext(rem);
388                 ptr = rem;
389                 rem = rem->next;
390                 free(ptr);
391         }
392 }
393
394
395
396
397
398 /*
399  * masterCC is the context we use when not attached to a session.  This
400  * function initializes it.
401  */
402 void InitializeMasterCC(void) {
403         memset(&masterCC, 0, sizeof(struct CitContext));
404         masterCC.internal_pgm = 1;
405         masterCC.cs_pid = 0;
406 }
407
408
409
410
411 /*
412  * Bind a thread to a context.  (It's inline merely to speed things up.)
413  */
414 INLINE void become_session(struct CitContext *which_con) {
415         citthread_setspecific(MyConKey, (void *)which_con );
416 }
417
418
419