Began removing $Id$ tags. This will be an ongoing process.
[citadel.git] / citadel / server_main.c
1 /*
2  * citserver's main() function lives here.
3  * 
4  * Copyright (c) 1987-2010 by the citadel.org team
5  *
6  * This program is free 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         int have_minus_x=0;
109         char relhome[PATH_MAX]="";
110         char ctdldir[PATH_MAX]=CTDLDIR;
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 #ifdef HAVE_GC
120         GC_INIT();
121         GC_find_leak = 1;
122 #endif
123
124
125         /* initialise semaphores here. Patch by Matt and davew
126          * its called here as they are needed by CtdlLogPrintf for thread safety
127          */
128         InitialiseSemaphores();
129         
130         /* initialize the master context */
131         InitializeMasterCC();
132
133         /* parse command-line arguments */
134         for (a=1; a<argc; ++a) {
135
136                 if (!strncmp(argv[a], "-l", 2)) {
137                         safestrncpy(facility, &argv[a][2], sizeof(facility));
138                         syslog_facility = SyslogFacility(facility);
139                         enable_syslog = 1;
140                 }
141
142                 /* run in the background if -d was specified */
143                 else if (!strcmp(argv[a], "-d")) {
144                         running_as_daemon = 1;
145                 }
146
147                 /* run a few stats if -s was specified */
148                 else if (!strncmp(argv[a], "-s", 2)) {
149                         statcount = atoi(&argv[a][2]);
150                 }
151
152                 /* -x specifies the desired logging level */
153                 else if (!strncmp(argv[a], "-x", 2)) {
154                         verbosity = atoi(&argv[a][2]);
155                         have_minus_x = 1;
156                 }
157
158                 else if (!strncmp(argv[a], "-h", 2)) {
159                         relh=argv[a][2]!='/';
160                         if (!relh) safestrncpy(ctdl_home_directory, &argv[a][2],
161                                                                    sizeof ctdl_home_directory);
162                         else
163                                 safestrncpy(relhome, &argv[a][2],
164                                                         sizeof relhome);
165                         home=1;
166                 }
167
168                 else if (!strncmp(argv[a], "-t", 2)) {
169                         if (freopen(&argv[a][2], "w", stderr) != stderr)
170                         {
171                                 CtdlLogPrintf(CTDL_EMERG, 
172                                               "unable to open your trace log [%s]: %s", 
173                                               &argv[a][2], 
174                                               strerror(errno));
175                                 exit(1);
176                         }
177                         have_log = 1;
178                 }
179
180                 else if (!strncmp(argv[a], "-D", 2)) {
181                         dbg = 1;
182                 }
183
184                 /* -r tells the server not to drop root permissions. don't use
185                  * this unless you know what you're doing. this should be
186                  * removed in the next release if it proves unnecessary. */
187                 else if (!strcmp(argv[a], "-r"))
188                         drop_root_perms = 0;
189
190                 /* any other parameter makes it crash and burn */
191                 else {
192                         CtdlLogPrintf(CTDL_EMERG,       "citserver: usage: "
193                                         "citserver "
194                                         "[-lLogFacility] "
195                                         "[-d] [-D] [-s]"
196                                         " [-tTraceFile]"
197                                         " [-xLogLevel] [-hHomeDir]\n");
198                         exit(1);
199                 }
200
201         }
202
203         if (have_minus_x && running_as_daemon && have_log)
204                 print_to_logfile = 1;
205
206         calc_dirs_n_files(relh, home, relhome, ctdldir, dbg);
207         /* daemonize, if we were asked to */
208         if (running_as_daemon) {
209                 start_daemon(0);
210                 drop_root_perms = 1;
211         }
212
213 #ifdef HAVE_BACKTRACE
214         bzero(&params, sizeof(params));
215         params.filename = file_pid_paniclog;
216         panic_fd=open(file_pid_paniclog, O_APPEND|O_CREAT|O_DIRECT);
217         params.filep = fopen(file_pid_paniclog, "a+");
218         params.debugLevel = ECRASH_DEBUG_VERBOSE;
219         params.dumpAllThreads = TRUE;
220         params.useBacktraceSymbols = 1;
221         params.signals[0]=SIGSEGV;
222         params.signals[1]=SIGILL;
223         params.signals[2]=SIGBUS;
224         params.signals[3]=SIGABRT;
225         eCrash_Init(&params);
226         eCrash_RegisterThread("MasterThread", 0);
227 #endif
228
229         /* Initialize the syslogger.  Yes, we are really using 0 as the
230          * facility, because we are going to bitwise-OR the facility to
231          * the severity of each message, allowing us to write to other
232          * facilities when we need to...
233          */
234         if (enable_syslog) {
235                 openlog("citadel", LOG_NDELAY, 0);
236                 setlogmask(LOG_UPTO(verbosity));
237         }
238         
239         /* Tell 'em who's in da house */
240         CtdlLogPrintf(CTDL_NOTICE, "\n");
241         CtdlLogPrintf(CTDL_NOTICE, "\n");
242         CtdlLogPrintf(CTDL_NOTICE,
243                 "*** Citadel server engine v%d.%02d (build %s) ***\n",
244                 (REV_LEVEL/100), (REV_LEVEL%100), svn_revision());
245         CtdlLogPrintf(CTDL_NOTICE, "Copyright (C) 1987-2010 by the Citadel development team.\n");
246         CtdlLogPrintf(CTDL_NOTICE, "This program is distributed under the terms of the GNU "
247                                         "General Public License.\n");
248         CtdlLogPrintf(CTDL_NOTICE, "\n");
249         CtdlLogPrintf(CTDL_DEBUG, "Called as: %s\n", argv[0]);
250         CtdlLogPrintf(CTDL_INFO, "%s\n", libcitadel_version_string());
251
252         /* Load site-specific parameters, and set the ipgm secret */
253         CtdlLogPrintf(CTDL_INFO, "Loading citadel.config\n");
254         get_config();
255         config.c_ipgm_secret = rand();
256
257         /* get_control() MUST MUST MUST be called BEFORE the databases are opened!! */
258         CtdlLogPrintf(CTDL_INFO, "Acquiring control record\n");
259         get_control();
260
261         put_config();
262
263 #ifdef HAVE_RUN_DIR
264         /* on some dists rundir gets purged on startup. so we need to recreate it. */
265
266         if (stat(ctdl_run_dir, &filestats)==-1){
267 #ifdef HAVE_GETPWUID_R
268 #ifdef SOLARIS_GETPWUID
269                 pwp = getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf));
270 #else // SOLARIS_GETPWUID
271                 getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
272 #endif // SOLARIS_GETPWUID
273 #else // HAVE_GETPWUID_R
274                 pwp = NULL;
275 #endif // HAVE_GETPWUID_R
276
277                 if ((mkdir(ctdl_run_dir, 0755) != 0) && (errno != EEXIST))
278                         CtdlLogPrintf(CTDL_EMERG, 
279                                       "unable to create run directory [%s]: %s", 
280                                       ctdl_run_dir, strerror(errno));
281
282                 if (chown(ctdl_run_dir, config.c_ctdluid, (pwp==NULL)?-1:pw.pw_gid) != 0)
283                         CtdlLogPrintf(CTDL_EMERG, 
284                                       "unable to set the access rights for [%s]: %s", 
285                                       ctdl_run_dir, strerror(errno));
286         }
287                         
288
289 #endif
290
291         /* Initialize... */
292         init_sysdep();
293
294         /*
295          * Do non system dependent startup functions.
296          */
297         master_startup();
298
299         /*
300          * Check that the control record is correct and place sensible values if it isn't
301          */
302         check_control();
303         
304         /*
305          * Run any upgrade entry points
306          */
307         CtdlLogPrintf(CTDL_INFO, "Upgrading modules.\n");
308         upgrade_modules();
309         
310 /**
311  * Load the user for the masterCC or create them if they don't exist
312  */
313         if (CtdlGetUser(&masterCC.user, "SYS_Citadel"))
314         {
315                 /** User doesn't exist. We can't use create user here as the user number needs to be 0 */
316                 strcpy (masterCC.user.fullname, "SYS_Citadel") ;
317                 CtdlPutUser(&masterCC.user);
318                 CtdlGetUser(&masterCC.user, "SYS_Citadel"); /** Just to be safe */
319         }
320         
321         /*
322          * Bind the server to a Unix-domain socket.
323          */
324         CtdlRegisterServiceHook(0,
325                                 file_citadel_socket,
326                                 citproto_begin_session,
327                                 do_command_loop,
328                                 do_async_loop,
329                                 CitadelServiceUDS);
330
331         /*
332          * Bind the server to our favorite TCP port (usually 504).
333          */
334         CtdlRegisterServiceHook(config.c_port_number,
335                                 NULL,
336                                 citproto_begin_session,
337                                 do_command_loop,
338                                 do_async_loop,
339                                 CitadelServiceTCP);
340
341                                 
342         
343         
344         /*
345          * Load any server-side extensions available here.
346          */
347         CtdlLogPrintf(CTDL_INFO, "Initializing server extensions\n");
348         size = strlen(ctdl_home_directory) + 9;
349         
350         initialise_modules(0);
351         
352         
353
354         /*
355          * If we need host auth, start our chkpwd daemon.
356          */
357         if (config.c_auth_mode == AUTHMODE_HOST) {
358                 start_chkpwd_daemon();
359         }
360
361
362         /*
363          * check, whether we're fired up another time after a crash.
364          * if, post an aide message, so the admin has a chance to react.
365          */
366         checkcrash ();
367
368
369         /*
370          * Now that we've bound the sockets, change to the Citadel user id and its
371          * corresponding group ids
372          */
373         if (drop_root_perms) {
374                 cdb_chmod_data();       /* make sure we own our data files */
375
376 #ifdef HAVE_GETPWUID_R
377 #ifdef SOLARIS_GETPWUID
378                 pwp = getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf));
379 #else // SOLARIS_GETPWUID
380                 getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
381 #endif // SOLARIS_GETPWUID
382 #else // HAVE_GETPWUID_R
383                 pwp = NULL;
384 #endif // HAVE_GETPWUID_R
385
386                 if (pwp == NULL)
387                         CtdlLogPrintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
388                                    "Group IDs will be incorrect.\n", (long)CTDLUID,
389                                 strerror(errno));
390                 else {
391                         initgroups(pw.pw_name, pw.pw_gid);
392                         if (setgid(pw.pw_gid))
393                                 CtdlLogPrintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
394                                         strerror(errno));
395                 }
396                 CtdlLogPrintf(CTDL_INFO, "Changing uid to %ld\n", (long)CTDLUID);
397                 if (setuid(CTDLUID) != 0) {
398                         CtdlLogPrintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
399                 }
400 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
401                 prctl(PR_SET_DUMPABLE, 1);
402 #endif
403         }
404
405         /* We want to check for idle sessions once per minute */
406         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
407
408         go_threading();
409         
410         
411         master_cleanup(exit_signal);
412         return(0);
413 }