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