Moved all of the background tasks back to the old EVT_TIMER style
[citadel.git] / citadel / server_main.c
1 /*
2  * citserver's main() function lives here.
3  * 
4  * Copyright (c) 1987-2011 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  */
20
21 #include "sysdep.h"
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <ctype.h>
27 #include <signal.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31 #include <sys/socket.h>
32 #include <syslog.h>
33
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
36 # include <time.h>
37 #else
38 # if HAVE_SYS_TIME_H
39 #  include <sys/time.h>
40 # else
41 #  include <time.h>
42 # endif
43 #endif
44
45 #include <limits.h>
46 #include <netinet/in.h>
47 #include <netdb.h>
48 #include <sys/un.h>
49 #include <string.h>
50 #include <pwd.h>
51 #include <errno.h>
52 #include <stdarg.h>
53 #include <grp.h>
54 #include <pwd.h>
55 #ifdef HAVE_SYS_PRCTL_H
56 #include <sys/prctl.h>
57 #endif
58 #include <libcitadel.h>
59 #include "citadel.h"
60 #include "server.h"
61 #include "serv_extensions.h"
62 #include "sysdep_decls.h"
63 #include "threads.h"
64 #include "citserver.h"
65 #include "support.h"
66 #include "config.h"
67 #include "control.h"
68 #include "database.h"
69 #include "user_ops.h"
70 #include "housekeeping.h"
71 #include "svn_revision.h"
72 #include "citadel_dirs.h"
73
74 #include "context.h"
75
76 #include "modules_init.h"
77 #include "ecrash.h"
78
79 #ifdef HAVE_SYS_SELECT_H
80 #include <sys/select.h>
81 #endif
82
83 #ifndef HAVE_SNPRINTF
84 #include "snprintf.h"
85 #endif
86 const char *CitadelServiceUDS="citadel-UDS";
87 const char *CitadelServiceTCP="citadel-TCP";
88
89
90
91 void go_threading(void);
92
93 /*
94  * Here's where it all begins.
95  */
96 int main(int argc, char **argv)
97 {
98         char facility[32];
99         int a;                  /* General-purpose variables */
100         struct passwd pw, *pwp = NULL;
101         char pwbuf[SIZ];
102         int drop_root_perms = 1;
103         size_t size;
104         int relh=0;
105         int home=0;
106         int dbg=0;
107         int have_log=0;
108         char relhome[PATH_MAX]="";
109         char ctdldir[PATH_MAX]=CTDLDIR;
110         int syslog_facility = LOG_DAEMON;
111 #ifdef HAVE_RUN_DIR
112         struct stat filestats;
113 #endif
114 #ifdef HAVE_BACKTRACE
115         eCrashParameters params;
116 //      eCrashSymbolTable symbol_table;
117 #endif
118
119         /* initialise semaphores here. Patch by Matt and davew
120          * its called here as they are needed by syslog for thread safety
121          */
122         InitialiseSemaphores();
123         
124         /* initialize the master context */
125         InitializeMasterCC();
126
127         /* parse command-line arguments */
128         for (a=1; a<argc; ++a) {
129
130                 if (!strncmp(argv[a], "-l", 2)) {
131                         safestrncpy(facility, &argv[a][2], sizeof(facility));
132                         syslog_facility = SyslogFacility(facility);
133                 }
134
135                 /* run in the background if -d was specified */
136                 else if (!strcmp(argv[a], "-d")) {
137                         running_as_daemon = 1;
138                 }
139
140                 else if (!strncmp(argv[a], "-h", 2)) {
141                         relh=argv[a][2]!='/';
142                         if (!relh) safestrncpy(ctdl_home_directory, &argv[a][2],
143                                                                    sizeof ctdl_home_directory);
144                         else
145                                 safestrncpy(relhome, &argv[a][2],
146                                                         sizeof relhome);
147                         home=1;
148                 }
149
150                 else if (!strncmp(argv[a], "-x", 2)) {
151                         /* deprecated */
152                 }
153
154                 else if (!strncmp(argv[a], "-t", 2)) {
155                         if (freopen(&argv[a][2], "w", stderr) != stderr)
156                         {
157                                 syslog(LOG_EMERG, 
158                                               "unable to open your trace log [%s]: %s", 
159                                               &argv[a][2], 
160                                               strerror(errno));
161                                 exit(1);
162                         }
163                         have_log = 1;
164                 }
165
166                 else if (!strncmp(argv[a], "-D", 2)) {
167                         dbg = 1;
168                 }
169
170                 /* -r tells the server not to drop root permissions. don't use
171                  * this unless you know what you're doing. this should be
172                  * removed in the next release if it proves unnecessary. */
173                 else if (!strcmp(argv[a], "-r"))
174                         drop_root_perms = 0;
175
176                 /* any other parameter makes it crash and burn */
177                 else {
178                         fprintf(stderr, "citserver: usage: "
179                                         "citserver "
180                                         "[-lLogFacility] "
181                                         "[-d] [-D] [-s] "
182                                         "[-tTraceFile] "
183                                         "[-hHomeDir]\n"
184                         );
185                         exit(1);
186                 }
187
188         }
189
190         openlog("citserver",
191                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
192                 syslog_facility
193         );
194
195         calc_dirs_n_files(relh, home, relhome, ctdldir, dbg);
196         /* daemonize, if we were asked to */
197         if (running_as_daemon) {
198                 start_daemon(0);
199                 drop_root_perms = 1;
200         }
201
202 #ifdef HAVE_BACKTRACE
203         bzero(&params, sizeof(params));
204         params.filename = file_pid_paniclog;
205         panic_fd=open(file_pid_paniclog, O_APPEND|O_CREAT|O_DIRECT);
206         params.filep = fopen(file_pid_paniclog, "a+");
207         params.debugLevel = ECRASH_DEBUG_VERBOSE;
208         params.dumpAllThreads = TRUE;
209         params.useBacktraceSymbols = 1;
210         params.signals[0]=SIGSEGV;
211         params.signals[1]=SIGILL;
212         params.signals[2]=SIGBUS;
213         params.signals[3]=SIGABRT;
214         eCrash_Init(&params);
215         eCrash_RegisterThread("MasterThread", 0);
216 #endif
217
218         /* Tell 'em who's in da house */
219         syslog(LOG_NOTICE, "\n");
220         syslog(LOG_NOTICE, "\n");
221         syslog(LOG_NOTICE,
222                 "*** Citadel server engine v%d.%02d (build %s) ***\n",
223                 (REV_LEVEL/100), (REV_LEVEL%100), svn_revision());
224         syslog(LOG_NOTICE, "Copyright (C) 1987-2010 by the Citadel development team.\n");
225         syslog(LOG_NOTICE, "This program is distributed under the terms of the GNU "
226                                         "General Public License.\n");
227         syslog(LOG_NOTICE, "\n");
228         syslog(LOG_DEBUG, "Called as: %s\n", argv[0]);
229         syslog(LOG_INFO, "%s\n", libcitadel_version_string());
230
231         /* Load site-specific parameters, and set the ipgm secret */
232         syslog(LOG_INFO, "Loading citadel.config\n");
233         get_config();
234         config.c_ipgm_secret = rand();
235
236         /* get_control() MUST MUST MUST be called BEFORE the databases are opened!! */
237         syslog(LOG_INFO, "Acquiring control record\n");
238         get_control();
239
240         put_config();
241
242 #ifdef HAVE_RUN_DIR
243         /* on some dists rundir gets purged on startup. so we need to recreate it. */
244
245         if (stat(ctdl_run_dir, &filestats)==-1){
246 #ifdef HAVE_GETPWUID_R
247 #ifdef SOLARIS_GETPWUID
248                 pwp = getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf));
249 #else // SOLARIS_GETPWUID
250                 getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
251 #endif // SOLARIS_GETPWUID
252 #else // HAVE_GETPWUID_R
253                 pwp = NULL;
254 #endif // HAVE_GETPWUID_R
255
256                 if ((mkdir(ctdl_run_dir, 0755) != 0) && (errno != EEXIST))
257                         syslog(LOG_EMERG, 
258                                       "unable to create run directory [%s]: %s", 
259                                       ctdl_run_dir, strerror(errno));
260
261                 if (chown(ctdl_run_dir, config.c_ctdluid, (pwp==NULL)?-1:pw.pw_gid) != 0)
262                         syslog(LOG_EMERG, 
263                                       "unable to set the access rights for [%s]: %s", 
264                                       ctdl_run_dir, strerror(errno));
265         }
266                         
267
268 #endif
269
270         /* Initialize... */
271         init_sysdep();
272
273         /*
274          * Do non system dependent startup functions.
275          */
276         master_startup();
277
278         /*
279          * Check that the control record is correct and place sensible values if it isn't
280          */
281         check_control();
282         
283         /*
284          * Run any upgrade entry points
285          */
286         syslog(LOG_INFO, "Upgrading modules.\n");
287         upgrade_modules();
288         
289 /**
290  * Load the user for the masterCC or create them if they don't exist
291  */
292         if (CtdlGetUser(&masterCC.user, "SYS_Citadel"))
293         {
294                 /** User doesn't exist. We can't use create user here as the user number needs to be 0 */
295                 strcpy (masterCC.user.fullname, "SYS_Citadel") ;
296                 CtdlPutUser(&masterCC.user);
297                 CtdlGetUser(&masterCC.user, "SYS_Citadel"); /** Just to be safe */
298         }
299         
300         /*
301          * Bind the server to a Unix-domain socket.
302          */
303         CtdlRegisterServiceHook(0,
304                                 file_citadel_socket,
305                                 citproto_begin_session,
306                                 do_command_loop,
307                                 do_async_loop,
308                                 CitadelServiceUDS);
309
310         /*
311          * Bind the server to our favorite TCP port (usually 504).
312          */
313         CtdlRegisterServiceHook(config.c_port_number,
314                                 NULL,
315                                 citproto_begin_session,
316                                 do_command_loop,
317                                 do_async_loop,
318                                 CitadelServiceTCP);
319
320                                 
321         
322         
323         /*
324          * Load any server-side extensions available here.
325          */
326         syslog(LOG_INFO, "Initializing server extensions\n");
327         size = strlen(ctdl_home_directory) + 9;
328         
329         initialise_modules(0);
330         
331         
332
333         /*
334          * If we need host auth, start our chkpwd daemon.
335          */
336         if (config.c_auth_mode == AUTHMODE_HOST) {
337                 start_chkpwd_daemon();
338         }
339
340
341         /*
342          * check, whether we're fired up another time after a crash.
343          * if, post an aide message, so the admin has a chance to react.
344          */
345         checkcrash ();
346
347
348         /*
349          * Now that we've bound the sockets, change to the Citadel user id and its
350          * corresponding group ids
351          */
352         if (drop_root_perms) {
353                 cdb_chmod_data();       /* make sure we own our data files */
354
355 #ifdef HAVE_GETPWUID_R
356 #ifdef SOLARIS_GETPWUID
357                 pwp = getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf));
358 #else // SOLARIS_GETPWUID
359                 getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
360 #endif // SOLARIS_GETPWUID
361 #else // HAVE_GETPWUID_R
362                 pwp = NULL;
363 #endif // HAVE_GETPWUID_R
364
365                 if (pwp == NULL)
366                         syslog(LOG_CRIT, "WARNING: getpwuid(%ld): %s\n"
367                                    "Group IDs will be incorrect.\n", (long)CTDLUID,
368                                 strerror(errno));
369                 else {
370                         initgroups(pw.pw_name, pw.pw_gid);
371                         if (setgid(pw.pw_gid))
372                                 syslog(LOG_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
373                                         strerror(errno));
374                 }
375                 syslog(LOG_INFO, "Changing uid to %ld\n", (long)CTDLUID);
376                 if (setuid(CTDLUID) != 0) {
377                         syslog(LOG_CRIT, "setuid() failed: %s\n", strerror(errno));
378                 }
379 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
380                 prctl(PR_SET_DUMPABLE, 1);
381 #endif
382         }
383
384         /* We want to check for idle sessions once per minute */
385         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
386
387         go_threading();
388         
389         master_cleanup(exit_signal);
390         return(0);
391 }