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