blob: b1f2be8821dc24fca34c2457aa5da370d380f330 [file] [log] [blame]
David Sodmanbbcb0522014-09-19 10:34:07 -07001/*
2 * Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
David Sodmanbbcb0522014-09-19 10:34:07 -07007#include <stdio.h>
8#include <stdlib.h>
9#include <unistd.h>
David Sodmane46ea8a2015-03-13 15:47:12 -070010#include <string.h>
Daniel Nicoara76622c32015-03-18 17:47:54 -040011#include <sys/file.h>
David Sodmanef1ba362015-03-16 10:50:24 -070012#include <sys/stat.h>
13#include <pwd.h>
David Sodmanbbcb0522014-09-19 10:34:07 -070014
David Sodmane46ea8a2015-03-13 15:47:12 -070015#include "util.h"
16
17void sync_lock(bool acquire)
18{
Daniel Nicoara76622c32015-03-18 17:47:54 -040019 static int lock = -1;
David Sodmane46ea8a2015-03-13 15:47:12 -070020 int stat;
David Sodmanef1ba362015-03-16 10:50:24 -070021 struct passwd* pw;
David Sodmane46ea8a2015-03-13 15:47:12 -070022
Daniel Nicoara76622c32015-03-18 17:47:54 -040023 if (lock < 0)
24 lock = open("/run/frecon", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
25
David Sodmane46ea8a2015-03-13 15:47:12 -070026 if (lock >= 0) {
David Sodmanef1ba362015-03-16 10:50:24 -070027 pw = getpwnam("chronos");
28 if (pw) {
29 stat = fchown(lock, pw->pw_uid, pw->pw_gid);
30 if (stat != 0)
31 LOG(ERROR, "fchown returned %d", stat);
32 }
33
Daniel Nicoara76622c32015-03-18 17:47:54 -040034 if (flock(lock, acquire ? LOCK_EX : LOCK_UN) < 0)
David Sodmanef1ba362015-03-16 10:50:24 -070035 LOG(ERROR, "Failed to operate on synch_lock(acquire = %d):%d, lock=%d: %m",
36 acquire, stat, lock);
David Sodmane46ea8a2015-03-13 15:47:12 -070037 }
38}
39
David Sodmanbbcb0522014-09-19 10:34:07 -070040
41void daemonize()
42{
43 pid_t pid;
44 int fd;
45
46 pid = fork();
47 if (pid == -1)
48 return;
49 else if (pid != 0)
50 exit(EXIT_SUCCESS);
51
52 if (setsid() == -1)
53 return;
54
55 // Re-direct stderr/stdout to the system message log
56 close(0);
57 close(1);
58 close(2);
59
60 open("/dev/kmsg", O_RDWR);
61
62 fd = dup(0);
63 if (fd != STDOUT_FILENO) {
64 close(fd);
65 return;
66 }
67 fd = dup(0);
68 if (fd != STDERR_FILENO) {
69 close(fd);
70 return;
71 }
72}
73
74#ifdef __clang__
75__attribute__((format (__printf__, 2, 0)))
76#endif
77void LOG(int severity, const char* fmt, ...)
78{
79 va_list arg_list;
80 fprintf(stderr, "frecon: ");
81 va_start( arg_list, fmt);
82 vfprintf(stderr, fmt, arg_list);
83 va_end(arg_list);
84 fprintf(stderr, "\n");
85}