removed StartLibCitadel()
[citadel.git] / citadel / server_main.c
1 /*
2  * citserver's main() function lives here.
3  * 
4  * Copyright (c) 1987-2021 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <stdio.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <grp.h>
20 #include <sys/file.h>
21 #include <libcitadel.h>
22 #include "citserver.h"
23 #include "svn_revision.h"
24 #include "modules_init.h"
25 #include "config.h"
26 #include "control.h"
27 #include "serv_extensions.h"
28 #include "citadel_dirs.h"
29 #include "user_ops.h"
30
31 uid_t ctdluid = 0;
32 const char *CitadelServiceUDS="citadel-UDS";
33 const char *CitadelServiceTCP="citadel-TCP";
34 int sanity_diag_mode = 0;
35
36
37 /*
38  * Create or remove a lock file, so we only have one Citadel Server running at a time.
39  * Set 'op' to nonzero to lock, zero to unlock.
40  */
41 void ctdl_lockfile(int op) {
42         static char lockfilename[PATH_MAX];
43         static FILE *fp;
44
45         if (op) {
46                 syslog(LOG_DEBUG, "main: creating lockfile");
47                 snprintf(lockfilename, sizeof lockfilename, "%s/citadel.lock", ctdl_run_dir);
48                 fp = fopen(lockfilename, "w");
49                 if (!fp) {
50                         syslog(LOG_ERR, "%s: %m", lockfilename);
51                         exit(CTDLEXIT_DB);
52                 }
53                 if (flock(fileno(fp), (LOCK_EX|LOCK_NB)) != 0) {
54                         syslog(LOG_ERR, "main: cannot lock %s , is another citserver running?", lockfilename);
55                         exit(CTDLEXIT_DB);
56                 }
57                 return;
58         }
59
60         syslog(LOG_DEBUG, "main: removing lockfile");
61         unlink(lockfilename);
62         flock(fileno(fp), LOCK_UN);
63         fclose(fp);
64 }
65
66
67 /*
68  * Here's where it all begins.
69  */
70 int main(int argc, char **argv) {
71
72         char facility[32];
73         int a;                  /* General-purpose variables */
74         struct passwd pw, *pwp = NULL;
75         char pwbuf[SIZ];
76         int drop_root_perms = 1;
77         int max_log_level = LOG_INFO;
78         char *ctdldir = CTDLDIR;
79         int syslog_facility = LOG_DAEMON;
80         uid_t u = 0;
81         struct passwd *p = NULL;
82 #ifdef HAVE_RUN_DIR
83         struct stat filestats;
84 #endif
85
86         /* Tell 'em who's in da house */
87         syslog(LOG_INFO, " ");
88         syslog(LOG_INFO, " ");
89         syslog(LOG_INFO, "*** Citadel server engine ***\n");
90         syslog(LOG_INFO, "Version %d (build %s) ***", REV_LEVEL, svn_revision());
91         syslog(LOG_INFO, "Copyright (C) 1987-2021 by the Citadel development team.");
92         syslog(LOG_INFO, " ");
93         syslog(LOG_INFO, "This program is open source software: you can redistribute it and/or");
94         syslog(LOG_INFO, "modify it under the terms of the GNU General Public License, version 3.");
95         syslog(LOG_INFO, " ");
96         syslog(LOG_INFO, "This program is distributed in the hope that it will be useful,");
97         syslog(LOG_INFO, "but WITHOUT ANY WARRANTY; without even the implied warranty of");
98         syslog(LOG_INFO, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the");
99         syslog(LOG_INFO, "GNU General Public License for more details.");
100         syslog(LOG_INFO, " ");
101         syslog(LOG_INFO, "%s", libcitadel_version_string());
102
103         /* parse command-line arguments */
104         while ((a=getopt(argc, argv, "cl:dh:x:t:B:Dru:s:")) != EOF) switch(a) {
105
106                 // test this binary for compatibility and exit
107                 case 'c':
108                         fprintf(stderr, "%s: binary compatibility confirmed\n", argv[0]);
109                         exit(0);
110                         break;
111
112                 // identify the desired syslog facility
113                 case 'l':
114                         safestrncpy(facility, optarg, sizeof(facility));
115                         syslog_facility = SyslogFacility(facility);
116                         break;
117
118                 // run in the background if -d was specified
119                 case 'd':
120                         running_as_daemon = 1;
121                         break;
122
123                 // specify the data directory
124                 case 'h':
125                         ctdldir = optarg;
126                         break;
127
128                 // identify the desired logging severity level
129                 case 'x':
130                         max_log_level = atoi(optarg);
131                         break;
132
133                 // deprecated
134                 case 't':
135                         break;
136
137                 // deprecated
138                 case 'B':
139                         break;
140
141                 // deprecated
142                 case 'D':
143                         break;
144
145                 // -r tells the server not to drop root permissions.
146                 // Don't use this unless you know what you're doing.
147                 case 'r':
148                         drop_root_perms = 0;
149                         break;
150
151                 // -u tells the server what uid to run under...
152                 case 'u':
153                         u = atoi(optarg);
154                         if (u > 0) {
155                                 ctdluid = u;
156                         }
157                         else {
158                                 p = getpwnam(optarg);
159                                 if (p) {
160                                         u = p->pw_uid;
161                                 }
162                         }
163                         if (u > 0) {
164                                 ctdluid = u;
165                         }
166                         break;
167
168                 // -s tells the server to behave differently during sanity checks
169                 case 's':
170                         sanity_diag_mode = atoi(optarg);
171                         break;
172
173                 // any other parameter makes it crash and burn
174                 default:
175                         fprintf(stderr, "citserver: usage: "
176                                         "citserver "
177                                         "[-l LogFacility] "
178                                         "[-x MaxLogLevel] "
179                                         "[-d] [-r] "
180                                         "[-u user] "
181                                         "[-h HomeDir]\n"
182                         );
183                         exit(1);
184         }
185
186         if (chdir(ctdldir) != 0) {
187                 syslog(LOG_ERR, "main: unable to change directory to [%s]: %m", ctdldir);
188                 exit(CTDLEXIT_HOME);
189         }
190         else {
191                 syslog(LOG_INFO, "main: running in data directory %s", ctdldir);
192         }
193
194         if ((ctdluid == 0) && (drop_root_perms == 0)) {
195                 fprintf(stderr, "citserver: cannot determine user to run as; please specify -r or -u options\n");
196                 exit(CTDLEXIT_UNUSER);
197         }
198
199         /* Last ditch effort to determine the user name ... if there's a user called "citadel" then use that */
200         if (ctdluid == 0) {
201                 p = getpwnam("citadel");
202                 if (!p) {
203                         p = getpwnam("bbs");
204                 }
205                 if (!p) {
206                         p = getpwnam("guest");
207                 }
208                 if (p) {
209                         u = p->pw_uid;
210                 }
211                 if (u > 0) {
212                         ctdluid = u;
213                 }
214         }
215
216         /* initialize the master context */
217         InitializeMasterCC();
218         InitializeMasterTSD();
219
220         setlogmask(LOG_UPTO(max_log_level));
221         openlog("citserver",
222                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
223                 syslog_facility
224         );
225
226         /* daemonize, if we were asked to */
227         if (running_as_daemon) {
228                 start_daemon(0);
229                 drop_root_perms = 1;
230         }
231
232         if ((mkdir(ctdl_run_dir, 0755) != 0) && (errno != EEXIST)) {
233                 syslog(LOG_ERR, "main: unable to create run directory [%s]: %m", ctdl_run_dir);
234         }
235
236         if (chown(ctdl_run_dir, ctdluid, (pwp==NULL)?-1:pw.pw_gid) != 0) {
237                 syslog(LOG_ERR, "main: unable to set the access rights for [%s]: %m", ctdl_run_dir);
238         }
239
240         ctdl_lockfile(1);
241         init_sysdep();                                          // Initialize...
242         master_startup();                                       // Do non system dependent startup functions
243         check_control();                                        // Check/sanitize/initialize control record, fix user indexes
244         syslog(LOG_INFO, "main: upgrading modules");            // Run any upgrade entry points
245         upgrade_modules();
246
247         /*
248          * Load the user for the masterCC or create them if they don't exist
249          */
250         if (CtdlGetUser(&masterCC.user, "SYS_Citadel")) {
251                 /* User doesn't exist. We can't use create user here as the user number needs to be 0 */
252                 strcpy (masterCC.user.fullname, "SYS_Citadel") ;
253                 CtdlPutUser(&masterCC.user);
254                 CtdlGetUser(&masterCC.user, "SYS_Citadel");     /* Just to be safe */
255         }
256         
257         /*
258          * Bind the server to a Unix-domain socket (user client access)
259          */
260         CtdlRegisterServiceHook(0,
261                                 file_citadel_socket,
262                                 citproto_begin_session,
263                                 do_command_loop,
264                                 do_async_loop,
265                                 CitadelServiceUDS);
266
267         /*
268          * Bind the server to a Unix-domain socket (admin client access)
269          */
270         CtdlRegisterServiceHook(0,
271                                 file_citadel_admin_socket,
272                                 citproto_begin_admin_session,
273                                 do_command_loop,
274                                 do_async_loop,
275                                 CitadelServiceUDS);
276         chmod(file_citadel_admin_socket, S_IRWXU);      /* for your eyes only */
277
278         /*
279          * Bind the server to our favorite TCP port (usually 504).
280          */
281         CtdlRegisterServiceHook(CtdlGetConfigInt("c_port_number"),
282                                 NULL,
283                                 citproto_begin_session,
284                                 do_command_loop,
285                                 do_async_loop,
286                                 CitadelServiceTCP);
287
288         /*
289          * Load any server-side extensions available here.
290          */
291         syslog(LOG_INFO, "main: initializing server extensions");
292         initialise_modules(0);
293
294         /*
295          * If we need host auth, start our chkpwd daemon.
296          */
297         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
298                 start_chkpwd_daemon();
299         }
300
301         /*
302          * check, whether we're fired up another time after a crash.
303          * if, post an aide message, so the admin has a chance to react.
304          */
305         checkcrash();
306
307         /*
308          * Now that we've bound the sockets, change to the Citadel user id and its corresponding group ids
309          */
310         if (drop_root_perms) {
311                 cdb_chmod_data();       /* make sure we own our data files */
312                 getpwuid_r(ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
313                 if (pwp == NULL)
314                         syslog(LOG_ERR, "main: WARNING, getpwuid(%ld): %m Group IDs will be incorrect.", (long)CTDLUID);
315                 else {
316                         initgroups(pw.pw_name, pw.pw_gid);
317                         if (setgid(pw.pw_gid)) {
318                                 syslog(LOG_ERR, "main: setgid(%ld): %m", (long)pw.pw_gid);
319                         }
320                 }
321                 syslog(LOG_INFO, "main: changing uid to %ld", (long)CTDLUID);
322                 if (setuid(CTDLUID) != 0) {
323                         syslog(LOG_ERR, "main: setuid() failed: %m");
324                 }
325 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
326                 prctl(PR_SET_DUMPABLE, 1);
327 #endif
328         }
329
330         /* We want to check for idle sessions once per minute */
331         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER, PRIO_CLEANUP + 1);
332
333         /* Go into multithreaded mode.  When this call exits, the server is stopping. */
334         go_threading();
335         
336         /* Get ready to shut down the server. */
337         int exit_code = master_cleanup(exit_signal);
338         ctdl_lockfile(0);
339         if (restart_server) {
340                 syslog(LOG_INFO, "main: *** CITADEL SERVER IS RESTARTING ***");
341                 execv(argv[0], argv);
342         }
343         return(exit_code);
344 }