]> code.citadel.org Git - citadel.git/blob - citadel/server/server_main.c
150e313135e9d0d22e54038d20dd2589abfc8a4e
[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         struct passwd pw, *pwp = NULL;
68         char pwbuf[SIZ];
69         int drop_root_perms = 1;
70         int max_log_level = LOG_INFO;
71         char *ctdldir = CTDLDIR;
72         int syslog_facility = LOG_DAEMON;
73         uid_t u = 0;
74         struct passwd *p = NULL;
75 #ifdef HAVE_RUN_DIR
76         struct stat filestats;
77 #endif
78
79         // Tell 'em who's in da house
80         syslog(LOG_INFO, " ");
81         syslog(LOG_INFO, " ");
82         syslog(LOG_INFO, "*** Citadel server engine ***\n");
83         syslog(LOG_INFO, "Version %d (build %s) ***", REV_LEVEL, BUILD_ID);
84         syslog(LOG_INFO, "Copyright (C) 1987-2022 by the Citadel development team.");
85         syslog(LOG_INFO, " ");
86         syslog(LOG_INFO, "This program is open source software.  Use, duplication, or disclosure");
87         syslog(LOG_INFO, "is subject to the terms of the GNU General Public License, version 3.");
88         syslog(LOG_INFO, " ");
89         syslog(LOG_INFO, "%s", libcitadel_version_string());
90
91         // parse command-line arguments
92         int g;
93         while ((g=getopt(argc, argv, "cl:dh:x:t:B:Dru:s:")) != EOF) switch(g) {
94
95                 // test this binary for compatibility and exit
96                 case 'c':
97                         fprintf(stderr, "%s: binary compatibility confirmed\n", argv[0]);
98                         exit(0);
99                         break;
100
101                 // identify the desired syslog facility
102                 case 'l':
103                         safestrncpy(facility, optarg, sizeof(facility));
104                         syslog_facility = SyslogFacility(facility);
105                         break;
106
107                 // run in the background if -d was specified
108                 case 'd':
109                         running_as_daemon = 1;
110                         break;
111
112                 // specify the data directory
113                 case 'h':
114                         ctdldir = optarg;
115                         break;
116
117                 // identify the desired logging severity level
118                 case 'x':
119                         max_log_level = atoi(optarg);
120                         break;
121
122                 // deprecated flags from old versions -- ignore silently to prevent breaking scripts
123                 case 't':
124                 case 'B':
125                 case 'D':
126                         break;
127
128                 // -r tells the server not to drop root permissions.
129                 // Don't use this unless you know what you're doing.
130                 case 'r':
131                         drop_root_perms = 0;
132                         break;
133
134                 // -u tells the server what uid to run under...
135                 case 'u':
136                         u = atoi(optarg);
137                         if (u > 0) {
138                                 ctdluid = u;
139                         }
140                         else {
141                                 p = getpwnam(optarg);
142                                 if (p) {
143                                         u = p->pw_uid;
144                                 }
145                         }
146                         if (u > 0) {
147                                 ctdluid = u;
148                         }
149                         break;
150
151                 // -s tells the server to behave differently during sanity checks
152                 case 's':
153                         sanity_diag_mode = atoi(optarg);
154                         break;
155
156                 // any other parameter makes it crash and burn
157                 default:
158                         fprintf(stderr, "citserver: usage: "
159                                         "citserver "
160                                         "[-l LogFacility] "
161                                         "[-x MaxLogLevel] "
162                                         "[-d] [-r] "
163                                         "[-u user] "
164                                         "[-h HomeDir]\n"
165                         );
166                         exit(1);
167         }
168
169         if (chdir(ctdldir) != 0) {
170                 syslog(LOG_ERR, "main: unable to change directory to [%s]: %m", ctdldir);
171                 exit(CTDLEXIT_HOME);
172         }
173         else {
174                 syslog(LOG_INFO, "main: running in data directory %s", ctdldir);
175         }
176
177         if ((ctdluid == 0) && (drop_root_perms == 0)) {
178                 fprintf(stderr, "citserver: cannot determine user to run as; please specify -r or -u options\n");
179                 exit(CTDLEXIT_UNUSER);
180         }
181
182         // Last ditch effort to determine the user name ... if there's a user called "citadel" then use that
183         if (ctdluid == 0) {
184                 p = getpwnam("citadel");
185                 if (!p) {
186                         p = getpwnam("bbs");
187                 }
188                 if (!p) {
189                         p = getpwnam("guest");
190                 }
191                 if (p) {
192                         u = p->pw_uid;
193                 }
194                 if (u > 0) {
195                         ctdluid = u;
196                 }
197         }
198
199         // initialize the master context
200         InitializeMasterCC();
201         InitializeMasterTSD();
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         // Load the user for the masterCC or create them if they don't exist
231         if (CtdlGetUser(&masterCC.user, "SYS_Citadel")) {
232                 // User doesn't exist. We can't use create user here as the user number needs to be 0
233                 strcpy(masterCC.user.fullname, "SYS_Citadel") ;
234                 CtdlPutUser(&masterCC.user);
235                 CtdlGetUser(&masterCC.user, "SYS_Citadel");     // Just to be safe
236         }
237         
238         // Bind the server to a Unix-domain socket (user client access)
239         CtdlRegisterServiceHook(0,
240                                 file_citadel_socket,
241                                 citproto_begin_session,
242                                 do_command_loop,
243                                 do_async_loop,
244                                 CitadelServiceUDS);
245
246         // Bind the server to a Unix-domain socket (admin client access)
247         CtdlRegisterServiceHook(0,
248                                 file_citadel_admin_socket,
249                                 citproto_begin_admin_session,
250                                 do_command_loop,
251                                 do_async_loop,
252                                 CitadelServiceUDS);
253         chmod(file_citadel_admin_socket, S_IRWXU);              // protect the admin socket - it offers high privilege
254
255         // Bind the server to our favorite TCP port (usually 504).
256         CtdlRegisterServiceHook(CtdlGetConfigInt("c_port_number"),
257                                 NULL,
258                                 citproto_begin_session,
259                                 do_command_loop,
260                                 do_async_loop,
261                                 CitadelServiceTCP);
262
263         // Load any server-side extensions available here.
264         syslog(LOG_INFO, "main: initializing server extensions");
265         initialize_modules(0);
266
267         // If we need host auth, start our chkpwd daemon.
268         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
269                 start_chkpwd_daemon();
270         }
271
272         // check, whether we're fired up another time after a crash.
273         // if, post an aide message, so the admin has a chance to react.
274         checkcrash();
275
276         // Now that we've bound the sockets, change to the Citadel user id and its corresponding group ids
277         if (drop_root_perms) {
278                 cdb_chmod_data();       // make sure we own our data files
279                 getpwuid_r(ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
280                 if (pwp == NULL) {
281                         syslog(LOG_ERR, "main: WARNING, getpwuid(%ld): %m Group IDs will be incorrect.", (long)CTDLUID);
282                 }
283                 else {
284                         initgroups(pw.pw_name, pw.pw_gid);
285                         if (setgid(pw.pw_gid)) {
286                                 syslog(LOG_ERR, "main: setgid(%ld): %m", (long)pw.pw_gid);
287                         }
288                 }
289                 syslog(LOG_INFO, "main: changing uid to %ld", (long)CTDLUID);
290                 if (setuid(CTDLUID) != 0) {
291                         syslog(LOG_ERR, "main: setuid() failed: %m");
292                 }
293 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
294                 prctl(PR_SET_DUMPABLE, 1);
295 #endif
296         }
297
298         // We want to check for idle sessions once per minute
299         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER, PRIO_CLEANUP + 1);
300
301         // Go into multithreaded mode.  When this call exits, the server is stopping.
302         go_threading();
303         
304         // Get ready to shut down the server.
305         int exit_code = master_cleanup(exit_signal);
306         ctdl_lockfile(0);
307         if (restart_server) {
308                 syslog(LOG_INFO, "main: *** CITADEL SERVER IS RESTARTING ***");
309                 execv(argv[0], argv);
310         }
311         return(exit_code);
312 }