26 #include "dbus-sysdeps.h"
27 #include "dbus-sysdeps-unix.h"
28 #include "dbus-internals.h"
29 #include "dbus-list.h"
30 #include "dbus-pipe.h"
31 #include "dbus-protocol.h"
32 #include "dbus-string.h"
33 #define DBUS_USERDB_INCLUDES_PRIVATE 1
34 #include "dbus-userdb.h"
35 #include "dbus-test.h"
37 #include <sys/types.h>
46 #ifdef HAVE_SYS_RESOURCE_H
47 #include <sys/resource.h>
50 #include <sys/socket.h>
54 #ifdef HAVE_SYS_SYSLIMITS_H
55 #include <sys/syslimits.h>
59 #include <systemd/sd-daemon.h>
63 #include <sys/capability.h>
93 DBusEnsureStandardFdsFlags flags;
95 _dbus_verbose (
"Becoming a daemon...\n");
97 _dbus_verbose (
"chdir to /\n");
101 "Could not chdir() to root directory");
105 _dbus_verbose (
"forking...\n");
106 switch ((child_pid = fork ()))
109 _dbus_verbose (
"fork failed\n");
111 "Failed to fork daemon: %s", _dbus_strerror (errno));
116 _dbus_verbose (
"in child, closing std file descriptors\n");
118 flags = DBUS_FORCE_STDIN_NULL | DBUS_FORCE_STDOUT_NULL;
121 if (s ==
NULL || *s ==
'\0')
122 flags |= DBUS_FORCE_STDERR_NULL;
124 _dbus_verbose (
"keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
128 _dbus_warn (
"%s: %s", s, _dbus_strerror (errno));
135 _dbus_verbose (
"setting umask\n");
139 _dbus_verbose (
"calling setsid()\n");
149 _dbus_verbose (
"pid file or pipe write failed: %s\n",
151 kill (child_pid, SIGTERM);
155 _dbus_verbose (
"parent exiting\n");
173 _dbus_write_pid_file (
const DBusString *filename,
177 const char *cfilename;
181 cfilename = _dbus_string_get_const_data (filename);
183 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
188 "Failed to open \"%s\": %s", cfilename,
189 _dbus_strerror (errno));
193 if ((f = fdopen (fd,
"w")) ==
NULL)
196 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
201 if (fprintf (f,
"%lu\n", pid) < 0)
204 "Failed to write to \"%s\": %s", cfilename,
205 _dbus_strerror (errno));
211 if (fclose (f) == EOF)
214 "Failed to close \"%s\": %s", cfilename,
215 _dbus_strerror (errno));
241 _dbus_verbose (
"writing pid file %s\n", _dbus_string_get_const_data (pidfile));
242 if (!_dbus_write_pid_file (pidfile,
246 _dbus_verbose (
"pid file write failed\n");
247 _DBUS_ASSERT_ERROR_IS_SET(error);
253 _dbus_verbose (
"No pid file requested\n");
256 if (print_pid_pipe !=
NULL && _dbus_pipe_is_valid (print_pid_pipe))
261 _dbus_verbose (
"writing our pid to pipe %d\n",
266 _DBUS_SET_OOM (error);
274 _DBUS_SET_OOM (error);
278 bytes = _dbus_string_get_length (&pid);
279 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
285 "Printing message bus PID: did not write enough bytes\n");
295 _dbus_verbose (
"No pid pipe to write to\n");
319 #ifndef HAVE_LIBAUDIT
340 "User '%s' does not appear to exist?",
352 if (setgroups (0,
NULL) < 0)
353 _dbus_warn (
"Failed to drop supplementary groups: %s",
354 _dbus_strerror (errno));
359 if (setgid (gid) < 0)
362 "Failed to set GID to %lu: %s", gid,
363 _dbus_strerror (errno));
367 if (setuid (uid) < 0)
370 "Failed to set UID to %lu: %s", uid,
371 _dbus_strerror (errno));
381 cap_value_t cap_val=0;
382 capsproc=cap_get_proc();
387 while (cap_val<=CAP_LAST_CAP){
388 cap_flag_value_t val;
390 if (0==cap_get_flag(capsproc,
394 cap_set_flag(capsproc, CAP_EFFECTIVE, 1, &cap_val, val);
400 cap_set_proc(capsproc);
402 if (capsproc) cap_free(capsproc);
410 #ifdef HAVE_SETRLIMIT
421 _dbus_rlimit_save_fd_limit (
DBusError *error)
429 _DBUS_SET_OOM (error);
433 if (getrlimit (RLIMIT_NOFILE, &self->lim) < 0)
436 "Failed to get fd limit: %s", _dbus_strerror (errno));
447 #define ENOUGH_FDS 65536
450 _dbus_rlimit_raise_fd_limit (
DBusError *error)
452 struct rlimit old, lim;
454 if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
457 "Failed to get fd limit: %s", _dbus_strerror (errno));
469 if (lim.rlim_cur != RLIM_INFINITY &&
470 lim.rlim_cur < ENOUGH_FDS)
471 lim.rlim_cur = ENOUGH_FDS;
473 if (lim.rlim_max != RLIM_INFINITY &&
474 lim.rlim_max < lim.rlim_cur)
475 lim.rlim_max = lim.rlim_cur;
484 if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
486 #if defined(__APPLE__) && defined(__MACH__)
488 lim.rlim_cur = MIN (OPEN_MAX, lim.rlim_max);
490 lim.rlim_cur = lim.rlim_max;
495 if (lim.rlim_max == old.rlim_max &&
496 lim.rlim_cur == old.rlim_cur)
499 if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
502 "Failed to set fd limit to %lu: %s",
503 (
unsigned long) lim.rlim_cur,
504 _dbus_strerror (errno));
512 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
515 if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
518 "Failed to restore old fd limit: %s",
519 _dbus_strerror (errno));
529 fd_limit_not_supported (
DBusError *error)
532 "cannot change fd limit on this platform");
536 _dbus_rlimit_save_fd_limit (
DBusError *error)
538 fd_limit_not_supported (error);
543 _dbus_rlimit_raise_fd_limit (
DBusError *error)
545 fd_limit_not_supported (error);
550 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
553 fd_limit_not_supported (error);
560 _dbus_rlimit_free (DBusRLimit *lim)
574 struct sigaction act;
577 sigemptyset (&empty_mask);
578 act.sa_handler = handler;
579 act.sa_mask = empty_mask;
581 sigaction (sig, &act,
NULL);
592 return (access (file, F_OK) == 0);
605 #ifdef DBUS_CONSOLE_AUTH_DIR
612 _DBUS_SET_OOM (error);
618 _DBUS_SET_OOM (error);
626 _DBUS_SET_OOM (error);
651 if (_dbus_string_get_length (filename) > 0)
652 return _dbus_string_get_byte (filename, 0) ==
'/';
670 const char *filename_c;
673 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
675 filename_c = _dbus_string_get_const_data (filename);
677 if (stat (filename_c, &sb) < 0)
680 "%s", _dbus_strerror (errno));
684 statbuf->
mode = sb.st_mode;
685 statbuf->
nlink = sb.st_nlink;
686 statbuf->
uid = sb.st_uid;
687 statbuf->
gid = sb.st_gid;
688 statbuf->
size = sb.st_size;
689 statbuf->
atime = sb.st_atime;
690 statbuf->
mtime = sb.st_mtime;
691 statbuf->
ctime = sb.st_ctime;
719 const char *filename_c;
721 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
723 filename_c = _dbus_string_get_const_data (filename);
725 d = opendir (filename_c);
729 "Failed to read directory \"%s\": %s",
731 _dbus_strerror (errno));
739 "Could not allocate memory for directory iterator");
769 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
773 ent = readdir (iter->
d);
782 "%s", _dbus_strerror (err));
786 else if (ent->d_name[0] ==
'.' &&
787 (ent->d_name[1] ==
'\0' ||
788 (ent->d_name[1] ==
'.' && ent->d_name[2] ==
'\0')))
796 "No memory to read directory entry");
817 fill_user_info_from_group (
struct group *g,
823 info->
gid = g->gr_gid;
843 const char *group_c_str;
849 group_c_str = _dbus_string_get_const_data (groupname);
858 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
868 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
874 if ((
long) buflen <= 0)
888 #ifdef HAVE_POSIX_GETPWNAM_R
890 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
893 result = getgrgid_r (gid, &g_str, buf, buflen,
896 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
902 if (result == ERANGE && buflen < 512 * 1024)
913 if (result == 0 && g == &g_str)
915 b = fill_user_info_from_group (g, info, error);
922 "Group %s unknown or failed to look it up\n",
923 group_c_str ? group_c_str :
"???");
933 g = getgrnam (group_c_str);
937 return fill_user_info_from_group (g, info, error);
942 "Group %s unknown or failed to look it up\n",
943 group_c_str ? group_c_str :
"???");
983 return fill_group_info (info, gid,
NULL, error);
1102 sep = _dbus_string_get_length (filename);
1106 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) ==
'/')
1120 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) ==
'/')
1126 _dbus_string_get_byte (filename, 0) ==
'/')
1130 dirname, _dbus_string_get_length (dirname));
1140 buf = _dbus_string_get_udata (str);
1141 len = _dbus_string_get_length (str);
1143 for (i = 0; i < len; i++)
1145 unsigned char c = (
unsigned char) buf[i];
1148 else if (c < 0x20 || c > 127)
1180 _DBUS_SET_OOM (error);
1186 _DBUS_SET_OOM (error);
1194 fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1199 "Failed to open \"%s\": %s",
1200 _dbus_string_get_const_data (&path),
1201 _dbus_strerror (errno));
1209 "Failed to read from \"%s\": %s",
1210 _dbus_string_get_const_data (&path),
1211 _dbus_strerror (errno));
1219 string_squash_nonprintable (&cmdline);
1228 _DBUS_SET_OOM (error);
1250 ensure_owned_directory (
const char *label,
1255 const char *dir = _dbus_string_get_const_data (
string);
1277 if (stat (dir, &buf) != 0)
1279 int saved_errno = errno;
1282 "%s \"%s\" not available: %s", label, dir,
1283 _dbus_strerror (saved_errno));
1287 if (!S_ISDIR (buf.st_mode))
1294 if (buf.st_uid != geteuid ())
1297 "%s \"%s\" is owned by uid %ld, not our uid %ld",
1298 label, dir, (
long) buf.st_uid, (
long) geteuid ());
1304 if ((S_IWOTH | S_IWGRP) & buf.st_mode)
1307 "%s \"%s\" can be written by others (mode 0%o)",
1308 label, dir, buf.st_mode);
1315 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
1316 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
1329 const char *xdg_runtime_dir;
1338 _DBUS_SET_OOM (error);
1345 _DBUS_SET_OOM (error);
1353 _DBUS_SET_OOM (error);
1360 if (xdg_runtime_dir ==
NULL)
1362 _dbus_verbose (
"XDG_RUNTIME_DIR is unset: transient session services "
1363 "not available here\n");
1374 _DBUS_SET_OOM (error);
1378 if (!ensure_owned_directory (
"XDG_RUNTIME_DIR", &xrd,
FALSE, error) ||
1379 !ensure_owned_directory (
"XDG_RUNTIME_DIR subdirectory", &dbus1,
TRUE,
1381 !ensure_owned_directory (
"XDG_RUNTIME_DIR subdirectory", &services,
1388 _DBUS_SET_OOM (error);
1392 _dbus_verbose (
"Transient service directory is %s\n", data);
1425 const char *xdg_data_home;
1426 const char *xdg_data_dirs;
1435 if (xdg_data_home !=
NULL)
1459 if (xdg_data_dirs !=
NULL)
1483 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
1526 static const char standard_search_path[] =
1536 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
1570 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
1582 _dbus_test_append_different_uid (
DBusString *uid)
1584 if (geteuid () == 0)
1600 _dbus_test_append_different_username (
DBusString *username)
1602 if (geteuid () == 0)
1629 int saved_errno = 0;
1630 const char *error_str =
NULL;
1633 fd = open (
"/proc/self/oom_score_adj", O_RDWR | O_CLOEXEC);
1638 fd = open (
"/proc/self/oom_score_adj", O_RDWR);
1644 ssize_t read_result = -1;
1647 char first_char =
'\0';
1649 read_result = read (fd, &first_char, 1);
1651 if (read_result < 0)
1656 error_str =
"failed to read from /proc/self/oom_score_adj";
1657 saved_errno = errno;
1677 if (read_result == 0 || first_char !=
'-')
1685 if (pwrite (fd,
"0",
sizeof (
char), 0) < 0)
1688 error_str =
"writing oom_score_adj error";
1689 saved_errno = errno;
1696 else if (errno == ENOENT)
1705 error_str =
"open(/proc/self/oom_score_adj)";
1706 saved_errno = errno;
1714 if (error_str_p !=
NULL)
1715 *error_str_p = error_str;
1717 errno = saved_errno;
dbus_bool_t _dbus_get_session_config_file(DBusString *str)
Get the absolute path of the session.conf file.
dbus_bool_t _dbus_ensure_standard_fds(DBusEnsureStandardFdsFlags flags, const char **error_str_p)
Ensure that the standard file descriptors stdin, stdout and stderr are open, by opening /dev/null if ...
dbus_bool_t _dbus_concat_dir_and_file(DBusString *dir, const DBusString *next_component)
Appends the given filename to the given directory.
dbus_bool_t _dbus_set_up_transient_session_servicedirs(DBusList **dirs, DBusError *error)
Returns the standard directories for a session bus to look for transient service activation files.
dbus_bool_t _dbus_get_system_config_file(DBusString *str)
Get the absolute path of the system.conf file (there is no system bus on Windows so this can just ret...
dbus_bool_t _dbus_group_info_fill_gid(DBusGroupInfo *info, dbus_gid_t gid, DBusError *error)
Initializes the given DBusGroupInfo struct with information about the given group ID.
void _dbus_string_free(DBusString *str)
Frees a string created by _dbus_string_init().
dbus_uid_t uid
User owning file.
dbus_bool_t _dbus_get_standard_system_servicedirs(DBusList **dirs)
Returns the standard directories for a system bus to look for service activation files.
dbus_bool_t _dbus_stat(const DBusString *filename, DBusStat *statbuf, DBusError *error)
stat() wrapper.
DBUS_PRIVATE_EXPORT dbus_bool_t _dbus_string_append_int(DBusString *str, long value)
Appends an integer to a DBusString.
const char * _dbus_error_from_errno(int error_number)
Converts a UNIX errno, or Windows errno or WinSock error value into a DBusError name.
dbus_bool_t _dbus_replace_install_prefix(DBusString *path)
Replace the DBUS_PREFIX in the given path, in-place, by the current D-Bus installation directory.
void _dbus_directory_close(DBusDirIter *iter)
Closes a directory iteration.
dbus_bool_t _dbus_string_find_byte_backward(const DBusString *str, int start, unsigned char byte, int *found)
Find the given byte scanning backward from the given start.
Portable struct with stat() results.
dbus_bool_t _dbus_get_user_id_and_primary_group(const DBusString *username, dbus_uid_t *uid_p, dbus_gid_t *gid_p)
Gets user ID and primary group given username.
dbus_bool_t _dbus_reset_oom_score_adj(const char **error_str_p)
If the current process has been protected from the Linux OOM killer (the oom_score_adj process parame...
dbus_bool_t _dbus_string_copy(const DBusString *source, int start, DBusString *dest, int insert_at)
Like _dbus_string_move(), but does not delete the section of the source string that's copied to the d...
dbus_bool_t _dbus_group_info_fill(DBusGroupInfo *info, const DBusString *groupname, DBusError *error)
Initializes the given DBusGroupInfo struct with information about the given group name.
unsigned long ctime
Creation time.
Information about a UNIX group.
dbus_bool_t _dbus_path_is_absolute(const DBusString *filename)
Checks whether the filename is an absolute path.
unsigned long dbus_gid_t
A group ID.
dbus_bool_t _dbus_string_init(DBusString *str)
Initializes a string.
dbus_bool_t _dbus_groups_from_uid(dbus_uid_t uid, dbus_gid_t **group_ids, int *n_group_ids)
Gets all groups corresponding to the given UID.
dbus_bool_t _dbus_unix_user_is_process_owner(dbus_uid_t uid)
Checks to see if the UNIX user ID matches the UID of the process.
dbus_bool_t _dbus_string_get_dirname(const DBusString *filename, DBusString *dirname)
Get the directory name from a complete filename.
#define TRUE
Expands to "1".
dbus_bool_t _dbus_list_append(DBusList **list, void *data)
Appends a value to the list.
dbus_bool_t _dbus_user_at_console(const char *username, DBusError *error)
Checks if user is at the console.
#define DBUS_ERROR_FAILED
A generic error; "something went wrong" - see the error message for more.
dbus_bool_t _dbus_change_to_daemon_user(const char *user, DBusError *error)
Changes the user and group the bus is running as.
unsigned long atime
Access time.
int _dbus_read(int fd, DBusString *buffer, int count)
Thin wrapper around the read() system call that appends the data it reads to the DBusString buffer.
void dbus_free(void *memory)
Frees a block of memory previously allocated by dbus_malloc() or dbus_malloc0().
dbus_bool_t _dbus_verify_daemon_user(const char *user)
Verify that after the fork we can successfully change to this user.
void * dbus_malloc(size_t bytes)
Allocates the given number of bytes, as with standard malloc().
DIR * d
The DIR* from opendir()
unsigned long mode
File mode.
dbus_bool_t _dbus_string_append_printf(DBusString *str, const char *format,...)
Appends a printf-style formatted string to the DBusString.
dbus_bool_t _dbus_get_group_id(const DBusString *groupname, dbus_gid_t *gid)
Gets group ID given groupname.
dbus_bool_t _dbus_unix_user_is_at_console(dbus_uid_t uid, DBusError *error)
Checks to see if the UNIX user ID is at the console.
unsigned long dbus_pid_t
A process ID.
dbus_bool_t _dbus_split_paths_and_append(DBusString *dirs, const char *suffix, DBusList **dir_list)
Split paths into a list of char strings.
unsigned long dbus_uid_t
A user ID.
#define FALSE
Expands to "0".
#define DBUS_ERROR_NO_MEMORY
There was not enough memory to complete an operation.
unsigned long nlink
Number of hard links.
dbus_bool_t _dbus_parse_unix_group_from_config(const DBusString *groupname, dbus_gid_t *gid_p)
Parse a UNIX group from the bus config file.
const char * _dbus_getenv(const char *varname)
Wrapper for getenv().
dbus_bool_t _dbus_is_console_user(dbus_uid_t uid, DBusError *error)
Checks to see if the UID sent in is the console user.
dbus_bool_t _dbus_directory_get_next_file(DBusDirIter *iter, DBusString *filename, DBusError *error)
Get next file in the directory.
void _dbus_fd_set_close_on_exec(int fd)
Sets the file descriptor to be close on exec.
dbus_bool_t _dbus_file_exists(const char *file)
Checks if a file exists.
dbus_bool_t dbus_error_is_set(const DBusError *error)
Checks whether an error occurred (the error is set).
#define _dbus_assert_not_reached(explanation)
Aborts with an error message if called.
dbus_bool_t _dbus_string_set_length(DBusString *str, int length)
Sets the length of a string.
unsigned long mtime
Modify time.
dbus_gid_t gid
Group owning file.
dbus_bool_t _dbus_command_for_pid(unsigned long pid, DBusString *str, int max_len, DBusError *error)
Get a printable string describing the command used to execute the process with pid.
#define _dbus_assert(condition)
Aborts with an error message if the condition is false.
dbus_bool_t _dbus_close(int fd, DBusError *error)
Closes a file descriptor.
dbus_bool_t _dbus_get_standard_session_servicedirs(DBusList **dirs)
Returns the standard directories for a session bus to look for service activation files.
void _dbus_warn(const char *format,...)
Prints a warning message to stderr.
dbus_uid_t _dbus_geteuid(void)
Gets our effective UID.
char * _dbus_strdup(const char *str)
Duplicates a string.
void _dbus_set_signal_handler(int sig, DBusSignalHandler handler)
Installs a UNIX signal handler.
dbus_bool_t _dbus_unix_groups_from_uid(dbus_uid_t uid, dbus_gid_t **group_ids, int *n_group_ids)
Gets all groups corresponding to the given UNIX user ID.
void(* DBusSignalHandler)(int sig)
A UNIX signal handler.
Object representing an exception.
DBusDirIter * _dbus_directory_open(const DBusString *filename, DBusError *error)
Open a directory to iterate over.
dbus_bool_t _dbus_ensure_directory(const DBusString *filename, DBusError *error)
Creates a directory; succeeds if the directory is created or already existed.
dbus_bool_t _dbus_become_daemon(const DBusString *pidfile, DBusPipe *print_pid_pipe, DBusError *error, dbus_bool_t keep_umask)
Does the chdir, fork, setsid, etc.
void dbus_set_error(DBusError *error, const char *name, const char *format,...)
Assigns an error name and message to a DBusError.
dbus_bool_t _dbus_string_steal_data(DBusString *str, char **data_return)
Like _dbus_string_get_data(), but removes the gotten data from the original string.
dbus_bool_t _dbus_parse_unix_user_from_config(const DBusString *username, dbus_uid_t *uid_p)
Parse a UNIX user from the bus config file.
const char * message
public error message field
Internals of directory iterator.
#define DBUS_GID_UNSET
an invalid GID used to represent an uninitialized dbus_gid_t field
dbus_bool_t _dbus_get_user_id(const DBusString *username, dbus_uid_t *uid)
Gets user ID given username.
dbus_bool_t _dbus_write_pid_to_file_and_pipe(const DBusString *pidfile, DBusPipe *print_pid_pipe, dbus_pid_t pid_to_write, DBusError *error)
Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a pipe (if non-NULL).
void _dbus_string_init_const(DBusString *str, const char *value)
Initializes a constant string.
dbus_bool_t _dbus_string_copy_len(const DBusString *source, int start, int len, DBusString *dest, int insert_at)
Like _dbus_string_copy(), but can copy a segment from the middle of the source string.
#define dbus_new0(type, count)
Safe macro for using dbus_malloc0().
#define DBUS_ERROR_NOT_SUPPORTED
Requested operation isn't supported (like ENOSYS on UNIX).
dbus_bool_t _dbus_homedir_from_current_process(const DBusString **homedir)
Gets homedir of user owning current process.
dbus_bool_t _dbus_string_append(DBusString *str, const char *buffer)
Appends a nul-terminated C-style string to a DBusString.
char * groupname
Group name.
dbus_bool_t _dbus_windows_user_is_process_owner(const char *windows_sid)
Checks to see if the Windows user SID matches the owner of the process.
unsigned long size
Size of file.
dbus_uint32_t dbus_bool_t
A boolean, valid values are TRUE and FALSE.
#define NULL
A null pointer, defined appropriately for C or C++.