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