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