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