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