]> git.proxmox.com Git - mirror_ovs.git/blame - lib/daemon-unix.c
replication: Avoid theoretical use-after-free error in reset_database().
[mirror_ovs.git] / lib / daemon-unix.c
CommitLineData
064af421 1/*
6069edb0 2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2015 Nicira, Inc.
064af421 3 *
a14bc59f
BP
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
064af421 7 *
a14bc59f
BP
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
064af421
BP
15 */
16
17#include <config.h>
18#include "daemon.h"
3834bcf2 19#include "daemon-private.h"
064af421
BP
20#include <errno.h>
21#include <fcntl.h>
e91b927d
AZ
22#include <grp.h>
23#include <pwd.h>
3762274e 24#include <signal.h>
064af421
BP
25#include <stdlib.h>
26#include <string.h>
3762274e 27#include <sys/resource.h>
95440284 28#include <sys/wait.h>
309eaa2b 29#include <sys/stat.h>
064af421 30#include <unistd.h>
e91b927d
AZ
31#if HAVE_LIBCAPNG
32#include <cap-ng.h>
33#endif
40f0707c 34#include "command-line.h"
064af421
BP
35#include "fatal-signal.h"
36#include "dirs.h"
ac718c9d 37#include "lockfile.h"
728a8b14 38#include "ovs-thread.h"
ff8decf1 39#include "process.h"
b8781ff0 40#include "socket-util.h"
03fbffbd 41#include "timeval.h"
064af421 42#include "util.h"
e6211adc 43#include "openvswitch/vlog.h"
064af421 44
a91dc444 45VLOG_DEFINE_THIS_MODULE(daemon_unix);
5136ce49 46
e91b927d
AZ
47#ifdef __linux__
48#define LINUX 1
49#else
50#define LINUX 0
51#endif
52
53#if HAVE_LIBCAPNG
54#define LIBCAPNG 1
55#else
56#define LIBCAPNG 0
57#endif
58
d4db8309 59/* --detach: Should we run in the background? */
3834bcf2 60bool detach; /* Was --detach specified? */
e8087a87 61static bool detached; /* Have we already detached? */
064af421 62
d4db8309 63/* --pidfile: Name of pidfile (null if none). */
3834bcf2 64char *pidfile;
064af421 65
e4bd5e2a
BP
66/* Device and inode of pidfile, so we can avoid reopening it. */
67static dev_t pidfile_dev;
68static ino_t pidfile_ino;
69
d4db8309
BP
70/* --overwrite-pidfile: Create pidfile even if one already exists and is
71 locked? */
e7bd7d78 72static bool overwrite_pidfile;
064af421 73
d4db8309 74/* --no-chdir: Should we chdir to "/"? */
91a1e24d
JP
75static bool chdir_ = true;
76
7943cd51
BP
77/* File descriptor used by daemonize_start() and daemonize_complete(). */
78static int daemonize_fd = -1;
95440284 79
ff8decf1
BP
80/* --monitor: Should a supervisory process monitor the daemon and restart it if
81 * it dies due to an error signal? */
82static bool monitor;
83
e91b927d
AZ
84/* --user: Only root can use this option. Switch to new uid:gid after
85 * initially running as root. */
86static bool switch_user = false;
e91b927d
AZ
87static uid_t uid;
88static gid_t gid;
89static char *user = NULL;
90static void daemon_become_new_user__(bool access_datapath);
91
aacea8ba
BP
92static void check_already_running(void);
93static int lock_pidfile(FILE *, int command);
d6056bc7
GS
94static pid_t fork_and_clean_up(void);
95static void daemonize_post_detach(void);
aacea8ba 96
064af421
BP
97/* Returns the file name that would be used for a pidfile if 'name' were
98 * provided to set_pidfile(). The caller must free the returned string. */
3834bcf2 99char *
d295e8e9 100make_pidfile_name(const char *name)
064af421 101{
daf03c53 102 return (!name
b43c6fe2
BP
103 ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
104 : abs_file_name(ovs_rundir(), name));
064af421
BP
105}
106
91a1e24d
JP
107/* Sets that we do not chdir to "/". */
108void
109set_no_chdir(void)
110{
111 chdir_ = false;
112}
113
00c08589
BP
114/* Normally, daemonize() or damonize_start() will terminate the program with a
115 * message if a locked pidfile already exists. If this function is called, an
116 * existing pidfile will be replaced, with a warning. */
064af421
BP
117void
118ignore_existing_pidfile(void)
119{
e7bd7d78 120 overwrite_pidfile = true;
064af421
BP
121}
122
123/* Sets up a following call to daemonize() to detach from the foreground
124 * session, running this process in the background. */
125void
126set_detach(void)
127{
128 detach = true;
129}
130
ff8decf1
BP
131/* Sets up a following call to daemonize() to fork a supervisory process to
132 * monitor the daemon and restart it if it dies due to an error signal. */
133void
134daemon_set_monitor(void)
135{
136 monitor = true;
137}
138
d4db8309
BP
139/* If a pidfile has been configured, creates it and stores the running
140 * process's pid in it. Ensures that the pidfile will be deleted when the
141 * process exits. */
064af421
BP
142static void
143make_pidfile(void)
144{
aacea8ba
BP
145 long int pid = getpid();
146 struct stat s;
147 char *tmpfile;
148 FILE *file;
149 int error;
150
151 /* Create a temporary pidfile. */
2388a783
EJ
152 if (overwrite_pidfile) {
153 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
154 fatal_signal_add_file_to_unlink(tmpfile);
155 } else {
156 /* Everyone shares the same file which will be treated as a lock. To
157 * avoid some uncomfortable race conditions, we can't set up the fatal
158 * signal unlink until we've acquired it. */
159 tmpfile = xasprintf("%s.tmp", pidfile);
160 }
161
162 file = fopen(tmpfile, "a+");
aacea8ba 163 if (!file) {
10a89ef0 164 VLOG_FATAL("%s: create failed (%s)", tmpfile, ovs_strerror(errno));
aacea8ba
BP
165 }
166
2388a783
EJ
167 error = lock_pidfile(file, F_SETLK);
168 if (error) {
169 /* Looks like we failed to acquire the lock. Note that, if we failed
170 * for some other reason (and '!overwrite_pidfile'), we will have
171 * left 'tmpfile' as garbage in the file system. */
10a89ef0
BP
172 VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile,
173 ovs_strerror(error));
2388a783
EJ
174 }
175
176 if (!overwrite_pidfile) {
177 /* We acquired the lock. Make sure to clean up on exit, and verify
178 * that we're allowed to create the actual pidfile. */
179 fatal_signal_add_file_to_unlink(tmpfile);
180 check_already_running();
181 }
182
aacea8ba 183 if (fstat(fileno(file), &s) == -1) {
10a89ef0 184 VLOG_FATAL("%s: fstat failed (%s)", tmpfile, ovs_strerror(errno));
aacea8ba
BP
185 }
186
2388a783 187 if (ftruncate(fileno(file), 0) == -1) {
10a89ef0 188 VLOG_FATAL("%s: truncate failed (%s)", tmpfile, ovs_strerror(errno));
2388a783
EJ
189 }
190
aacea8ba
BP
191 fprintf(file, "%ld\n", pid);
192 if (fflush(file) == EOF) {
10a89ef0 193 VLOG_FATAL("%s: write failed (%s)", tmpfile, ovs_strerror(errno));
aacea8ba
BP
194 }
195
2388a783 196 error = rename(tmpfile, pidfile);
aacea8ba 197
2388a783
EJ
198 /* Due to a race, 'tmpfile' may be owned by a different process, so we
199 * shouldn't delete it on exit. */
200 fatal_signal_remove_file_to_unlink(tmpfile);
201
202 if (error < 0) {
203 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
10a89ef0 204 tmpfile, pidfile, ovs_strerror(errno));
aacea8ba
BP
205 }
206
207 /* Ensure that the pidfile will get deleted on exit. */
208 fatal_signal_add_file_to_unlink(pidfile);
209
aacea8ba
BP
210 /* Clean up.
211 *
212 * We don't close 'file' because its file descriptor must remain open to
213 * hold the lock. */
214 pidfile_dev = s.st_dev;
215 pidfile_ino = s.st_ino;
216 free(tmpfile);
064af421
BP
217}
218
8aee05cc
BP
219/* Calls fork() and on success returns its return value. On failure, logs an
220 * error and exits unsuccessfully.
221 *
222 * Post-fork, but before returning, this function calls a few other functions
223 * that are generally useful if the child isn't planning to exec a new
224 * process. */
d6056bc7 225static pid_t
8aee05cc
BP
226fork_and_clean_up(void)
227{
728a8b14 228 pid_t pid = xfork();
8aee05cc
BP
229 if (pid > 0) {
230 /* Running in parent process. */
231 fatal_signal_fork();
232 } else if (!pid) {
233 /* Running in child process. */
8aee05cc 234 lockfile_postfork();
8aee05cc 235 }
8aee05cc
BP
236 return pid;
237}
238
e6c5e539
BP
239/* Forks, then:
240 *
241 * - In the parent, waits for the child to signal that it has completed its
b925336a
AA
242 * startup sequence. Then stores -1 in '*fdp' and returns the child's
243 * pid in '*child_pid' argument.
e6c5e539 244 *
b925336a
AA
245 * - In the child, stores a fd in '*fdp' and returns 0 through '*child_pid'
246 * argument. The caller should pass the fd to fork_notify_startup() after
247 * it finishes its startup sequence.
e6c5e539 248 *
b925336a
AA
249 * Returns 0 on success. If something goes wrong and child process was not
250 * able to signal its readiness by calling fork_notify_startup(), then this
251 * function returns -1. However, even in case of failure it still sets child
252 * process id in '*child_pid'. */
253static int
254fork_and_wait_for_startup(int *fdp, pid_t *child_pid)
7943cd51
BP
255{
256 int fds[2];
257 pid_t pid;
b925336a 258 int ret = 0;
7943cd51 259
279c9e03 260 xpipe(fds);
7943cd51 261
8aee05cc 262 pid = fork_and_clean_up();
7943cd51
BP
263 if (pid > 0) {
264 /* Running in parent process. */
af9a1442 265 size_t bytes_read;
7943cd51
BP
266 char c;
267
268 close(fds[1]);
af9a1442 269 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
7943cd51
BP
270 int retval;
271 int status;
272
273 do {
274 retval = waitpid(pid, &status, 0);
275 } while (retval == -1 && errno == EINTR);
276
2c8fcc9c
BP
277 if (retval == pid) {
278 if (WIFEXITED(status) && WEXITSTATUS(status)) {
279 /* Child exited with an error. Convey the same error
280 * to our parent process as a courtesy. */
281 exit(WEXITSTATUS(status));
282 } else {
283 char *status_msg = process_status_msg(status);
b925336a
AA
284 VLOG_ERR("fork child died before signaling startup (%s)",
285 status_msg);
286 ret = -1;
2c8fcc9c
BP
287 }
288 } else if (retval < 0) {
10a89ef0 289 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
2c8fcc9c 290 } else {
428b2edd 291 OVS_NOT_REACHED();
7943cd51 292 }
7943cd51
BP
293 }
294 close(fds[0]);
295 *fdp = -1;
296 } else if (!pid) {
297 /* Running in child process. */
298 close(fds[0]);
7943cd51 299 *fdp = fds[1];
7943cd51 300 }
b925336a
AA
301 *child_pid = pid;
302 return ret;
7943cd51
BP
303}
304
305static void
306fork_notify_startup(int fd)
307{
308 if (fd != -1) {
309 size_t bytes_written;
310 int error;
311
312 error = write_fully(fd, "", 1, &bytes_written);
313 if (error) {
10a89ef0 314 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
7943cd51
BP
315 }
316
317 close(fd);
318 }
319}
320
ff8decf1
BP
321static bool
322should_restart(int status)
323{
324 if (WIFSIGNALED(status)) {
325 static const int error_signals[] = {
f67c3295
BP
326 /* This list of signals is documented in daemon.man. If you
327 * change the list, update the documentation too. */
ff8decf1
BP
328 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
329 SIGXCPU, SIGXFSZ
330 };
331
332 size_t i;
333
334 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
335 if (error_signals[i] == WTERMSIG(status)) {
336 return true;
337 }
338 }
339 }
340 return false;
341}
342
343static void
344monitor_daemon(pid_t daemon_pid)
345{
ff8decf1 346 /* XXX Should log daemon's stderr output at startup time. */
a9633ada 347 time_t last_restart;
40f0707c 348 char *status_msg;
cbbdf81c 349 int crashes;
b925336a 350 bool child_ready = true;
ff8decf1 351
bc9fb3a9 352 set_subprogram_name("monitor");
40f0707c 353 status_msg = xstrdup("healthy");
a9633ada 354 last_restart = TIME_MIN;
cbbdf81c 355 crashes = 0;
ff8decf1
BP
356 for (;;) {
357 int retval;
358 int status;
359
5f383751
RB
360 ovs_cmdl_proctitle_set("monitoring pid %lu (%s)",
361 (unsigned long int) daemon_pid, status_msg);
40f0707c 362
b925336a 363 if (child_ready) {
8ee45836 364 int error;
b925336a
AA
365 do {
366 retval = waitpid(daemon_pid, &status, 0);
8ee45836
HH
367 error = retval == -1 ? errno : 0;
368 } while (error == EINTR);
369 vlog_reopen_log_file();
370 if (error) {
371 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(error));
b925336a
AA
372 }
373 }
ff8decf1 374
b925336a 375 if (!child_ready || retval == daemon_pid) {
40f0707c 376 char *s = process_status_msg(status);
40f0707c 377 if (should_restart(status)) {
2bf9d87a
BP
378 free(status_msg);
379 status_msg = xasprintf("%d crashes: pid %lu died, %s",
380 ++crashes,
381 (unsigned long int) daemon_pid, s);
382 free(s);
383
7c2dd4c6
BP
384 if (WCOREDUMP(status)) {
385 /* Disable further core dumps to save disk space. */
386 struct rlimit r;
387
388 r.rlim_cur = 0;
389 r.rlim_max = 0;
390 if (setrlimit(RLIMIT_CORE, &r) == -1) {
391 VLOG_WARN("failed to disable core dumps: %s",
10a89ef0 392 ovs_strerror(errno));
7c2dd4c6
BP
393 }
394 }
395
a9633ada
BP
396 /* Throttle restarts to no more than once every 10 seconds. */
397 if (time(NULL) < last_restart + 10) {
398 VLOG_WARN("%s, waiting until 10 seconds since last "
399 "restart", status_msg);
400 for (;;) {
401 time_t now = time(NULL);
402 time_t wakeup = last_restart + 10;
403 if (now >= wakeup) {
404 break;
405 }
275eebb9 406 xsleep(wakeup - now);
a9633ada
BP
407 }
408 }
409 last_restart = time(NULL);
410
40f0707c 411 VLOG_ERR("%s, restarting", status_msg);
b925336a
AA
412 child_ready = !fork_and_wait_for_startup(&daemonize_fd,
413 &daemon_pid);
414 if (child_ready && !daemon_pid) {
415 /* Child process needs to break out of monitoring
416 * loop. */
ff8decf1
BP
417 break;
418 }
419 } else {
2bf9d87a
BP
420 VLOG_INFO("pid %lu died, %s, exiting",
421 (unsigned long int) daemon_pid, s);
422 free(s);
ff8decf1
BP
423 exit(0);
424 }
425 }
426 }
b2d06cb8 427 free(status_msg);
ff8decf1
BP
428
429 /* Running in new daemon process. */
5f383751 430 ovs_cmdl_proctitle_restore();
bc9fb3a9 431 set_subprogram_name("");
ff8decf1
BP
432}
433
95440284
BP
434/* If daemonization is configured, then starts daemonization, by forking and
435 * returning in the child process. The parent process hangs around until the
436 * child lets it know either that it completed startup successfully (by calling
437 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
438 * exit code). */
439void
e91b927d 440daemonize_start(bool access_datapath)
064af421 441{
728a8b14 442 assert_single_threaded();
7943cd51 443 daemonize_fd = -1;
95440284 444
e91b927d
AZ
445 if (switch_user) {
446 daemon_become_new_user__(access_datapath);
447 switch_user = false;
448 }
449
7943cd51 450 if (detach) {
b925336a
AA
451 pid_t pid;
452
453 if (fork_and_wait_for_startup(&daemonize_fd, &pid)) {
454 VLOG_FATAL("could not detach from foreground session");
455 }
456 if (pid > 0) {
95440284 457 /* Running in parent process. */
064af421 458 exit(0);
064af421 459 }
066f329e 460
ff8decf1 461 /* Running in daemon or monitor process. */
066f329e 462 setsid();
ff8decf1
BP
463 }
464
465 if (monitor) {
466 int saved_daemonize_fd = daemonize_fd;
467 pid_t daemon_pid;
468
b925336a
AA
469 if (fork_and_wait_for_startup(&daemonize_fd, &daemon_pid)) {
470 VLOG_FATAL("could not initiate process monitoring");
471 }
ff8decf1
BP
472 if (daemon_pid > 0) {
473 /* Running in monitor process. */
474 fork_notify_startup(saved_daemonize_fd);
475 close_standard_fds();
476 monitor_daemon(daemon_pid);
477 }
7943cd51 478 /* Running in daemon process. */
064af421 479 }
7943cd51 480
92fa2e92
BP
481 forbid_forking("running in daemon process");
482
aacea8ba
BP
483 if (pidfile) {
484 make_pidfile();
485 }
df5d2ed9
BP
486
487 /* Make sure that the unixctl commands for vlog get registered in a
488 * daemon, even before the first log message. */
489 vlog_init();
064af421
BP
490}
491
95440284 492/* If daemonization is configured, then this function notifies the parent
e8087a87
BP
493 * process that the child process has completed startup successfully. It also
494 * call daemonize_post_detach().
a7ff9bd7
BP
495 *
496 * Calling this function more than once has no additional effect. */
95440284
BP
497void
498daemonize_complete(void)
499{
7ffd3f69
GS
500 if (pidfile) {
501 free(pidfile);
502 pidfile = NULL;
503 }
504
e8087a87
BP
505 if (!detached) {
506 detached = true;
507
508 fork_notify_startup(daemonize_fd);
509 daemonize_fd = -1;
510 daemonize_post_detach();
511 }
512}
95440284 513
e8087a87
BP
514/* If daemonization is configured, then this function does traditional Unix
515 * daemonization behavior: join a new session, chdir to the root (if not
516 * disabled), and close the standard file descriptors.
517 *
518 * It only makes sense to call this function as part of an implementation of a
519 * special daemon subprocess. A normal daemon should just call
520 * daemonize_complete(). */
d6056bc7 521static void
e8087a87
BP
522daemonize_post_detach(void)
523{
7943cd51 524 if (detach) {
95440284
BP
525 if (chdir_) {
526 ignore(chdir("/"));
527 }
7943cd51 528 close_standard_fds();
95440284
BP
529 }
530}
531
064af421
BP
532void
533daemon_usage(void)
534{
535 printf(
536 "\nDaemon options:\n"
e7bd7d78 537 " --detach run in background as daemon\n"
91a1e24d 538 " --no-chdir do not chdir to '/'\n"
e7bd7d78
JP
539 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
540 " --overwrite-pidfile with --pidfile, start even if already "
541 "running\n",
b43c6fe2 542 ovs_rundir(), program_name);
064af421
BP
543}
544
aacea8ba
BP
545static int
546lock_pidfile__(FILE *file, int command, struct flock *lck)
547{
548 int error;
549
550 lck->l_type = F_WRLCK;
551 lck->l_whence = SEEK_SET;
552 lck->l_start = 0;
553 lck->l_len = 0;
554 lck->l_pid = 0;
555
556 do {
557 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
558 } while (error == EINTR);
559 return error;
560}
561
562static int
563lock_pidfile(FILE *file, int command)
564{
565 struct flock lck;
566
567 return lock_pidfile__(file, command, &lck);
568}
569
18e124a2 570static pid_t
aacea8ba 571read_pidfile__(const char *pidfile, bool delete_if_stale)
064af421 572{
aacea8ba 573 struct stat s, s2;
064af421 574 struct flock lck;
aacea8ba 575 char line[128];
064af421
BP
576 FILE *file;
577 int error;
578
e4bd5e2a
BP
579 if ((pidfile_ino || pidfile_dev)
580 && !stat(pidfile, &s)
581 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
582 /* It's our own pidfile. We can't afford to open it, because closing
583 * *any* fd for a file that a process has locked also releases all the
584 * locks on that file.
585 *
586 * Fortunately, we know the associated pid anyhow: */
587 return getpid();
588 }
589
aacea8ba 590 file = fopen(pidfile, "r+");
064af421 591 if (!file) {
aacea8ba 592 if (errno == ENOENT && delete_if_stale) {
18e124a2
BP
593 return 0;
594 }
064af421 595 error = errno;
10a89ef0 596 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
064af421
BP
597 goto error;
598 }
599
aacea8ba
BP
600 error = lock_pidfile__(file, F_GETLK, &lck);
601 if (error) {
10a89ef0 602 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
064af421
BP
603 goto error;
604 }
605 if (lck.l_type == F_UNLCK) {
aacea8ba
BP
606 /* pidfile exists but it isn't locked by anyone. We need to delete it
607 * so that a new pidfile can go in its place. But just calling
608 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
609 * before we do and then replaces it by a valid pidfile? We'd unlink
610 * their valid pidfile. We do a little dance to avoid the race, by
611 * locking the invalid pidfile. Only one process can have the invalid
612 * pidfile locked, and only that process has the right to unlink it. */
613 if (!delete_if_stale) {
614 error = ESRCH;
0b376942 615 VLOG_DBG("%s: pid file is stale", pidfile);
aacea8ba
BP
616 goto error;
617 }
618
619 /* Get the lock. */
620 error = lock_pidfile(file, F_SETLK);
621 if (error) {
622 /* We lost a race with someone else doing the same thing. */
623 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
624 goto error;
625 }
626
627 /* Is the file we have locked still named 'pidfile'? */
628 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
629 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
630 /* No. We lost a race with someone else who got the lock before
631 * us, deleted the pidfile, and closed it (releasing the lock). */
632 error = EALREADY;
633 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
634 goto error;
635 }
636
637 /* We won the right to delete the stale pidfile. */
638 if (unlink(pidfile)) {
639 error = errno;
640 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
10a89ef0 641 pidfile, ovs_strerror(error));
aacea8ba
BP
642 goto error;
643 }
644 VLOG_DBG("%s: deleted stale pidfile", pidfile);
645 fclose(file);
646 return 0;
064af421
BP
647 }
648
649 if (!fgets(line, sizeof line, file)) {
650 if (ferror(file)) {
651 error = errno;
10a89ef0 652 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
064af421
BP
653 } else {
654 error = ESRCH;
655 VLOG_WARN("%s: read: unexpected end of file", pidfile);
656 }
657 goto error;
658 }
659
660 if (lck.l_pid != strtoul(line, NULL, 10)) {
aacea8ba
BP
661 /* The process that has the pidfile locked is not the process that
662 * created it. It must be stale, with the process that has it locked
663 * preparing to delete it. */
064af421 664 error = ESRCH;
aacea8ba
BP
665 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
666 pidfile, line, (long int) lck.l_pid);
064af421
BP
667 goto error;
668 }
669
670 fclose(file);
671 return lck.l_pid;
672
673error:
674 if (file) {
675 fclose(file);
676 }
677 return -error;
678}
18e124a2
BP
679
680/* Opens and reads a PID from 'pidfile'. Returns the positive PID if
681 * successful, otherwise a negative errno value. */
682pid_t
683read_pidfile(const char *pidfile)
684{
aacea8ba 685 return read_pidfile__(pidfile, false);
18e124a2
BP
686}
687
aacea8ba
BP
688/* Checks whether a process with the given 'pidfile' is already running and,
689 * if so, aborts. If 'pidfile' is stale, deletes it. */
690static void
691check_already_running(void)
18e124a2 692{
aacea8ba
BP
693 long int pid = read_pidfile__(pidfile, true);
694 if (pid > 0) {
695 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
696 } else if (pid < 0) {
697 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
10a89ef0 698 pidfile, ovs_strerror(-pid));
aacea8ba 699 }
18e124a2 700}
fda546bd
GS
701
702\f
703/* stub functions for non-windows platform. */
704
705void
706service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
707{
708}
709
710void
711service_stop(void)
712{
713}
714
715bool
716should_service_stop(void)
717{
718 return false;
719}
e91b927d
AZ
720
721\f
722static bool
723gid_matches(gid_t expected, gid_t value)
724{
725 return expected == -1 || expected == value;
726}
727
728static bool
6a54bae1 729gid_verify(gid_t gid)
e91b927d 730{
6a54bae1 731 gid_t r, e;
e91b927d 732
6a54bae1
YT
733 r = getgid();
734 e = getegid();
735 return (gid_matches(gid, r) &&
736 gid_matches(gid, e));
e91b927d
AZ
737}
738
739static void
6a54bae1 740daemon_switch_group(gid_t gid)
e91b927d 741{
6a54bae1
YT
742 if ((setgid(gid) == -1) || !gid_verify(gid)) {
743 VLOG_FATAL("%s: fail to switch group to gid as %d, aborting",
e91b927d
AZ
744 pidfile, gid);
745 }
746}
747
748static bool
749uid_matches(uid_t expected, uid_t value)
750{
751 return expected == -1 || expected == value;
752}
753
754static bool
6a54bae1 755uid_verify(const uid_t uid)
e91b927d 756{
6a54bae1 757 uid_t r, e;
e91b927d 758
6a54bae1
YT
759 r = getuid();
760 e = geteuid();
761 return (uid_matches(uid, r) &&
762 uid_matches(uid, e));
e91b927d
AZ
763}
764
765static void
6a54bae1 766daemon_switch_user(const uid_t uid, const char *user)
e91b927d 767{
6a54bae1 768 if ((setuid(uid) == -1) || !uid_verify(uid)) {
e91b927d
AZ
769 VLOG_FATAL("%s: fail to switch user to %s, aborting",
770 pidfile, user);
771 }
772}
773
774/* Use portable Unix APIs to switch uid:gid, when datapath
775 * access is not required. On Linux systems, all capabilities
776 * will be dropped. */
777static void
778daemon_become_new_user_unix(void)
779{
780 /* "Setuid Demystified" by Hao Chen, etc outlines some caveats of
781 * around unix system call setuid() and friends. This implementation
782 * mostly follow the advice given by the paper. The paper is
783 * published in 2002, so things could have changed. */
784
785 /* Change both real and effective uid and gid will permanently
786 * drop the process' privilege. "Setuid Demystified" suggested
787 * that calling getuid() after each setuid() call to verify they
788 * are actually set, because checking return code alone is not
789 * sufficient. */
6a54bae1 790 daemon_switch_group(gid);
e91b927d
AZ
791 if (user && initgroups(user, gid) == -1) {
792 VLOG_FATAL("%s: fail to add supplementary group gid %d, "
793 "aborting", pidfile, gid);
794 }
6a54bae1 795 daemon_switch_user(uid, user);
e91b927d
AZ
796}
797
798/* Linux specific implementation of daemon_become_new_user()
799 * using libcap-ng. */
e91b927d 800static void
6e6271d2 801daemon_become_new_user_linux(bool access_datapath OVS_UNUSED)
e91b927d 802{
6e6271d2 803#if defined __linux__ && HAVE_LIBCAPNG
e91b927d
AZ
804 int ret;
805
806 ret = capng_get_caps_process();
807
808 if (!ret) {
809 if (capng_have_capabilities(CAPNG_SELECT_CAPS) > CAPNG_NONE) {
810 const capng_type_t cap_sets = CAPNG_EFFECTIVE|CAPNG_PERMITTED;
811
812 capng_clear(CAPNG_SELECT_BOTH);
813
814 ret = capng_update(CAPNG_ADD, cap_sets, CAP_IPC_LOCK)
815 || capng_update(CAPNG_ADD, cap_sets, CAP_NET_BIND_SERVICE);
816
817 if (access_datapath && !ret) {
818 ret = capng_update(CAPNG_ADD, cap_sets, CAP_NET_ADMIN)
819 || capng_update(CAPNG_ADD, cap_sets, CAP_NET_RAW);
820 }
821 } else {
822 ret = -1;
823 }
824 }
825
826 if (!ret) {
827 /* CAPNG_INIT_SUPP_GRP will be a better choice than
828 * CAPNG_DROP_SUPP_GRP. However this enum value is only defined
829 * with libcap-ng higher than version 0.7.4, which is not wildly
830 * available on many Linux distributions yet. Taking a more
831 * conservative approach to make sure OVS behaves consistently.
832 *
833 * XXX We may change this for future OVS releases.
834 */
835 ret = capng_change_id(uid, gid, CAPNG_DROP_SUPP_GRP
836 | CAPNG_CLEAR_BOUNDING);
837 }
838
839 if (ret) {
840 VLOG_FATAL("%s: libcap-ng fail to switch to user and group "
841 "%d:%d, aborting", pidfile, uid, gid);
842 }
e91b927d 843#endif
6e6271d2 844}
e91b927d
AZ
845
846static void
847daemon_become_new_user__(bool access_datapath)
848{
3de44dd1
AZ
849 /* If vlog file has been created, change its owner to the non-root user
850 * as specifed by the --user option. */
de929213 851 vlog_change_owner_unix(uid, gid);
3de44dd1 852
e91b927d
AZ
853 if (LINUX) {
854 if (LIBCAPNG) {
855 daemon_become_new_user_linux(access_datapath);
856 } else {
857 VLOG_FATAL("%s: fail to downgrade user using libcap-ng. "
858 "(libcap-ng is not configured at compile time), "
859 "aborting.", pidfile);
860 }
861 } else {
862 daemon_become_new_user_unix();
863 }
864}
865
866/* Noramlly, user switch is embedded within daemonize_start().
867 * However, there in case the user switch needs to be done
868 * before daemonize_start(), the following API can be used. */
869void
870daemon_become_new_user(bool access_datapath)
871{
872 assert_single_threaded();
873 if (switch_user) {
874 daemon_become_new_user__(access_datapath);
6069edb0 875 /* daemonize_start() should not switch user again. */
e91b927d
AZ
876 switch_user = false;
877 }
878}
879
880/* Return the maximun suggested buffer size for both getpwname_r()
881 * and getgrnam_r().
882 *
883 * This size may still not be big enough. in case getpwname_r()
884 * and friends return ERANGE, a larger buffer should be supplied to
885 * retry. (The man page did not specify the max size to stop at, we
886 * will keep trying with doubling the buffer size for each round until
887 * the size wrapps around size_t. */
888static size_t
889get_sysconf_buffer_size(void)
890{
891 size_t bufsize, pwd_bs = 0, grp_bs = 0;
892 const size_t default_bufsize = 1024;
893
894 errno = 0;
895 if ((pwd_bs = sysconf(_SC_GETPW_R_SIZE_MAX)) == -1) {
896 if (errno) {
897 VLOG_FATAL("%s: Read initial passwordd struct size "
898 "failed (%s), aborting. ", pidfile,
899 ovs_strerror(errno));
900 }
901 }
902
903 if ((grp_bs = sysconf(_SC_GETGR_R_SIZE_MAX)) == -1) {
904 if (errno) {
905 VLOG_FATAL("%s: Read initial group struct size "
906 "failed (%s), aborting. ", pidfile,
907 ovs_strerror(errno));
908 }
909 }
910
911 bufsize = MAX(pwd_bs, grp_bs);
912 return bufsize ? bufsize : default_bufsize;
913}
914
915/* Try to double the size of '*buf', return true
916 * if successful, and '*sizep' will be updated with
917 * the new size. Otherwise, return false. */
918static bool
919enlarge_buffer(char **buf, size_t *sizep)
920{
921 size_t newsize = *sizep * 2;
922
923 if (newsize > *sizep) {
924 *buf = xrealloc(*buf, newsize);
925 *sizep = newsize;
926 return true;
927 }
928
929 return false;
930}
931
932/* Parse and sanity check user_spec.
933 *
934 * If successful, set global variables 'uid' and 'gid'
935 * with the parsed results. Global variable 'user'
936 * will be pointing to a string that stores the name
937 * of the user to be switched into.
938 *
939 * Also set 'switch_to_new_user' to true, The actual
940 * user switching is done as soon as daemonize_start()
941 * is called. I/O access before calling daemonize_start()
942 * will still be with root's credential. */
943void
944daemon_set_new_user(const char *user_spec)
945{
946 char *pos = strchr(user_spec, ':');
947 size_t init_bufsize, bufsize;
948
949 init_bufsize = get_sysconf_buffer_size();
950 uid = getuid();
951 gid = getgid();
952
953 if (geteuid() || uid) {
954 VLOG_FATAL("%s: only root can use --user option", pidfile);
955 }
956
957 user_spec += strspn(user_spec, " \t\r\n");
958 size_t len = pos ? pos - user_spec : strlen(user_spec);
959 char *buf;
960 struct passwd pwd, *res;
961 int e;
962
963 bufsize = init_bufsize;
964 buf = xmalloc(bufsize);
965 if (len) {
966 user = xmemdup0(user_spec, len);
967
968 while ((e = getpwnam_r(user, &pwd, buf, bufsize, &res)) == ERANGE) {
969 if (!enlarge_buffer(&buf, &bufsize)) {
970 break;
971 }
972 }
973
974 if (e != 0) {
975 VLOG_FATAL("%s: Failed to retrive user %s's uid (%s), aborting.",
976 pidfile, user, ovs_strerror(e));
977 }
eaf2aa9e
CE
978 if (res == NULL) {
979 VLOG_FATAL("%s: user %s not found, aborting.", pidfile, user);
980 }
e91b927d
AZ
981 } else {
982 /* User name is not specified, use current user. */
983 while ((e = getpwuid_r(uid, &pwd, buf, bufsize, &res)) == ERANGE) {
984 if (!enlarge_buffer(&buf, &bufsize)) {
985 break;
986 }
987 }
988
989 if (e != 0) {
990 VLOG_FATAL("%s: Failed to retrive current user's name "
991 "(%s), aborting.", pidfile, ovs_strerror(e));
992 }
993 user = xstrdup(pwd.pw_name);
994 }
995
996 uid = pwd.pw_uid;
997 gid = pwd.pw_gid;
998 free(buf);
999
1000 if (pos) {
1001 char *grpstr = pos + 1;
1002 grpstr += strspn(grpstr, " \t\r\n");
1003
1004 if (*grpstr) {
71f21279 1005 struct group grp, *gres;
e91b927d
AZ
1006
1007 bufsize = init_bufsize;
1008 buf = xmalloc(bufsize);
71f21279 1009 while ((e = getgrnam_r(grpstr, &grp, buf, bufsize, &gres))
e91b927d
AZ
1010 == ERANGE) {
1011 if (!enlarge_buffer(&buf, &bufsize)) {
1012 break;
1013 }
1014 }
1015
1016 if (e) {
1017 VLOG_FATAL("%s: Failed to get group entry for %s, "
1018 "(%s), aborting.", pidfile, grpstr,
1019 ovs_strerror(e));
1020 }
71f21279 1021 if (gres == NULL) {
eaf2aa9e
CE
1022 VLOG_FATAL("%s: group %s not found, aborting.", pidfile,
1023 grpstr);
1024 }
e91b927d
AZ
1025
1026 if (gid != grp.gr_gid) {
1027 char **mem;
1028
1029 for (mem = grp.gr_mem; *mem; ++mem) {
1030 if (!strcmp(*mem, user)) {
1031 break;
1032 }
1033 }
1034
1035 if (!*mem) {
1036 VLOG_FATAL("%s: Invalid --user option %s (user %s is "
1037 "not in group %s), aborting.", pidfile,
1038 user_spec, user, grpstr);
1039 }
1040 gid = grp.gr_gid;
1041 }
1042 free(buf);
1043 }
1044 }
1045
6069edb0 1046 switch_user = true;
e91b927d 1047}