Simple concurrency lock to prevent multiple citservers running at the same time
[citadel.git] / citadel / server_main.c
1 /*
2  * citserver's main() function lives here.
3  * 
4  * Copyright (c) 1987-2016 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, "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, "Cannot open or create %s", lockfilename);
54                         exit(CTDLEXIT_DB);
55                 }
56                 if (flock(fileno(fp), (LOCK_EX|LOCK_NB)) != 0) {
57                         syslog(LOG_ERR, "Cannot lock %s , is another citserver running?", lockfilename);
58                         exit(CTDLEXIT_DB);
59                 }
60                 return;
61         }
62
63         syslog(LOG_DEBUG, "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-2016 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_EMERG, 
260                                       "unable to create run directory [%s]: %s", 
261                                       ctdl_run_dir, strerror(errno));
262
263                 if (chown(ctdl_run_dir, ctdluid, (pwp==NULL)?-1:pw.pw_gid) != 0)
264                         syslog(LOG_EMERG, 
265                                       "unable to set the access rights for [%s]: %s", 
266                                       ctdl_run_dir, strerror(errno));
267         }
268                         
269
270 #endif
271
272         ctdl_lockfile(1);
273
274         /* Initialize... */
275         init_sysdep();
276
277         /*
278          * Do non system dependent startup functions.
279          */
280         master_startup();
281
282         /*
283          * Check that the control record is correct and place sensible values if it isn't
284          */
285         check_control();
286         
287         /*
288          * Run any upgrade entry points
289          */
290         syslog(LOG_INFO, "Upgrading modules.");
291         upgrade_modules();
292         
293 /*
294  * Load the user for the masterCC or create them if they don't exist
295  */
296         if (CtdlGetUser(&masterCC.user, "SYS_Citadel"))
297         {
298                 /* User doesn't exist. We can't use create user here as the user number needs to be 0 */
299                 strcpy (masterCC.user.fullname, "SYS_Citadel") ;
300                 CtdlPutUser(&masterCC.user);
301                 CtdlGetUser(&masterCC.user, "SYS_Citadel"); /* Just to be safe */
302         }
303         
304         /*
305          * Bind the server to a Unix-domain socket (user client access)
306          */
307         CtdlRegisterServiceHook(0,
308                                 file_citadel_socket,
309                                 citproto_begin_session,
310                                 do_command_loop,
311                                 do_async_loop,
312                                 CitadelServiceUDS);
313
314         /*
315          * Bind the server to a Unix-domain socket (admin client access)
316          */
317         CtdlRegisterServiceHook(0,
318                                 file_citadel_admin_socket,
319                                 citproto_begin_admin_session,
320                                 do_command_loop,
321                                 do_async_loop,
322                                 CitadelServiceUDS);
323         chmod(file_citadel_admin_socket, S_IRWXU);      /* for your eyes only */
324
325         /*
326          * Bind the server to our favorite TCP port (usually 504).
327          */
328         CtdlRegisterServiceHook(CtdlGetConfigInt("c_port_number"),
329                                 NULL,
330                                 citproto_begin_session,
331                                 do_command_loop,
332                                 do_async_loop,
333                                 CitadelServiceTCP);
334
335                                 
336         
337         
338         /*
339          * Load any server-side extensions available here.
340          */
341         syslog(LOG_INFO, "Initializing server extensions");
342         
343         initialise_modules(0);
344
345         eDebuglist[1] = getenv("CITADEL_LOGDEBUG");
346         CtdlSetDebugLogFacilities(eDebuglist, 2);
347
348         /*
349          * If we need host auth, start our chkpwd daemon.
350          */
351         if (CtdlGetConfigInt("c_auth_mode") == AUTHMODE_HOST) {
352                 start_chkpwd_daemon();
353         }
354
355
356         /*
357          * check, whether we're fired up another time after a crash.
358          * if, post an aide message, so the admin has a chance to react.
359          */
360         checkcrash ();
361
362
363         /*
364          * Now that we've bound the sockets, change to the Citadel user id and its
365          * corresponding group ids
366          */
367         if (drop_root_perms) {
368                 cdb_chmod_data();       /* make sure we own our data files */
369
370 #ifdef HAVE_GETPWUID_R
371 #ifdef SOLARIS_GETPWUID
372                 pwp = getpwuid_r(ctdluid, &pw, pwbuf, sizeof(pwbuf));
373 #else // SOLARIS_GETPWUID
374                 getpwuid_r(ctdluid, &pw, pwbuf, sizeof(pwbuf), &pwp);
375 #endif // SOLARIS_GETPWUID
376 #else // HAVE_GETPWUID_R
377                 pwp = NULL;
378 #endif // HAVE_GETPWUID_R
379
380                 if (pwp == NULL)
381                         syslog(LOG_CRIT, "WARNING: getpwuid(%ld): %s"
382                                    "Group IDs will be incorrect.\n", (long)CTDLUID,
383                                 strerror(errno));
384                 else {
385                         initgroups(pw.pw_name, pw.pw_gid);
386                         if (setgid(pw.pw_gid))
387                                 syslog(LOG_CRIT, "setgid(%ld): %s", (long)pw.pw_gid,
388                                         strerror(errno));
389                 }
390                 syslog(LOG_INFO, "Changing uid to %ld", (long)CTDLUID);
391                 if (setuid(CTDLUID) != 0) {
392                         syslog(LOG_CRIT, "setuid() failed: %s", strerror(errno));
393                 }
394 #if defined (HAVE_SYS_PRCTL_H) && defined (PR_SET_DUMPABLE)
395                 prctl(PR_SET_DUMPABLE, 1);
396 #endif
397         }
398
399         /* We want to check for idle sessions once per minute */
400         CtdlRegisterSessionHook(terminate_idle_sessions, EVT_TIMER, PRIO_CLEANUP + 1);
401
402         go_threading();
403         
404         int exit_code = master_cleanup(exit_signal);
405         ctdl_lockfile(0);
406         return(exit_code);
407 }