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