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