Added code to rebuild citadel.control if it gets deleted some how.
[citadel.git] / citadel / server_main.c
1 /*
2  * citserver's main() function lives here.
3  *
4  * $Id$
5  */
6
7 #include "sysdep.h"
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <fcntl.h>
12 #include <ctype.h>
13 #include <signal.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <sys/wait.h>
17 #include <sys/socket.h>
18 #include <syslog.h>
19
20 #if TIME_WITH_SYS_TIME
21 # include <sys/time.h>
22 # include <time.h>
23 #else
24 # if HAVE_SYS_TIME_H
25 #  include <sys/time.h>
26 # else
27 #  include <time.h>
28 # endif
29 #endif
30
31 #include <limits.h>
32 #include <netinet/in.h>
33 #include <netdb.h>
34 #include <sys/un.h>
35 #include <string.h>
36 #include <pwd.h>
37 #include <errno.h>
38 #include <stdarg.h>
39 #include <grp.h>
40 #include <pwd.h>
41 #ifdef HAVE_PTHREAD_H
42 #include <pthread.h>
43 #endif
44 #ifdef HAVE_SYS_PRCTL_H
45 #include <sys/prctl.h>
46 #endif
47 #include "citadel.h"
48 #include "server.h"
49 #include "serv_extensions.h"
50 #include "sysdep_decls.h"
51 #include "citserver.h"
52 #include "support.h"
53 #include "config.h"
54 #include "control.h"
55 #include "database.h"
56 #include "user_ops.h"
57 #include "housekeeping.h"
58 #include "tools.h"
59 #include "citadel_dirs.c"
60
61 #include "modules_init.h"
62 #include "ecrash.h"
63
64 #ifdef HAVE_SYS_SELECT_H
65 #include <sys/select.h>
66 #endif
67
68 #ifndef HAVE_SNPRINTF
69 #include "snprintf.h"
70 #endif
71 const char *CitadelServiceUDS="citadel-UDS";
72 const char *CitadelServiceTCP="citadel-TCP";
73
74 /*
75  * Here's where it all begins.
76  */
77 int main(int argc, char **argv)
78 {
79         char facility[32];
80         int a, i;                       /* General-purpose variables */
81         struct passwd pw, *pwp = NULL;
82         char pwbuf[SIZ];
83         int drop_root_perms = 1;
84         size_t size;
85         int relh=0;
86         int home=0;
87         char relhome[PATH_MAX]="";
88         char ctdldir[PATH_MAX]=CTDLDIR;
89 #ifdef HAVE_RUN_DIR
90         struct stat filestats;
91 #endif
92 #ifdef HAVE_BACKTRACE
93         eCrashParameters params;
94 //      eCrashSymbolTable symbol_table;
95 #endif
96         /* initialise semaphores here. Patch by Matt and davew
97          * its called here as they are needed by lprintf for thread safety
98          */
99         InitialiseSemaphores();
100         
101         /* initialize the master context */
102         InitializeMasterCC();
103
104         /* parse command-line arguments */
105         for (a=1; a<argc; ++a) {
106
107                 if (!strncmp(argv[a], "-l", 2)) {
108                         safestrncpy(facility, &argv[a][2], sizeof(facility));
109                         syslog_facility = SyslogFacility(facility);
110                         enable_syslog = 1;
111                 }
112
113                 /* run in the background if -d was specified */
114                 else if (!strcmp(argv[a], "-d")) {
115                         running_as_daemon = 1;
116                 }
117
118                 /* -x specifies the desired logging level */
119                 else if (!strncmp(argv[a], "-x", 2)) {
120                         verbosity = atoi(&argv[a][2]);
121                 }
122
123                 else if (!strncmp(argv[a], "-h", 2)) {
124                         relh=argv[a][2]!='/';
125                         if (!relh) safestrncpy(ctdl_home_directory, &argv[a][2],
126                                                                    sizeof ctdl_home_directory);
127                         else
128                                 safestrncpy(relhome, &argv[a][2],
129                                                         sizeof relhome);
130                         home_specified = 1;
131                         home=1;
132                 }
133
134                 else if (!strncmp(argv[a], "-t", 2)) {
135                         freopen(&argv[a][2], "w", stderr);
136                 }
137
138                 else if (!strncmp(argv[a], "-f", 2)) {
139                         do_defrag = 1;
140                 }
141
142                 /* -r tells the server not to drop root permissions. don't use
143                  * this unless you know what you're doing. this should be
144                  * removed in the next release if it proves unnecessary. */
145                 else if (!strcmp(argv[a], "-r"))
146                         drop_root_perms = 0;
147
148                 /* any other parameter makes it crash and burn */
149                 else {
150                         lprintf(CTDL_EMERG,     "citserver: usage: "
151                                         "citserver "
152                                         "[-lLogFacility] "
153                                         "[-d] [-f]"
154                                         " [-tTraceFile]"
155                                         " [-xLogLevel] [-hHomeDir]\n");
156                         exit(1);
157                 }
158
159         }
160
161         calc_dirs_n_files(relh, home, relhome, ctdldir);
162         /* daemonize, if we were asked to */
163         if (running_as_daemon) {
164                 start_daemon(0);
165                 drop_root_perms = 1;
166         }
167
168 #ifdef HAVE_BACKTRACE
169         bzero(&params, sizeof(params));
170         params.filename = file_pid_paniclog;
171         panic_fd=open(file_pid_paniclog, O_APPEND|O_CREAT|O_DIRECT);
172         params.filep = fopen(file_pid_paniclog, "a+");
173         params.debugLevel = ECRASH_DEBUG_VERBOSE;
174         params.dumpAllThreads = TRUE;
175         params.useBacktraceSymbols = 1;
176 ///     BuildSymbolTable(&symbol_table);
177 //      params.symbolTable = &symbol_table;
178         params.signals[0]=SIGSEGV;
179         params.signals[1]=SIGILL;
180         params.signals[2]=SIGBUS;
181         params.signals[3]=SIGABRT;
182
183         eCrash_Init(&params);
184                 
185         eCrash_RegisterThread("MasterThread", 0);
186
187 ///     signal(SIGSEGV, cit_panic_backtrace);
188 #endif
189         /* Initialize the syslogger.  Yes, we are really using 0 as the
190          * facility, because we are going to bitwise-OR the facility to
191          * the severity of each message, allowing us to write to other
192          * facilities when we need to...
193          */
194         if (enable_syslog) {
195                 openlog("citadel", LOG_NDELAY, 0);
196                 setlogmask(LOG_UPTO(verbosity));
197         }
198         
199         /* Tell 'em who's in da house */
200         lprintf(CTDL_NOTICE, "\n");
201         lprintf(CTDL_NOTICE, "\n");
202         lprintf(CTDL_NOTICE,
203                 "*** Citadel server engine v%d.%02d ***\n",
204                 (REV_LEVEL/100), (REV_LEVEL%100));
205         lprintf(CTDL_NOTICE,
206                 "Copyright (C) 1987-2007 by the Citadel development team.\n");
207         lprintf(CTDL_NOTICE,
208                 "This program is distributed under the terms of the GNU "
209                 "General Public License.\n");
210         lprintf(CTDL_NOTICE, "\n");
211         lprintf(CTDL_DEBUG, "Called as: %s\n", argv[0]);
212
213         /* Load site-specific parameters, and set the ipgm secret */
214         lprintf(CTDL_INFO, "Loading citadel.config\n");
215         get_config();
216         config.c_ipgm_secret = rand();
217         put_config();
218
219 #ifdef HAVE_RUN_DIR
220         /* on some dists rundir gets purged on startup. so we need to recreate it. */
221
222         if (stat(ctdl_run_dir, &filestats)==-1){
223 #ifdef SOLARIS_GETPWUID
224                 pwp = getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf));
225 #else
226                 getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
227 #endif
228                 mkdir(ctdl_run_dir, 0755);
229                 chown(ctdl_run_dir, config.c_ctdluid, (pwp==NULL)?-1:pw.pw_gid);
230         }
231                         
232
233 #endif
234
235         /* Initialize... */
236         init_sysdep();
237
238         /*
239          * Do non system dependent startup functions.
240          */
241         master_startup();
242
243         lprintf(CTDL_INFO, "Acquiring control record\n");
244         get_control();
245
246         /*
247          * Bind the server to a Unix-domain socket.
248          */
249         CtdlRegisterServiceHook(0,
250                                 file_citadel_socket,
251                                 citproto_begin_session,
252                                 do_command_loop,
253                                 do_async_loop,
254                                 CitadelServiceUDS);
255
256         /*
257          * Bind the server to our favorite TCP port (usually 504).
258          */
259         CtdlRegisterServiceHook(config.c_port_number,
260                                 NULL,
261                                 citproto_begin_session,
262                                 do_command_loop,
263                                 do_async_loop,
264                                 CitadelServiceTCP);
265
266         /*
267          * Load any server-side extensions available here.
268          */
269         lprintf(CTDL_INFO, "Initializing server extensions\n");
270         size = strlen(ctdl_home_directory) + 9;
271         
272 /*
273         initialize_server_extensions();
274 */
275         
276         initialise_modules();
277         
278         
279
280         /*
281          * If we need host auth, start our chkpwd daemon.
282          */
283         if (config.c_auth_mode == 1) {
284                 start_chkpwd_daemon();
285         }
286
287         /*
288          * Now that we've bound the sockets, change to the Citadel user id and its
289          * corresponding group ids
290          */
291         if (drop_root_perms) {
292                 cdb_chmod_data();       /* make sure we own our data files */
293
294 #ifdef SOLARIS_GETPWUID
295                 pwp = getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf));
296 #else
297                 getpwuid_r(config.c_ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
298 #endif
299                 if (pwp == NULL)
300                         lprintf(CTDL_CRIT, "WARNING: getpwuid(%ld): %s\n"
301                                    "Group IDs will be incorrect.\n", (long)CTDLUID,
302                                 strerror(errno));
303                 else {
304                         initgroups(pw.pw_name, pw.pw_gid);
305                         if (setgid(pw.pw_gid))
306                                 lprintf(CTDL_CRIT, "setgid(%ld): %s\n", (long)pw.pw_gid,
307                                         strerror(errno));
308                 }
309                 lprintf(CTDL_INFO, "Changing uid to %ld\n", (long)CTDLUID);
310                 if (setuid(CTDLUID) != 0) {
311                         lprintf(CTDL_CRIT, "setuid() failed: %s\n", strerror(errno));
312                 }
313 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
314                 prctl(PR_SET_DUMPABLE, 1);
315 #endif
316         }
317
318         /* We want to check for idle sessions once per minute */
319         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER);
320
321         /*
322          * Now create a bunch of worker threads.
323          */
324         lprintf(CTDL_DEBUG, "Starting %d worker threads\n",
325                 config.c_min_workers-1);
326         begin_critical_section(S_WORKER_LIST);
327         for (i=0; i<(config.c_min_workers-1); ++i) {
328                 create_worker();
329         }
330         end_critical_section(S_WORKER_LIST);
331
332         /* Create the maintenance threads. */
333         create_maintenance_threads();
334
335         /* This thread is now useless.  It can't be turned into a worker
336          * thread because its stack is too small, but it can't be killed
337          * either because the whole server process would exit.  So we just
338          * join to the first worker thread and exit when it exits.
339          */
340         pthread_join(worker_list->tid, NULL);
341         master_cleanup(0);
342         return(0);
343 }