349213d6f6bf496724b3d5704e26a1abc6f94ee8
[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:h: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                 // specify the data directory
104                 case 'h':
105                         ctdldir = optarg;
106                         break;
107
108                 // identify the desired logging severity level
109                 case 'x':
110                         max_log_level = atoi(optarg);
111                         break;
112
113                 // -r tells the server not to drop root permissions.
114                 // Don't use this unless you know what you're doing.
115                 case 'r':
116                         drop_root_perms = 0;
117                         break;
118
119                 // -u tells the server what uid to run under...
120                 case 'u':
121                         u = atoi(optarg);
122                         if (u > 0) {
123                                 ctdluid = u;
124                         }
125                         else {
126                                 p = getpwnam(optarg);
127                                 if (p) {
128                                         u = p->pw_uid;
129                                 }
130                         }
131                         if (u > 0) {
132                                 ctdluid = u;
133                         }
134                         break;
135
136                 // -s tells the server to behave differently during sanity checks
137                 case 's':
138                         sanity_diag_mode = atoi(optarg);
139                         break;
140
141                 // -R is an undocumented rescue mode that you should never use
142                 case 'R':
143                         rescue_string = strdup(optarg);
144                         break;
145
146                 // any other parameter makes it crash and burn
147                 default:
148                         fprintf(stderr, "citserver: usage: "
149                                         "citserver "
150                                         "[-l LogFacility] "
151                                         "[-x MaxLogLevel] "
152                                         "[-d] [-r] "
153                                         "[-u user] "
154                                         "[-h HomeDir]\n"
155                         );
156                         exit(1);
157         }
158
159         if (chdir(ctdldir) != 0) {
160                 syslog(LOG_ERR, "main: unable to change directory to [%s]: %m", ctdldir);
161                 exit(CTDLEXIT_HOME);
162         }
163         else {
164                 syslog(LOG_INFO, "main: running in data directory %s", ctdldir);
165         }
166
167         if ((ctdluid == 0) && (drop_root_perms == 0)) {
168                 fprintf(stderr, "citserver: cannot determine user to run as; please specify -r or -u options\n");
169                 exit(CTDLEXIT_UNUSER);
170         }
171
172         // Last ditch effort to determine the user name ... if there's a user called "citadel" then use that
173         if (ctdluid == 0) {
174                 p = getpwnam("citadel");
175                 if (!p) {
176                         p = getpwnam("bbs");
177                 }
178                 if (!p) {
179                         p = getpwnam("guest");
180                 }
181                 if (p) {
182                         u = p->pw_uid;
183                 }
184                 if (u > 0) {
185                         ctdluid = u;
186                 }
187         }
188
189         // initialize the master context
190         InitializeMasterCC();
191
192         setlogmask(LOG_UPTO(max_log_level));
193         openlog("citserver",
194                 ( running_as_daemon ? (LOG_PID) : (LOG_PID | LOG_PERROR) ),
195                 syslog_facility
196         );
197
198         if ((mkdir(ctdl_run_dir, 0755) != 0) && (errno != EEXIST)) {
199                 syslog(LOG_ERR, "main: unable to create run directory [%s]: %m", ctdl_run_dir);
200         }
201
202         if (chown(ctdl_run_dir, ctdluid, (pwp==NULL)?-1:pw.pw_gid) != 0) {
203                 syslog(LOG_ERR, "main: unable to set the access rights for [%s]: %m", ctdl_run_dir);
204         }
205
206         ctdl_lockfile(1);
207         init_sysdep();                                          // Initialize...
208         master_startup();                                       // Do non system dependent startup functions
209         check_control();                                        // Check/sanitize/initialize control record, fix user indexes
210         syslog(LOG_INFO, "main: upgrading modules");            // Run any upgrade entry points
211         pre_startup_upgrades();
212
213         // Setting this key to nonzero causes the server to regenerate all data that can be derived
214         // from other tables: usersbynumber, directory, fulltext.
215         // The import utility (ctdlload) sets this key.
216         if (CtdlGetConfigInt("regenerate_secondary_indices") != 0) {
217                 regenerate_secondary_indices();
218         }
219
220
221         // Load the user for the masterCC or create them if they don't exist
222         if (CtdlGetUser(&masterCC.user, "SYS_Citadel")) {
223                 // User doesn't exist. We can't use create user here as the user number needs to be 0
224                 strcpy(masterCC.user.fullname, "SYS_Citadel") ;
225                 CtdlPutUser(&masterCC.user);
226                 CtdlGetUser(&masterCC.user, "SYS_Citadel");     // Just to be safe
227         }
228         
229         // Bind the server to a Unix-domain socket (user client access)
230         CtdlRegisterServiceHook(0,
231                                 file_citadel_socket,
232                                 citproto_begin_session,
233                                 do_command_loop,
234                                 do_async_loop,
235                                 CitadelServiceUDS);
236
237         // Bind the server to a Unix-domain socket (admin client access)
238         CtdlRegisterServiceHook(0,
239                                 file_citadel_admin_socket,
240                                 citproto_begin_admin_session,
241                                 do_command_loop,
242                                 do_async_loop,
243                                 CitadelServiceUDS);
244         chmod(file_citadel_admin_socket, S_IRWXU);              // protect the admin socket - it offers high privilege
245
246         // Bind the server to our favorite TCP port (usually 504).
247         CtdlRegisterServiceHook(CtdlGetConfigInt("c_port_number"),
248                                 NULL,
249                                 citproto_begin_session,
250                                 do_command_loop,
251                                 do_async_loop,
252                                 CitadelServiceTCP);
253
254         // Load any server-side extensions available here.
255         syslog(LOG_INFO, "main: initializing server extensions");
256         initialize_modules(0);
257
258         // If we need host auth, start our chkpwd daemon.
259         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
260                 start_chkpwd_daemon();
261         }
262
263         // Now that we've bound the sockets, change to the Citadel user id and its corresponding group ids
264         getpwuid_r(ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
265         if (pwp == NULL) {
266                 syslog(LOG_ERR, "main: WARNING, getpwuid(%ld): %m Group IDs will be incorrect.", (long)ctdluid);
267         }
268         else {
269                 initgroups(pw.pw_name, pw.pw_gid);
270                 if (setgid(pw.pw_gid)) {
271                         syslog(LOG_ERR, "main: setgid(%ld): %m", (long)pw.pw_gid);
272                 }
273         }
274         if (drop_root_perms) {
275                 syslog(LOG_INFO, "main: changing uid to %ld", (long)ctdluid);
276                 if (setuid(ctdluid) != 0) {
277                         syslog(LOG_ERR, "main: setuid() failed: %m");
278                 }
279 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
280                 prctl(PR_SET_DUMPABLE, 1);
281 #endif
282         }
283
284         // We want to check for idle sessions once per minute
285         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER, PRIO_CLEANUP + 1);
286
287         // Are we in the undocumented rescue mode?
288         if (rescue_string) {
289                 undocumented_rescue_mode(rescue_string);
290         }
291         else {
292                 // Go into multithreaded mode.  When this call exits, the server is stopping.
293                 go_threading();
294         }
295         
296         // Get ready to shut down the server.
297         master_cleanup(exit_signal);
298 }