1 /*#############################################################################
3 # Pakfire - The IPFire package management system #
4 # Copyright (C) 2022 Pakfire development team #
6 # This program is free software: you can redistribute it and/or modify #
7 # it under the terms of the GNU General Public License as published by #
8 # the Free Software Foundation, either version 3 of the License, or #
9 # (at your option) any later version. #
11 # This program is distributed in the hope that it will be useful, #
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
14 # GNU General Public License for more details. #
16 # You should have received a copy of the GNU General Public License #
17 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 #############################################################################*/
23 #include <linux/capability.h>
24 #include <linux/sched.h>
26 #include <linux/wait.h>
31 #include <sys/capability.h>
32 #include <sys/epoll.h>
33 #include <sys/eventfd.h>
34 #include <sys/mount.h>
35 #include <sys/personality.h>
36 #include <sys/prctl.h>
37 #include <sys/resource.h>
38 #include <sys/timerfd.h>
39 #include <sys/types.h>
45 #include <netlink/route/link.h>
53 #include <pakfire/arch.h>
54 #include <pakfire/cgroup.h>
55 #include <pakfire/jail.h>
56 #include <pakfire/logging.h>
57 #include <pakfire/mount.h>
58 #include <pakfire/pakfire.h>
59 #include <pakfire/path.h>
60 #include <pakfire/private.h>
61 #include <pakfire/pwd.h>
62 #include <pakfire/string.h>
63 #include <pakfire/util.h>
65 #define BUFFER_SIZE 1024 * 64
66 #define ENVIRON_SIZE 128
67 #define EPOLL_MAX_EVENTS 2
68 #define MAX_MOUNTPOINTS 8
70 // The default environment that will be set for every command
71 static const struct environ
{
76 { "LANG", "C.utf-8" },
77 { "PATH", "/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin", },
80 // Tell everything that it is running inside a Pakfire container
81 { "container", "pakfire" },
85 struct pakfire_jail_mountpoint
{
86 char source
[PATH_MAX
];
87 char target
[PATH_MAX
];
92 struct pakfire_ctx
* ctx
;
93 struct pakfire
* pakfire
;
96 // A unique ID for each jail
98 char __uuid
[UUID_STR_LEN
];
104 struct itimerspec timeout
;
107 struct pakfire_cgroup
* cgroup
;
110 char* env
[ENVIRON_SIZE
];
113 struct pakfire_jail_mountpoint mountpoints
[MAX_MOUNTPOINTS
];
114 unsigned int num_mountpoints
;
117 struct pakfire_jail_callbacks
{
119 pakfire_jail_log_callback log
;
124 struct pakfire_log_buffer
{
125 char data
[BUFFER_SIZE
];
129 struct pakfire_jail_exec
{
132 // PID (of the child)
136 // Socket to pass FDs
139 // Process status (from waitid)
142 // FD to notify the client that the parent has finished initialization
146 struct pakfire_jail_pipes
{
156 #endif /* ENABLE_DEBUG */
160 struct pakfire_jail_communicate
{
161 pakfire_jail_communicate_in in
;
162 pakfire_jail_communicate_out out
;
167 struct pakfire_jail_buffers
{
168 struct pakfire_log_buffer stdout
;
169 struct pakfire_log_buffer stderr
;
172 struct pakfire_log_buffer log_INFO
;
173 struct pakfire_log_buffer log_ERROR
;
175 struct pakfire_log_buffer log_DEBUG
;
176 #endif /* ENABLE_DEBUG */
179 struct pakfire_cgroup
* cgroup
;
180 struct pakfire_cgroup_stats cgroup_stats
;
183 struct pakfire_jail_pty
{
184 // The path to the console
185 char console
[PATH_MAX
];
188 struct pakfire_jail_pty_master
{
191 enum pakfire_jail_pty_flags
{
192 PAKFIRE_JAIL_PTY_READY_TO_READ
= (1 << 0),
193 PAKFIRE_JAIL_PTY_READY_TO_WRITE
= (1 << 1),
198 struct pakfire_jail_pty_stdio
{
200 char buffer
[LINE_MAX
];
201 struct termios attrs
;
202 enum pakfire_jail_pty_flags flags
;
206 struct pakfire_jail_pty_stdio stdout
;
210 static int clone3(struct clone_args
* args
, size_t size
) {
211 return syscall(__NR_clone3
, args
, size
);
214 static int pidfd_send_signal(int pidfd
, int sig
, siginfo_t
* info
, unsigned int flags
) {
215 return syscall(SYS_pidfd_send_signal
, pidfd
, sig
, info
, flags
);
218 static int pivot_root(const char* new_root
, const char* old_root
) {
219 return syscall(SYS_pivot_root
, new_root
, old_root
);
222 static int pakfire_jail_exec_has_flag(
223 const struct pakfire_jail_exec
* ctx
, const enum pakfire_jail_exec_flags flag
) {
224 return ctx
->flags
& flag
;
227 static void pakfire_jail_free(struct pakfire_jail
* jail
) {
228 DEBUG(jail
->pakfire
, "Freeing jail at %p\n", jail
);
231 for (unsigned int i
= 0; jail
->env
[i
]; i
++)
235 pakfire_cgroup_unref(jail
->cgroup
);
237 pakfire_unref(jail
->pakfire
);
239 pakfire_ctx_unref(jail
->ctx
);
244 Passes any log messages on to the default pakfire log callback
246 static int pakfire_jail_default_log_callback(struct pakfire
* pakfire
, void* data
,
247 int priority
, const char* line
, size_t length
) {
250 INFO(pakfire
, "%s", line
);
254 ERROR(pakfire
, "%s", line
);
259 DEBUG(pakfire
, "%s", line
);
267 static const char* pakfire_jail_uuid(struct pakfire_jail
* jail
) {
269 uuid_unparse_lower(jail
->uuid
, jail
->__uuid
);
274 static int pakfire_jail_setup_interactive_env(struct pakfire_jail
* jail
) {
276 int r
= pakfire_jail_set_env(jail
, "PS1", "pakfire-jail \\w> ");
281 char* TERM
= secure_getenv("TERM");
283 r
= pakfire_jail_set_env(jail
, "TERM", TERM
);
289 char* LANG
= secure_getenv("LANG");
291 r
= pakfire_jail_set_env(jail
, "LANG", LANG
);
299 PAKFIRE_EXPORT
int pakfire_jail_create(struct pakfire_jail
** jail
, struct pakfire
* pakfire
) {
302 const char* arch
= pakfire_get_effective_arch(pakfire
);
304 // Allocate a new jail
305 struct pakfire_jail
* j
= calloc(1, sizeof(*j
));
310 j
->ctx
= pakfire_ctx(pakfire
);
313 j
->pakfire
= pakfire_ref(pakfire
);
315 // Initialize reference counter
318 // Generate a random UUID
319 uuid_generate_random(j
->uuid
);
321 DEBUG(j
->pakfire
, "Allocated new jail at %p\n", j
);
323 // Set the default logging callback
324 pakfire_jail_set_log_callback(j
, pakfire_jail_default_log_callback
, NULL
);
326 // Set default environment
327 for (const struct environ
* e
= ENV
; e
->key
; e
++) {
328 r
= pakfire_jail_set_env(j
, e
->key
, e
->val
);
333 // Enable all CPU features that CPU has to offer
334 if (!pakfire_arch_is_supported_by_host(arch
)) {
335 r
= pakfire_jail_set_env(j
, "QEMU_CPU", "max");
340 // Set container UUID
341 r
= pakfire_jail_set_env(j
, "container_uuid", pakfire_jail_uuid(j
));
345 // Disable systemctl to talk to systemd
346 if (!pakfire_on_root(j
->pakfire
)) {
347 r
= pakfire_jail_set_env(j
, "SYSTEMD_OFFLINE", "1");
357 pakfire_jail_free(j
);
362 PAKFIRE_EXPORT
struct pakfire_jail
* pakfire_jail_ref(struct pakfire_jail
* jail
) {
368 PAKFIRE_EXPORT
struct pakfire_jail
* pakfire_jail_unref(struct pakfire_jail
* jail
) {
369 if (--jail
->nrefs
> 0)
372 pakfire_jail_free(jail
);
378 PAKFIRE_EXPORT
void pakfire_jail_set_log_callback(struct pakfire_jail
* jail
,
379 pakfire_jail_log_callback callback
, void* data
) {
380 jail
->callbacks
.log
= callback
;
381 jail
->callbacks
.log_data
= data
;
386 PAKFIRE_EXPORT
int pakfire_jail_nice(struct pakfire_jail
* jail
, int nice
) {
387 // Check if nice level is in range
388 if (nice
< -19 || nice
> 20) {
399 int pakfire_jail_set_cgroup(struct pakfire_jail
* jail
, struct pakfire_cgroup
* cgroup
) {
400 // Free any previous cgroup
402 pakfire_cgroup_unref(jail
->cgroup
);
406 // Set any new cgroup
408 DEBUG(jail
->pakfire
, "Setting cgroup %p\n", cgroup
);
410 jail
->cgroup
= pakfire_cgroup_ref(cgroup
);
419 // Returns the length of the environment
420 static unsigned int pakfire_jail_env_length(struct pakfire_jail
* jail
) {
423 // Count everything in the environment
424 for (char** e
= jail
->env
; *e
; e
++)
430 // Finds an existing environment variable and returns its index or -1 if not found
431 static int pakfire_jail_find_env(struct pakfire_jail
* jail
, const char* key
) {
437 const size_t length
= strlen(key
);
439 for (unsigned int i
= 0; jail
->env
[i
]; i
++) {
440 if ((pakfire_string_startswith(jail
->env
[i
], key
)
441 && *(jail
->env
[i
] + length
) == '=')) {
450 // Returns the value of an environment variable or NULL
451 PAKFIRE_EXPORT
const char* pakfire_jail_get_env(struct pakfire_jail
* jail
,
453 int i
= pakfire_jail_find_env(jail
, key
);
457 return jail
->env
[i
] + strlen(key
) + 1;
460 // Sets an environment variable
461 PAKFIRE_EXPORT
int pakfire_jail_set_env(struct pakfire_jail
* jail
,
462 const char* key
, const char* value
) {
463 // Find the index where to write this value to
464 int i
= pakfire_jail_find_env(jail
, key
);
466 i
= pakfire_jail_env_length(jail
);
468 // Return -ENOSPC when the environment is full
469 if (i
>= ENVIRON_SIZE
) {
474 // Free any previous value
478 // Format and set environment variable
479 asprintf(&jail
->env
[i
], "%s=%s", key
, value
);
481 DEBUG(jail
->pakfire
, "Set environment variable: %s\n", jail
->env
[i
]);
486 // Imports an environment
487 PAKFIRE_EXPORT
int pakfire_jail_import_env(struct pakfire_jail
* jail
, const char* env
[]) {
495 // Copy environment variables
496 for (unsigned int i
= 0; env
[i
]; i
++) {
497 r
= pakfire_string_partition(env
[i
], "=", &key
, &val
);
502 r
= pakfire_jail_set_env(jail
, key
, val
);
519 PAKFIRE_EXPORT
int pakfire_jail_set_timeout(
520 struct pakfire_jail
* jail
, unsigned int timeout
) {
522 jail
->timeout
.it_value
.tv_sec
= timeout
;
525 DEBUG(jail
->pakfire
, "Timeout set to %u second(s)\n", timeout
);
527 DEBUG(jail
->pakfire
, "Timeout disabled\n");
532 static int pakfire_jail_create_timer(struct pakfire_jail
* jail
) {
535 // Nothing to do if no timeout has been set
536 if (!jail
->timeout
.it_value
.tv_sec
)
539 // Create a new timer
540 const int fd
= timerfd_create(CLOCK_MONOTONIC
, 0);
542 ERROR(jail
->pakfire
, "Could not create timer: %m\n");
547 r
= timerfd_settime(fd
, 0, &jail
->timeout
, NULL
);
549 ERROR(jail
->pakfire
, "Could not arm timer: %m\n");
563 This function replaces any logging in the child process.
565 All log messages will be sent to the parent process through their respective pipes.
567 static void pakfire_jail_log_redirect(void* data
, int priority
, const char* file
,
568 int line
, const char* fn
, const char* format
, va_list args
) {
569 struct pakfire_jail_pipes
* pipes
= (struct pakfire_jail_pipes
*)data
;
574 fd
= pipes
->log_INFO
[1];
578 fd
= pipes
->log_ERROR
[1];
583 fd
= pipes
->log_DEBUG
[1];
585 #endif /* ENABLE_DEBUG */
587 // Ignore any messages of an unknown priority
592 // Send the log message
594 vdprintf(fd
, format
, args
);
597 static int pakfire_jail_log_buffer_is_full(const struct pakfire_log_buffer
* buffer
) {
598 return (sizeof(buffer
->data
) == buffer
->used
);
602 This function reads as much data as it can from the file descriptor.
603 If it finds a whole line in it, it will send it to the logger and repeat the process.
604 If not newline character is found, it will try to read more data until it finds one.
606 static int pakfire_jail_handle_log(struct pakfire_jail
* jail
,
607 struct pakfire_jail_exec
* ctx
, int priority
, int fd
,
608 struct pakfire_log_buffer
* buffer
, pakfire_jail_communicate_out callback
, void* data
) {
609 char line
[BUFFER_SIZE
+ 1];
611 // Fill up buffer from fd
612 if (buffer
->used
< sizeof(buffer
->data
)) {
613 ssize_t bytes_read
= read(fd
, buffer
->data
+ buffer
->used
,
614 sizeof(buffer
->data
) - buffer
->used
);
617 if (bytes_read
< 0) {
618 ERROR(jail
->pakfire
, "Could not read from fd %d: %m\n", fd
);
622 // Update buffer size
623 buffer
->used
+= bytes_read
;
626 // See if we have any lines that we can write
627 while (buffer
->used
) {
628 // Search for the end of the first line
629 char* eol
= memchr(buffer
->data
, '\n', buffer
->used
);
633 // If the buffer is full, we send the content to the logger and try again
634 // This should not happen in practise
635 if (pakfire_jail_log_buffer_is_full(buffer
)) {
636 DEBUG(jail
->pakfire
, "Logging buffer is full. Sending all content\n");
638 eol
= buffer
->data
+ sizeof(buffer
->data
) - 1;
640 // Otherwise we might have only read parts of the output
645 // Find the length of the string
646 size_t length
= eol
- buffer
->data
+ 1;
648 // Copy the line into the buffer
649 memcpy(line
, buffer
->data
, length
);
651 // Terminate the string
656 int r
= callback(jail
->pakfire
, data
, priority
, line
, length
);
658 ERROR(jail
->pakfire
, "The logging callback returned an error: %d\n", r
);
663 // Remove line from buffer
664 memmove(buffer
->data
, buffer
->data
+ length
, buffer
->used
- length
);
665 buffer
->used
-= length
;
671 static int pakfire_jail_stream_stdin(struct pakfire_jail
* jail
,
672 struct pakfire_jail_exec
* ctx
, const int fd
) {
675 // Nothing to do if there is no stdin callback set
676 if (!ctx
->communicate
.in
) {
677 DEBUG(jail
->pakfire
, "Callback for standard input is not set\n");
681 // Skip if the writing pipe has already been closed
682 if (ctx
->pipes
.stdin
[1] < 0)
685 DEBUG(jail
->pakfire
, "Streaming standard input...\n");
687 // Calling the callback
688 r
= ctx
->communicate
.in(jail
->pakfire
, ctx
->communicate
.data
, fd
);
690 DEBUG(jail
->pakfire
, "Standard input callback finished: %d\n", r
);
692 // The callback signaled that it has written everything
694 DEBUG(jail
->pakfire
, "Closing standard input pipe\n");
696 // Close the file-descriptor
699 // Reset the file-descriptor so it won't be closed again later
700 ctx
->pipes
.stdin
[1] = -1;
709 static int pakfire_jail_recv_fd(struct pakfire_jail
* jail
, int socket
, int* fd
) {
710 const size_t payload_length
= sizeof(fd
);
711 char buffer
[CMSG_SPACE(payload_length
)];
714 struct msghdr msg
= {
715 .msg_control
= buffer
,
716 .msg_controllen
= sizeof(buffer
),
719 // Receive the message
720 r
= recvmsg(socket
, &msg
, 0);
722 CTX_ERROR(jail
->ctx
, "Could not receive file descriptor: %s\n", strerror(errno
));
727 struct cmsghdr
* cmsg
= CMSG_FIRSTHDR(&msg
);
731 *fd
= *((int*)CMSG_DATA(cmsg
));
733 CTX_DEBUG(jail
->ctx
, "Received fd %d from socket %d\n", *fd
, socket
);
738 static int pakfire_jail_send_fd(struct pakfire_jail
* jail
, int socket
, int fd
) {
739 const size_t payload_length
= sizeof(fd
);
740 char buffer
[CMSG_SPACE(payload_length
)];
743 CTX_DEBUG(jail
->ctx
, "Sending fd %d to socket %d\n", fd
, socket
);
746 struct msghdr msg
= {
747 .msg_control
= buffer
,
748 .msg_controllen
= sizeof(buffer
),
752 struct cmsghdr
* cmsg
= CMSG_FIRSTHDR(&msg
);
753 cmsg
->cmsg_level
= SOL_SOCKET
;
754 cmsg
->cmsg_type
= SCM_RIGHTS
;
755 cmsg
->cmsg_len
= CMSG_LEN(payload_length
);
758 *((int*)CMSG_DATA(cmsg
)) = fd
;
761 r
= sendmsg(socket
, &msg
, 0);
763 CTX_ERROR(jail
->ctx
, "Could not send file descriptor: %s\n", strerror(errno
));
770 static int pakfire_jail_setup_pipe(struct pakfire_jail
* jail
, int (*fds
)[2], const int flags
) {
771 int r
= pipe2(*fds
, flags
);
773 ERROR(jail
->pakfire
, "Could not setup pipe: %m\n");
780 static void pakfire_jail_close_pipe(struct pakfire_jail
* jail
, int fds
[2]) {
781 for (unsigned int i
= 0; i
< 2; i
++)
787 This is a convenience function to fetch the reading end of a pipe and
788 closes the write end.
790 static int pakfire_jail_get_pipe_to_read(struct pakfire_jail
* jail
, int (*fds
)[2]) {
791 // Give the variables easier names to avoid confusion
792 int* fd_read
= &(*fds
)[0];
793 int* fd_write
= &(*fds
)[1];
795 // Close the write end of the pipe
796 if (*fd_write
>= 0) {
801 // Return the read end
808 static int pakfire_jail_get_pipe_to_write(struct pakfire_jail
* jail
, int (*fds
)[2]) {
809 // Give the variables easier names to avoid confusion
810 int* fd_read
= &(*fds
)[0];
811 int* fd_write
= &(*fds
)[1];
813 // Close the read end of the pipe
819 // Return the write end
826 static int pakfire_jail_log(struct pakfire
* pakfire
, void* data
, int priority
,
827 const char* line
, const size_t length
) {
828 // Pass everything to the parent logger
829 pakfire_log_condition(pakfire
, priority
, 0, "%.*s", (int)length
, line
);
834 static int pakfire_jail_epoll_add_fd(struct pakfire_jail
* jail
, int epollfd
, int fd
, int events
) {
835 struct epoll_event event
= {
836 .events
= events
|EPOLLHUP
,
844 int flags
= fcntl(fd
, F_GETFL
, 0);
846 // Set modified flags
847 r
= fcntl(fd
, F_SETFL
, flags
|O_NONBLOCK
);
849 CTX_ERROR(jail
->ctx
, "Could not set file descriptor %d into non-blocking mode: %s\n",
850 fd
, strerror(errno
));
854 // Add the file descriptor to the loop
855 r
= epoll_ctl(epollfd
, EPOLL_CTL_ADD
, fd
, &event
);
857 ERROR(jail
->pakfire
, "Could not add file descriptor %d to epoll(): %s\n",
858 fd
, strerror(errno
));
865 static int pakfire_jail_setup_pty_forwarding(struct pakfire_jail
* jail
,
866 struct pakfire_jail_exec
* ctx
, const int epollfd
, const int fd
) {
867 // Store the file descriptor
875 static int pakfire_jail_wait(struct pakfire_jail
* jail
, struct pakfire_jail_exec
* ctx
) {
877 struct epoll_event events
[EPOLL_MAX_EVENTS
];
881 // Fetch file descriptors from context
882 const int stdin
= pakfire_jail_get_pipe_to_write(jail
, &ctx
->pipes
.stdin
);
883 const int stdout
= pakfire_jail_get_pipe_to_read(jail
, &ctx
->pipes
.stdout
);
884 const int stderr
= pakfire_jail_get_pipe_to_read(jail
, &ctx
->pipes
.stderr
);
885 const int pidfd
= ctx
->pidfd
;
887 // Fetch the UNIX domain socket
888 const int socket_recv
= pakfire_jail_get_pipe_to_read(jail
, &ctx
->socket
);
891 const int timerfd
= pakfire_jail_create_timer(jail
);
894 const int log_INFO
= pakfire_jail_get_pipe_to_read(jail
, &ctx
->pipes
.log_INFO
);
895 const int log_ERROR
= pakfire_jail_get_pipe_to_read(jail
, &ctx
->pipes
.log_ERROR
);
897 const int log_DEBUG
= pakfire_jail_get_pipe_to_read(jail
, &ctx
->pipes
.log_DEBUG
);
898 #endif /* ENABLE_DEBUG */
900 // Make a list of all file descriptors we are interested in
901 const struct pakfire_wait_fds
{
905 // Standard input/output
911 { timerfd
, EPOLLIN
},
914 { ctx
->pidfd
, EPOLLIN
},
917 { log_INFO
, EPOLLIN
},
918 { log_ERROR
, EPOLLIN
},
920 { log_DEBUG
, EPOLLIN
},
921 #endif /* ENABLE_DEBUG */
923 // UNIX Domain Socket
924 { socket_recv
, EPOLLIN
},
931 epollfd
= epoll_create1(0);
933 ERROR(jail
->pakfire
, "Could not initialize epoll(): %m\n");
938 // Turn file descriptors into non-blocking mode and add them to epoll()
939 for (const struct pakfire_wait_fds
* fd
= fds
; fd
->events
; fd
++) {
940 // Skip fds which were not initialized
944 // Add the FD to the event loop
945 r
= pakfire_jail_epoll_add_fd(jail
, epollfd
, fd
->fd
, fd
->events
);
952 // Loop for as long as the process is alive
954 int num
= epoll_wait(epollfd
, events
, EPOLL_MAX_EVENTS
, -1);
956 // Ignore if epoll_wait() has been interrupted
960 ERROR(jail
->pakfire
, "epoll_wait() failed: %m\n");
966 for (int i
= 0; i
< num
; i
++) {
967 int e
= events
[i
].events
;
968 int fd
= events
[i
].data
.fd
;
970 struct pakfire_log_buffer
* buffer
= NULL
;
971 pakfire_jail_communicate_out callback
= NULL
;
975 // Check if there is any data to be read
977 // Handle any changes to the PIDFD
979 // Call waidid() and store the result
980 r
= waitid(P_PIDFD
, ctx
->pidfd
, &ctx
->status
, WEXITED
);
982 ERROR(jail
->pakfire
, "waitid() failed: %m\n");
986 // Mark that we have ended so that we will process the remaining
987 // events from epoll() now, but won't restart the outer loop.
991 // Handle timer events
992 } else if (fd
== timerfd
) {
993 DEBUG(jail
->pakfire
, "Timer event received\n");
996 r
= read(timerfd
, garbage
, sizeof(garbage
));
998 ERROR(jail
->pakfire
, "Could not disarm timer: %m\n");
1003 // Terminate the process if it hasn't already ended
1005 DEBUG(jail
->pakfire
, "Terminating process...\n");
1007 // Send SIGTERM to the process
1008 r
= pidfd_send_signal(pidfd
, SIGKILL
, NULL
, 0);
1010 ERROR(jail
->pakfire
, "Could not kill process: %m\n");
1015 // Don't fall through to log processing
1018 // Handle logging messages
1019 } else if (fd
== log_INFO
) {
1020 buffer
= &ctx
->buffers
.log_INFO
;
1021 priority
= LOG_INFO
;
1023 callback
= pakfire_jail_log
;
1025 } else if (fd
== log_ERROR
) {
1026 buffer
= &ctx
->buffers
.log_ERROR
;
1029 callback
= pakfire_jail_log
;
1032 } else if (fd
== log_DEBUG
) {
1033 buffer
= &ctx
->buffers
.log_DEBUG
;
1034 priority
= LOG_DEBUG
;
1036 callback
= pakfire_jail_log
;
1037 #endif /* ENABLE_DEBUG */
1039 // Handle anything from the log pipes
1040 } else if (fd
== stdout
) {
1041 buffer
= &ctx
->buffers
.stdout
;
1042 priority
= LOG_INFO
;
1044 // Send any output to the default logger if no callback is set
1045 if (ctx
->communicate
.out
) {
1046 callback
= ctx
->communicate
.out
;
1047 data
= ctx
->communicate
.data
;
1049 callback
= jail
->callbacks
.log
;
1050 data
= jail
->callbacks
.log_data
;
1053 } else if (fd
== stderr
) {
1054 buffer
= &ctx
->buffers
.stderr
;
1057 // Send any output to the default logger if no callback is set
1058 if (ctx
->communicate
.out
) {
1059 callback
= ctx
->communicate
.out
;
1060 data
= ctx
->communicate
.data
;
1062 callback
= jail
->callbacks
.log
;
1063 data
= jail
->callbacks
.log_data
;
1066 // Handle socket messages
1067 } else if (fd
== socket_recv
) {
1068 // Receive the passed FD
1069 r
= pakfire_jail_recv_fd(jail
, socket_recv
, &fd
);
1073 // Setup PTY forwarding
1074 if (ctx
->pty
.master
.fd
< 0) {
1075 r
= pakfire_jail_setup_pty_forwarding(jail
, ctx
, epollfd
, fd
);
1077 CTX_ERROR(jail
->ctx
, "Failed setting up PTY forwarding: %s\n", strerror(-r
));
1082 // Don't fall through to log processing
1086 DEBUG(jail
->pakfire
, "Received invalid file descriptor %d\n", fd
);
1091 r
= pakfire_jail_handle_log(jail
, ctx
, priority
, fd
, buffer
, callback
, data
);
1097 // Handle standard input
1099 r
= pakfire_jail_stream_stdin(jail
, ctx
, fd
);
1102 // Ignore if we filled up the buffer
1107 ERROR(jail
->pakfire
, "Could not write to stdin: %m\n");
1114 // Check if any file descriptors have been closed
1116 // Remove the file descriptor
1117 r
= epoll_ctl(epollfd
, EPOLL_CTL_DEL
, fd
, NULL
);
1119 ERROR(jail
->pakfire
, "Could not remove closed file-descriptor %d: %m\n", fd
);
1135 int pakfire_jail_capture_stdout(struct pakfire
* pakfire
, void* data
,
1136 int priority
, const char* line
, size_t length
) {
1137 char** output
= (char**)data
;
1140 // Append everything from stdout to a buffer
1141 if (output
&& priority
== LOG_INFO
) {
1142 r
= asprintf(output
, "%s%s", (output
&& *output
) ? *output
: "", line
);
1148 // Send everything else to the default logger
1149 return pakfire_jail_default_log_callback(pakfire
, NULL
, priority
, line
, length
);
1154 // Logs all capabilities of the current process
1155 static int pakfire_jail_show_capabilities(struct pakfire_jail
* jail
) {
1158 cap_flag_value_t value_e
;
1159 cap_flag_value_t value_i
;
1160 cap_flag_value_t value_p
;
1164 pid_t pid
= getpid();
1166 // Fetch all capabilities
1167 caps
= cap_get_proc();
1169 ERROR(jail
->pakfire
, "Could not fetch capabilities: %m\n");
1174 DEBUG(jail
->pakfire
, "Capabilities of PID %d:\n", pid
);
1176 // Iterate over all capabilities
1177 for (unsigned int cap
= 0; cap_valid(cap
); cap
++) {
1178 name
= cap_to_name(cap
);
1180 // Fetch effective value
1181 r
= cap_get_flag(caps
, cap
, CAP_EFFECTIVE
, &value_e
);
1185 // Fetch inheritable value
1186 r
= cap_get_flag(caps
, cap
, CAP_INHERITABLE
, &value_i
);
1190 // Fetch permitted value
1191 r
= cap_get_flag(caps
, cap
, CAP_PERMITTED
, &value_p
);
1195 DEBUG(jail
->pakfire
,
1196 " %-24s : %c%c%c\n",
1198 (value_e
== CAP_SET
) ? 'e' : '-',
1199 (value_i
== CAP_SET
) ? 'i' : '-',
1200 (value_p
== CAP_SET
) ? 'p' : '-'
1220 static int pakfire_jail_set_capabilities(struct pakfire_jail
* jail
) {
1225 // Fetch capabilities
1226 caps
= cap_get_proc();
1228 ERROR(jail
->pakfire
, "Could not read capabilities: %m\n");
1233 // Walk through all capabilities
1234 for (cap_value_t cap
= 0; cap_valid(cap
); cap
++) {
1235 cap_value_t _caps
[] = { cap
};
1237 // Fetch the name of the capability
1238 name
= cap_to_name(cap
);
1240 r
= cap_set_flag(caps
, CAP_EFFECTIVE
, 1, _caps
, CAP_SET
);
1242 ERROR(jail
->pakfire
, "Could not set %s: %m\n", name
);
1246 r
= cap_set_flag(caps
, CAP_INHERITABLE
, 1, _caps
, CAP_SET
);
1248 ERROR(jail
->pakfire
, "Could not set %s: %m\n", name
);
1252 r
= cap_set_flag(caps
, CAP_PERMITTED
, 1, _caps
, CAP_SET
);
1254 ERROR(jail
->pakfire
, "Could not set %s: %m\n", name
);
1263 // Restore all capabilities
1264 r
= cap_set_proc(caps
);
1266 ERROR(jail
->pakfire
, "Restoring capabilities failed: %m\n");
1270 // Add all capabilities to the ambient set
1271 for (unsigned int cap
= 0; cap_valid(cap
); cap
++) {
1272 name
= cap_to_name(cap
);
1274 // Raise the capability
1275 r
= prctl(PR_CAP_AMBIENT
, PR_CAP_AMBIENT_RAISE
, cap
, 0, 0);
1277 ERROR(jail
->pakfire
, "Could not set ambient capability %s: %m\n", name
);
1300 static int pakfire_jail_limit_syscalls(struct pakfire_jail
* jail
) {
1301 const int syscalls
[] = {
1302 // The kernel's keyring isn't namespaced
1305 SCMP_SYS(request_key
),
1307 // Disable userfaultfd
1308 SCMP_SYS(userfaultfd
),
1310 // Disable perf which could leak a lot of information about the host
1311 SCMP_SYS(perf_event_open
),
1317 DEBUG(jail
->pakfire
, "Applying syscall filter...\n");
1319 // Setup a syscall filter which allows everything by default
1320 scmp_filter_ctx ctx
= seccomp_init(SCMP_ACT_ALLOW
);
1322 ERROR(jail
->pakfire
, "Could not setup seccomp filter: %m\n");
1327 for (const int* syscall
= syscalls
; *syscall
; syscall
++) {
1328 r
= seccomp_rule_add(ctx
, SCMP_ACT_ERRNO(EPERM
), *syscall
, 0);
1330 ERROR(jail
->pakfire
, "Could not configure syscall %d: %m\n", *syscall
);
1335 // Load syscall filter into the kernel
1336 r
= seccomp_load(ctx
);
1338 ERROR(jail
->pakfire
, "Could not load syscall filter into the kernel: %m\n");
1344 seccomp_release(ctx
);
1351 PAKFIRE_EXPORT
int pakfire_jail_bind(struct pakfire_jail
* jail
,
1352 const char* source
, const char* target
, int flags
) {
1353 struct pakfire_jail_mountpoint
* mp
= NULL
;
1356 // Check if there is any space left
1357 if (jail
->num_mountpoints
>= MAX_MOUNTPOINTS
) {
1362 // Check for valid inputs
1363 if (!source
|| !target
) {
1368 // Select the next free slot
1369 mp
= &jail
->mountpoints
[jail
->num_mountpoints
];
1372 r
= pakfire_string_set(mp
->source
, source
);
1374 ERROR(jail
->pakfire
, "Could not copy source: %m\n");
1379 r
= pakfire_string_set(mp
->target
, target
);
1381 ERROR(jail
->pakfire
, "Could not copy target: %m\n");
1388 // Increment counter
1389 jail
->num_mountpoints
++;
1394 static int pakfire_jail_mount_networking(struct pakfire_jail
* jail
) {
1397 const char* paths
[] = {
1403 // Bind-mount all paths read-only
1404 for (const char** path
= paths
; *path
; path
++) {
1405 r
= pakfire_bind(jail
->pakfire
, *path
, NULL
, MS_RDONLY
);
1408 // Ignore if we don't have permission
1423 Mounts everything that we require in the new namespace
1425 static int pakfire_jail_mount(struct pakfire_jail
* jail
, struct pakfire_jail_exec
* ctx
) {
1426 struct pakfire_jail_mountpoint
* mp
= NULL
;
1430 // Enable loop devices
1431 if (pakfire_jail_exec_has_flag(ctx
, PAKFIRE_JAIL_HAS_LOOP_DEVICES
))
1432 flags
|= PAKFIRE_MOUNT_LOOP_DEVICES
;
1434 // Mount all default stuff
1435 r
= pakfire_mount_all(jail
->pakfire
, PAKFIRE_MNTNS_OUTER
, flags
);
1440 r
= pakfire_populate_dev(jail
->pakfire
, flags
);
1444 // Mount the interpreter (if needed)
1445 r
= pakfire_mount_interpreter(jail
->pakfire
);
1449 // Mount networking stuff
1450 if (pakfire_jail_exec_has_flag(ctx
, PAKFIRE_JAIL_HAS_NETWORKING
)) {
1451 r
= pakfire_jail_mount_networking(jail
);
1456 // Mount all custom stuff
1457 for (unsigned int i
= 0; i
< jail
->num_mountpoints
; i
++) {
1459 mp
= &jail
->mountpoints
[i
];
1462 r
= pakfire_bind(jail
->pakfire
, mp
->source
, mp
->target
, mp
->flags
);
1472 static int pakfire_jail_setup_loopback(struct pakfire_jail
* jail
) {
1473 struct nl_sock
* nl
= NULL
;
1474 struct nl_cache
* cache
= NULL
;
1475 struct rtnl_link
* link
= NULL
;
1476 struct rtnl_link
* change
= NULL
;
1479 DEBUG(jail
->pakfire
, "Setting up loopback...\n");
1481 // Allocate a netlink socket
1482 nl
= nl_socket_alloc();
1484 ERROR(jail
->pakfire
, "Could not allocate a netlink socket: %m\n");
1489 // Connect the socket
1490 r
= nl_connect(nl
, NETLINK_ROUTE
);
1492 ERROR(jail
->pakfire
, "Could not connect netlink socket: %s\n", nl_geterror(r
));
1496 // Allocate the netlink cache
1497 r
= rtnl_link_alloc_cache(nl
, AF_UNSPEC
, &cache
);
1499 ERROR(jail
->pakfire
, "Unable to allocate netlink cache: %s\n", nl_geterror(r
));
1503 // Fetch loopback interface
1504 link
= rtnl_link_get_by_name(cache
, "lo");
1506 ERROR(jail
->pakfire
, "Could not find lo interface. Ignoring.\n");
1511 // Allocate a new link
1512 change
= rtnl_link_alloc();
1514 ERROR(jail
->pakfire
, "Could not allocate change link\n");
1519 // Set the link to UP
1520 rtnl_link_set_flags(change
, IFF_UP
);
1522 // Apply any changes
1523 r
= rtnl_link_change(nl
, link
, change
, 0);
1525 ERROR(jail
->pakfire
, "Unable to activate loopback: %s\n", nl_geterror(r
));
1541 static int pakfire_jail_setup_uid_mapping(struct pakfire_jail
* jail
, pid_t pid
) {
1542 char path
[PATH_MAX
];
1545 // Skip mapping anything when running on /
1546 if (pakfire_on_root(jail
->pakfire
))
1550 r
= pakfire_string_format(path
, "/proc/%d/uid_map", pid
);
1555 const uid_t uid
= pakfire_uid(jail
->pakfire
);
1558 const struct pakfire_subid
* subuid
= pakfire_subuid(jail
->pakfire
);
1562 /* When running as root, we will map the entire range.
1564 When running as a non-privileged user, we will map the root user inside the jail
1565 to the user's UID outside of the jail, and we will map the rest starting from one.
1570 r
= pakfire_file_write(jail
->pakfire
, path
, 0, 0, 0,
1571 "0 %lu %lu\n", subuid
->id
, subuid
->length
);
1573 r
= pakfire_file_write(jail
->pakfire
, path
, 0, 0, 0,
1574 "0 %lu 1\n1 %lu %lu\n", uid
, subuid
->id
, subuid
->length
);
1578 ERROR(jail
->pakfire
, "Could not map UIDs: %m\n");
1585 static int pakfire_jail_setup_gid_mapping(struct pakfire_jail
* jail
, pid_t pid
) {
1586 char path
[PATH_MAX
];
1589 // Skip mapping anything when running on /
1590 if (pakfire_on_root(jail
->pakfire
))
1594 const gid_t gid
= pakfire_gid(jail
->pakfire
);
1597 const struct pakfire_subid
* subgid
= pakfire_subgid(jail
->pakfire
);
1602 r
= pakfire_string_format(path
, "/proc/%d/gid_map", pid
);
1608 r
= pakfire_file_write(jail
->pakfire
, path
, 0, 0, 0,
1609 "0 %lu %lu\n", subgid
->id
, subgid
->length
);
1611 r
= pakfire_file_write(jail
->pakfire
, path
, 0, 0, 0,
1612 "0 %lu 1\n1 %lu %lu\n", gid
, subgid
->id
, subgid
->length
);
1616 ERROR(jail
->pakfire
, "Could not map GIDs: %m\n");
1623 static int pakfire_jail_setgroups(struct pakfire_jail
* jail
, pid_t pid
) {
1624 char path
[PATH_MAX
];
1628 r
= pakfire_string_format(path
, "/proc/%d/setgroups", pid
);
1632 r
= pakfire_file_write(jail
->pakfire
, path
, 0, 0, 0, "deny\n");
1634 CTX_ERROR(jail
->ctx
, "Could not set setgroups to deny: %s\n", strerror(errno
));
1641 static int pakfire_jail_send_signal(struct pakfire_jail
* jail
, int fd
) {
1642 const uint64_t val
= 1;
1645 DEBUG(jail
->pakfire
, "Sending signal...\n");
1647 // Write to the file descriptor
1648 r
= eventfd_write(fd
, val
);
1650 ERROR(jail
->pakfire
, "Could not send signal: %s\n", strerror(errno
));
1654 // Close the file descriptor
1660 static int pakfire_jail_wait_for_signal(struct pakfire_jail
* jail
, int fd
) {
1664 DEBUG(jail
->pakfire
, "Waiting for signal...\n");
1666 r
= eventfd_read(fd
, &val
);
1668 ERROR(jail
->pakfire
, "Error waiting for signal: %s\n", strerror(errno
));
1672 // Close the file descriptor
1679 Performs the initialisation that needs to happen in the parent part
1681 static int pakfire_jail_parent(struct pakfire_jail
* jail
, struct pakfire_jail_exec
* ctx
) {
1684 // Setup UID mapping
1685 r
= pakfire_jail_setup_uid_mapping(jail
, ctx
->pid
);
1689 // Write "deny" to /proc/PID/setgroups
1690 r
= pakfire_jail_setgroups(jail
, ctx
->pid
);
1694 // Setup GID mapping
1695 r
= pakfire_jail_setup_gid_mapping(jail
, ctx
->pid
);
1699 // Parent has finished initialisation
1700 DEBUG(jail
->pakfire
, "Parent has finished initialization\n");
1702 // Send signal to client
1703 r
= pakfire_jail_send_signal(jail
, ctx
->completed_fd
);
1710 static int pakfire_jail_switch_root(struct pakfire_jail
* jail
, const char* root
) {
1713 // Change to the new root
1716 ERROR(jail
->pakfire
, "chdir(%s) failed: %m\n", root
);
1721 r
= pivot_root(".", ".");
1723 ERROR(jail
->pakfire
, "Failed changing into the new root directory %s: %m\n", root
);
1727 // Umount the old root
1728 r
= umount2(".", MNT_DETACH
);
1730 ERROR(jail
->pakfire
, "Could not umount the old root filesystem: %m\n");
1737 static int pakfire_jail_open_pty(struct pakfire_jail
* jail
, struct pakfire_jail_exec
* ctx
) {
1740 // Allocate a new PTY
1741 ctx
->pty
.master
.fd
= posix_openpt(O_RDWR
|O_NONBLOCK
|O_NOCTTY
|O_CLOEXEC
);
1742 if (ctx
->pty
.master
.fd
< 0)
1746 r
= ptsname_r(ctx
->pty
.master
.fd
, ctx
->pty
.console
, sizeof(ctx
->pty
.console
));
1750 CTX_DEBUG(jail
->ctx
, "Allocated console at %s (%d)\n", ctx
->pty
.console
, ctx
->pty
.master
.fd
);
1754 r
= pakfire_symlink(jail
->ctx
, "/dev/console", ctx
->pty
.console
);
1762 static int pakfire_jail_child(struct pakfire_jail
* jail
, struct pakfire_jail_exec
* ctx
,
1763 const char* argv
[]) {
1766 // Redirect any logging to our log pipe
1767 pakfire_ctx_set_log_callback(jail
->ctx
, pakfire_jail_log_redirect
, &ctx
->pipes
);
1770 pid_t pid
= getpid();
1772 DEBUG(jail
->pakfire
, "Launched child process in jail with PID %d\n", pid
);
1774 // Wait for the parent to finish initialization
1775 r
= pakfire_jail_wait_for_signal(jail
, ctx
->completed_fd
);
1780 r
= prctl(PR_SET_PDEATHSIG
, SIGKILL
, 0, 0, 0);
1782 ERROR(jail
->pakfire
, "Could not configure to die with parent: %m\n");
1786 // Make this process dumpable
1787 r
= prctl (PR_SET_DUMPABLE
, 1, 0, 0, 0);
1789 ERROR(jail
->pakfire
, "Could not make the process dumpable: %m\n");
1793 // Don't drop any capabilities on setuid()
1794 r
= prctl(PR_SET_KEEPCAPS
, 1);
1796 ERROR(jail
->pakfire
, "Could not set PR_SET_KEEPCAPS: %m\n");
1801 uid_t uid
= getuid();
1802 gid_t gid
= getgid();
1805 uid_t euid
= geteuid();
1806 gid_t egid
= getegid();
1808 DEBUG(jail
->pakfire
, " UID: %u (effective %u)\n", uid
, euid
);
1809 DEBUG(jail
->pakfire
, " GID: %u (effective %u)\n", gid
, egid
);
1811 // Log all mountpoints
1812 pakfire_mount_list(jail
->ctx
);
1814 // Fail if we are not PID 1
1816 CTX_ERROR(jail
->ctx
, "Child process is not PID 1\n");
1820 // Fail if we are not running as root
1821 if (uid
|| gid
|| euid
|| egid
) {
1822 ERROR(jail
->pakfire
, "Child process is not running as root\n");
1826 const int socket_send
= pakfire_jail_get_pipe_to_write(jail
, &ctx
->socket
);
1828 // Mount all default stuff
1829 r
= pakfire_mount_all(jail
->pakfire
, PAKFIRE_MNTNS_INNER
, 0);
1833 const char* root
= pakfire_get_path(jail
->pakfire
);
1834 const char* arch
= pakfire_get_effective_arch(jail
->pakfire
);
1836 // Change mount propagation to slave to receive anything from the parent namespace
1837 r
= pakfire_mount_change_propagation(jail
->ctx
, "/", MS_SLAVE
);
1841 // Make root a mountpoint in the new mount namespace
1842 r
= pakfire_mount_make_mounpoint(jail
->pakfire
, root
);
1846 // Change mount propagation to private
1847 r
= pakfire_mount_change_propagation(jail
->ctx
, root
, MS_PRIVATE
);
1851 // Change root (unless root is /)
1852 if (!pakfire_on_root(jail
->pakfire
)) {
1854 r
= pakfire_jail_mount(jail
, ctx
);
1859 r
= pakfire_jail_switch_root(jail
, root
);
1865 unsigned long persona
= pakfire_arch_personality(arch
);
1867 r
= personality(persona
);
1869 ERROR(jail
->pakfire
, "Could not set personality (%x)\n", (unsigned int)persona
);
1875 if (!pakfire_jail_exec_has_flag(ctx
, PAKFIRE_JAIL_HAS_NETWORKING
)) {
1876 r
= pakfire_jail_setup_loopback(jail
);
1883 DEBUG(jail
->pakfire
, "Setting nice level to %d\n", jail
->nice
);
1885 r
= setpriority(PRIO_PROCESS
, pid
, jail
->nice
);
1887 ERROR(jail
->pakfire
, "Could not set nice level: %m\n");
1893 // Create a new session
1896 CTX_ERROR(jail
->ctx
, "Could not create a new session: %s\n", strerror(errno
));
1901 // Allocate a new PTY
1902 r
= pakfire_jail_open_pty(jail
, ctx
);
1904 CTX_ERROR(jail
->ctx
, "Could not allocate a new PTY: %s\n", strerror(-r
));
1908 // Send the PTY master to the parent process
1909 r
= pakfire_jail_send_fd(jail
, socket_send
, ctx
->pty
.master
.fd
);
1911 CTX_ERROR(jail
->ctx
, "Failed sending the PTY master to the parent: %s\n", strerror(-r
));
1915 // Close the master of the PTY
1916 close(ctx
->pty
.master
.fd
);
1917 ctx
->pty
.master
.fd
= -1;
1922 // Close other end of log pipes
1923 close(ctx
->pipes
.log_INFO
[0]);
1924 close(ctx
->pipes
.log_ERROR
[0]);
1926 close(ctx
->pipes
.log_DEBUG
[0]);
1927 #endif /* ENABLE_DEBUG */
1929 // Connect standard input
1930 if (ctx
->pipes
.stdin
[0] >= 0) {
1931 r
= dup2(ctx
->pipes
.stdin
[0], STDIN_FILENO
);
1933 ERROR(jail
->pakfire
, "Could not connect fd %d to stdin: %m\n",
1934 ctx
->pipes
.stdin
[0]);
1940 // Connect standard output and error
1941 if (ctx
->pipes
.stdout
[1] >= 0 && ctx
->pipes
.stderr
[1] >= 0) {
1942 r
= dup2(ctx
->pipes
.stdout
[1], STDOUT_FILENO
);
1944 ERROR(jail
->pakfire
, "Could not connect fd %d to stdout: %m\n",
1945 ctx
->pipes
.stdout
[1]);
1950 r
= dup2(ctx
->pipes
.stderr
[1], STDERR_FILENO
);
1952 ERROR(jail
->pakfire
, "Could not connect fd %d to stderr: %m\n",
1953 ctx
->pipes
.stderr
[1]);
1958 // Close the pipe (as we have moved the original file descriptors)
1959 pakfire_jail_close_pipe(jail
, ctx
->pipes
.stdin
);
1960 pakfire_jail_close_pipe(jail
, ctx
->pipes
.stdout
);
1961 pakfire_jail_close_pipe(jail
, ctx
->pipes
.stderr
);
1964 // Reset open file limit (http://0pointer.net/blog/file-descriptor-limits.html)
1965 r
= pakfire_rlimit_reset_nofile(jail
->pakfire
);
1970 r
= pakfire_jail_set_capabilities(jail
);
1974 // Show capabilities
1975 r
= pakfire_jail_show_capabilities(jail
);
1980 r
= pakfire_jail_limit_syscalls(jail
);
1984 DEBUG(jail
->pakfire
, "Child process initialization done\n");
1985 DEBUG(jail
->pakfire
, "Launching command:\n");
1988 for (unsigned int i
= 0; argv
[i
]; i
++)
1989 DEBUG(jail
->pakfire
, " argv[%u] = %s\n", i
, argv
[i
]);
1992 r
= execvpe(argv
[0], (char**)argv
, jail
->env
);
1994 // Translate errno into regular exit code
1997 // Ignore if the command doesn't exist
1998 if (ctx
->flags
& PAKFIRE_JAIL_NOENT_OK
)
2009 ERROR(jail
->pakfire
, "Could not execve(%s): %m\n", argv
[0]);
2012 // We should not get here
2016 // Run a command in the jail
2017 static int __pakfire_jail_exec(struct pakfire_jail
* jail
, const char* argv
[],
2018 const int interactive
,
2019 pakfire_jail_communicate_in communicate_in
,
2020 pakfire_jail_communicate_out communicate_out
,
2021 void* data
, int flags
) {
2025 // Check if argv is valid
2026 if (!argv
|| !argv
[0]) {
2031 // Initialize context for this call
2032 struct pakfire_jail_exec ctx
= {
2035 .socket
= { -1, -1 },
2038 .stdin
= { -1, -1 },
2039 .stdout
= { -1, -1 },
2040 .stderr
= { -1, -1 },
2041 .log_INFO
= { -1, -1 },
2042 .log_ERROR
= { -1, -1 },
2044 .log_DEBUG
= { -1, -1 },
2045 #endif /* ENABLE_DEBUG */
2049 .in
= communicate_in
,
2050 .out
= communicate_out
,
2070 DEBUG(jail
->pakfire
, "Executing jail...\n");
2072 // Enable networking in interactive mode
2074 ctx
.flags
|= PAKFIRE_JAIL_HAS_NETWORKING
;
2077 Setup a file descriptor which can be used to notify the client that the parent
2078 has completed configuration.
2080 ctx
.completed_fd
= eventfd(0, EFD_CLOEXEC
);
2081 if (ctx
.completed_fd
< 0) {
2082 ERROR(jail
->pakfire
, "eventfd() failed: %m\n");
2086 // Create a UNIX domain socket
2087 r
= socketpair(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, ctx
.socket
);
2089 CTX_ERROR(jail
->ctx
, "Could not create UNIX socket: %s\n", strerror(errno
));
2094 // Create pipes to communicate with child process if we are not running interactively
2096 // stdin (only if callback is set)
2097 if (ctx
.communicate
.in
) {
2098 r
= pakfire_jail_setup_pipe(jail
, &ctx
.pipes
.stdin
, 0);
2104 r
= pakfire_jail_setup_pipe(jail
, &ctx
.pipes
.stdout
, 0);
2109 r
= pakfire_jail_setup_pipe(jail
, &ctx
.pipes
.stderr
, 0);
2114 // Setup pipes for logging
2116 r
= pakfire_jail_setup_pipe(jail
, &ctx
.pipes
.log_INFO
, O_CLOEXEC
);
2121 r
= pakfire_jail_setup_pipe(jail
, &ctx
.pipes
.log_ERROR
, O_CLOEXEC
);
2127 r
= pakfire_jail_setup_pipe(jail
, &ctx
.pipes
.log_DEBUG
, O_CLOEXEC
);
2130 #endif /* ENABLE_DEBUG */
2132 // Configure child process
2133 struct clone_args args
= {
2143 .exit_signal
= SIGCHLD
,
2144 .pidfd
= (long long unsigned int)&ctx
.pidfd
,
2147 // Launch the process in a cgroup that is a leaf of the configured cgroup
2149 args
.flags
|= CLONE_INTO_CGROUP
;
2152 const char* uuid
= pakfire_jail_uuid(jail
);
2154 // Create a temporary cgroup
2155 r
= pakfire_cgroup_child(&ctx
.cgroup
, jail
->cgroup
, uuid
, 0);
2157 ERROR(jail
->pakfire
, "Could not create cgroup for jail: %m\n");
2161 // Clone into this cgroup
2162 args
.cgroup
= pakfire_cgroup_fd(ctx
.cgroup
);
2166 if (!pakfire_jail_exec_has_flag(&ctx
, PAKFIRE_JAIL_HAS_NETWORKING
)) {
2167 args
.flags
|= CLONE_NEWNET
;
2170 // Fork this process
2171 ctx
.pid
= clone3(&args
, sizeof(args
));
2173 ERROR(jail
->pakfire
, "Could not clone: %m\n");
2177 } else if (ctx
.pid
== 0) {
2178 r
= pakfire_jail_child(jail
, &ctx
, argv
);
2183 r
= pakfire_jail_parent(jail
, &ctx
);
2187 DEBUG(jail
->pakfire
, "Waiting for PID %d to finish its work\n", ctx
.pid
);
2189 // Read output of the child process
2190 r
= pakfire_jail_wait(jail
, &ctx
);
2194 // Handle exit status
2195 switch (ctx
.status
.si_code
) {
2197 DEBUG(jail
->pakfire
, "The child process exited with code %d\n",
2198 ctx
.status
.si_status
);
2201 exit
= ctx
.status
.si_status
;
2205 ERROR(jail
->pakfire
, "The child process was killed\n");
2210 ERROR(jail
->pakfire
, "The child process terminated abnormally\n");
2213 // Log anything else
2215 ERROR(jail
->pakfire
, "Unknown child exit code: %d\n", ctx
.status
.si_code
);
2220 // Destroy the temporary cgroup (if any)
2222 // Read cgroup stats
2223 pakfire_cgroup_stat(ctx
.cgroup
, &ctx
.cgroup_stats
);
2224 pakfire_cgroup_stat_dump(ctx
.cgroup
, &ctx
.cgroup_stats
);
2225 pakfire_cgroup_destroy(ctx
.cgroup
);
2226 pakfire_cgroup_unref(ctx
.cgroup
);
2229 // Close any file descriptors
2230 pakfire_jail_close_pipe(jail
, ctx
.pipes
.stdin
);
2231 pakfire_jail_close_pipe(jail
, ctx
.pipes
.stdout
);
2232 pakfire_jail_close_pipe(jail
, ctx
.pipes
.stderr
);
2235 if (ctx
.pty
.master
.fd
>= 0)
2236 close(ctx
.pty
.master
.fd
);
2237 pakfire_jail_close_pipe(jail
, ctx
.pipes
.log_INFO
);
2238 pakfire_jail_close_pipe(jail
, ctx
.pipes
.log_ERROR
);
2240 pakfire_jail_close_pipe(jail
, ctx
.pipes
.log_DEBUG
);
2241 #endif /* ENABLE_DEBUG */
2242 pakfire_jail_close_pipe(jail
, ctx
.socket
);
2247 PAKFIRE_EXPORT
int pakfire_jail_exec(
2248 struct pakfire_jail
* jail
,
2250 pakfire_jail_communicate_in callback_in
,
2251 pakfire_jail_communicate_out callback_out
,
2252 void* data
, int flags
) {
2253 return __pakfire_jail_exec(jail
, argv
, 0, callback_in
, callback_out
, data
, flags
);
2256 static int pakfire_jail_exec_interactive(
2257 struct pakfire_jail
* jail
, const char* argv
[], int flags
) {
2260 // Setup interactive stuff
2261 r
= pakfire_jail_setup_interactive_env(jail
);
2265 return __pakfire_jail_exec(jail
, argv
, 1, NULL
, NULL
, NULL
, flags
);
2268 int pakfire_jail_exec_script(struct pakfire_jail
* jail
,
2272 pakfire_jail_communicate_in callback_in
,
2273 pakfire_jail_communicate_out callback_out
,
2275 char path
[PATH_MAX
];
2276 const char** argv
= NULL
;
2280 const char* root
= pakfire_get_path(jail
->pakfire
);
2282 // Write the scriptlet to disk
2283 r
= pakfire_path_append(path
, root
, PAKFIRE_TMP_DIR
"/pakfire-script.XXXXXX");
2287 // Create a temporary file
2288 f
= pakfire_mktemp(path
, 0700);
2290 ERROR(jail
->pakfire
, "Could not create temporary file: %m\n");
2294 DEBUG(jail
->pakfire
, "Writing script to %s:\n%.*s\n", path
, (int)size
, script
);
2297 r
= fprintf(f
, "%s", script
);
2299 ERROR(jail
->pakfire
, "Could not write script to file %s: %m\n", path
);
2306 ERROR(jail
->pakfire
, "Could not close script file %s: %m\n", path
);
2312 // Count how many arguments were passed
2313 unsigned int argc
= 1;
2315 for (const char** arg
= args
; *arg
; arg
++)
2319 argv
= calloc(argc
+ 1, sizeof(*argv
));
2321 ERROR(jail
->pakfire
, "Could not allocate argv: %m\n");
2326 argv
[0] = (root
) ? pakfire_path_relpath(root
, path
) : path
;
2329 for (unsigned int i
= 1; i
< argc
; i
++)
2330 argv
[i
] = args
[i
-1];
2333 r
= pakfire_jail_exec(jail
, argv
, callback_in
, callback_out
, data
, 0);
2341 // Remove script from disk
2349 A convenience function that creates a new jail, runs the given command and destroys
2352 int pakfire_jail_run(struct pakfire
* pakfire
, const char* argv
[], int flags
, char** output
) {
2353 struct pakfire_jail
* jail
= NULL
;
2356 // Create a new jail
2357 r
= pakfire_jail_create(&jail
, pakfire
);
2361 // Execute the command
2362 r
= pakfire_jail_exec(jail
, argv
, NULL
, pakfire_jail_capture_stdout
, output
, 0);
2366 pakfire_jail_unref(jail
);
2371 int pakfire_jail_run_script(struct pakfire
* pakfire
,
2372 const char* script
, const size_t length
, const char* argv
[], int flags
) {
2373 struct pakfire_jail
* jail
= NULL
;
2376 // Create a new jail
2377 r
= pakfire_jail_create(&jail
, pakfire
);
2381 // Execute the command
2382 r
= pakfire_jail_exec_script(jail
, script
, length
, argv
, NULL
, NULL
, NULL
);
2386 pakfire_jail_unref(jail
);
2391 int pakfire_jail_shell(struct pakfire_jail
* jail
) {
2394 const char* argv
[] = {
2395 "/bin/bash", "--login", NULL
,
2398 // Execute /bin/bash
2399 r
= pakfire_jail_exec_interactive(jail
, argv
, 0);
2405 // Ignore any return codes from the shell
2409 static int pakfire_jail_run_if_possible(struct pakfire
* pakfire
, const char** argv
) {
2410 char path
[PATH_MAX
];
2413 r
= pakfire_path(pakfire
, path
, "%s", *argv
);
2417 // Check if the file is executable
2418 r
= access(path
, X_OK
);
2420 DEBUG(pakfire
, "%s is not executable. Skipping...\n", *argv
);
2424 return pakfire_jail_run(pakfire
, argv
, 0, NULL
);
2427 int pakfire_jail_ldconfig(struct pakfire
* pakfire
) {
2428 const char* argv
[] = {
2433 return pakfire_jail_run_if_possible(pakfire
, argv
);
2436 int pakfire_jail_run_systemd_tmpfiles(struct pakfire
* pakfire
) {
2437 const char* argv
[] = {
2438 "/usr/bin/systemd-tmpfiles",
2443 return pakfire_jail_run_if_possible(pakfire
, argv
);