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