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