blob: 992fd83b069e299a1eac4194554df16cc480425b [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>
David Sodmanbbcb0522014-09-19 10:34:07 -070011#include <fcntl.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{
19 int lock;
20 int stat;
21 struct flock flock;
David Sodmanef1ba362015-03-16 10:50:24 -070022 struct passwd* pw;
David Sodmane46ea8a2015-03-13 15:47:12 -070023
David Sodmanef1ba362015-03-16 10:50:24 -070024 lock = open("/run/frecon", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
David Sodmane46ea8a2015-03-13 15:47:12 -070025 if (lock >= 0) {
David Sodmanef1ba362015-03-16 10:50:24 -070026 pw = getpwnam("chronos");
27 if (pw) {
28 stat = fchown(lock, pw->pw_uid, pw->pw_gid);
29 if (stat != 0)
30 LOG(ERROR, "fchown returned %d", stat);
31 }
32
David Sodmane46ea8a2015-03-13 15:47:12 -070033 memset(&flock, 0, sizeof(flock));
34 flock.l_type = acquire ? F_WRLCK : F_UNLCK;
35 flock.l_whence = SEEK_SET;
36 flock.l_start = 0;
David Sodmanef1ba362015-03-16 10:50:24 -070037 flock.l_len = 0;
David Sodmane46ea8a2015-03-13 15:47:12 -070038 stat = fcntl(lock, F_SETLK, &flock);
39 if (stat < 0)
David Sodmanef1ba362015-03-16 10:50:24 -070040 LOG(ERROR, "Failed to operate on synch_lock(acquire = %d):%d, lock=%d: %m",
41 acquire, stat, lock);
David Sodmane46ea8a2015-03-13 15:47:12 -070042 }
43}
44
David Sodmanbbcb0522014-09-19 10:34:07 -070045
46void daemonize()
47{
48 pid_t pid;
49 int fd;
50
51 pid = fork();
52 if (pid == -1)
53 return;
54 else if (pid != 0)
55 exit(EXIT_SUCCESS);
56
57 if (setsid() == -1)
58 return;
59
60 // Re-direct stderr/stdout to the system message log
61 close(0);
62 close(1);
63 close(2);
64
65 open("/dev/kmsg", O_RDWR);
66
67 fd = dup(0);
68 if (fd != STDOUT_FILENO) {
69 close(fd);
70 return;
71 }
72 fd = dup(0);
73 if (fd != STDERR_FILENO) {
74 close(fd);
75 return;
76 }
77}
78
79#ifdef __clang__
80__attribute__((format (__printf__, 2, 0)))
81#endif
82void LOG(int severity, const char* fmt, ...)
83{
84 va_list arg_list;
85 fprintf(stderr, "frecon: ");
86 va_start( arg_list, fmt);
87 vfprintf(stderr, fmt, arg_list);
88 va_end(arg_list);
89 fprintf(stderr, "\n");
90}