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