1 /*
2 * handlreg.c
3 *
4 * implementation of xentoolcore_restrict_all
5 *
6 * Copyright (c) 2017 Citrix
7 * Part of a generic logging interface used by various dom0 userland libraries.
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation;
12 * version 2.1 of the License.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "xentoolcore_internal.h"
24
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29
30 #include <pthread.h>
31 #include <assert.h>
32
33 static pthread_mutex_t handles_lock = PTHREAD_MUTEX_INITIALIZER;
34 static XENTOOLCORE_LIST_HEAD(, Xentoolcore__Active_Handle) handles;
35
lock(void)36 static void lock(void) {
37 int e = pthread_mutex_lock(&handles_lock);
38 assert(!e);
39 }
40
unlock(void)41 static void unlock(void) {
42 int e = pthread_mutex_unlock(&handles_lock);
43 assert(!e);
44 }
45
xentoolcore__register_active_handle(Xentoolcore__Active_Handle * ah)46 void xentoolcore__register_active_handle(Xentoolcore__Active_Handle *ah) {
47 lock();
48 XENTOOLCORE_LIST_INSERT_HEAD(&handles, ah, entry);
49 unlock();
50 }
51
xentoolcore__deregister_active_handle(Xentoolcore__Active_Handle * ah)52 void xentoolcore__deregister_active_handle(Xentoolcore__Active_Handle *ah) {
53 lock();
54 XENTOOLCORE_LIST_REMOVE(ah, entry);
55 unlock();
56 }
57
xentoolcore_restrict_all(domid_t domid)58 int xentoolcore_restrict_all(domid_t domid) {
59 int r;
60 Xentoolcore__Active_Handle *ah;
61
62 lock();
63 XENTOOLCORE_LIST_FOREACH(ah, &handles, entry) {
64 r = ah->restrict_callback(ah, domid);
65 if (r) goto out;
66 }
67
68 r = 0;
69 out:
70 unlock();
71 return r;
72 }
73
xentoolcore__restrict_by_dup2_null(int fd)74 int xentoolcore__restrict_by_dup2_null(int fd) {
75 int nullfd = -1, r;
76
77 if (fd < 0)
78 /* just in case */
79 return 0;
80
81 nullfd = open("/dev/null", O_RDONLY);
82 if (nullfd < 0) goto err;
83
84 r = dup2(nullfd, fd);
85 if (r < 0) goto err;
86
87 close(nullfd);
88 return 0;
89
90 err:
91 if (nullfd >= 0) close(nullfd);
92 return -1;
93 }
94
95 /*
96 * Local variables:
97 * mode: C
98 * c-file-style: "BSD"
99 * c-basic-offset: 4
100 * tab-width: 4
101 * indent-tabs-mode: nil
102 * End:
103 */
104