1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps-util-unix.c Would be in dbus-sysdeps-unix.c, but not used in libdbus
4 * Copyright (C) 2002, 2003, 2004, 2005 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program 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
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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>
67 * @addtogroup DBusInternalsUtils
73 * Does the chdir, fork, setsid, etc. to become a daemon process.
75 * @param pidfile #NULL, or pidfile to create
76 * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
77 * @param error return location for errors
78 * @param keep_umask #TRUE to keep the original umask
79 * @returns #FALSE on failure
82 _dbus_become_daemon (const DBusString *pidfile,
83 DBusPipe *print_pid_pipe,
85 dbus_bool_t keep_umask)
89 DBusEnsureStandardFdsFlags flags;
91 _dbus_verbose ("Becoming a daemon...\n");
93 _dbus_verbose ("chdir to /\n");
96 dbus_set_error (error, DBUS_ERROR_FAILED,
97 "Could not chdir() to root directory");
101 _dbus_verbose ("forking...\n");
102 switch ((child_pid = fork ()))
105 _dbus_verbose ("fork failed\n");
106 dbus_set_error (error, _dbus_error_from_errno (errno),
107 "Failed to fork daemon: %s", _dbus_strerror (errno));
112 _dbus_verbose ("in child, closing std file descriptors\n");
114 flags = DBUS_FORCE_STDIN_NULL | DBUS_FORCE_STDOUT_NULL;
115 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
117 if (s == NULL || *s == '\0')
118 flags |= DBUS_FORCE_STDERR_NULL;
120 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
122 if (!_dbus_ensure_standard_fds (flags, &s))
124 _dbus_warn ("%s: %s", s, _dbus_strerror (errno));
130 /* Get a predictable umask */
131 _dbus_verbose ("setting umask\n");
135 _dbus_verbose ("calling setsid()\n");
137 _dbus_assert_not_reached ("setsid() failed");
142 if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
145 _dbus_verbose ("pid file or pipe write failed: %s\n",
147 kill (child_pid, SIGTERM);
151 _dbus_verbose ("parent exiting\n");
161 * Creates a file containing the process ID.
163 * @param filename the filename to write to
164 * @param pid our process ID
165 * @param error return location for errors
166 * @returns #FALSE on failure
169 _dbus_write_pid_file (const DBusString *filename,
173 const char *cfilename;
177 cfilename = _dbus_string_get_const_data (filename);
179 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
183 dbus_set_error (error, _dbus_error_from_errno (errno),
184 "Failed to open \"%s\": %s", cfilename,
185 _dbus_strerror (errno));
189 if ((f = fdopen (fd, "w")) == NULL)
191 dbus_set_error (error, _dbus_error_from_errno (errno),
192 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
193 _dbus_close (fd, NULL);
197 if (fprintf (f, "%lu\n", pid) < 0)
199 dbus_set_error (error, _dbus_error_from_errno (errno),
200 "Failed to write to \"%s\": %s", cfilename,
201 _dbus_strerror (errno));
207 if (fclose (f) == EOF)
209 dbus_set_error (error, _dbus_error_from_errno (errno),
210 "Failed to close \"%s\": %s", cfilename,
211 _dbus_strerror (errno));
219 * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
220 * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
223 * @param pidfile the file to write to or #NULL
224 * @param print_pid_pipe the pipe to write to or #NULL
225 * @param pid_to_write the pid to write out
226 * @param error error on failure
227 * @returns FALSE if error is set
230 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
231 DBusPipe *print_pid_pipe,
232 dbus_pid_t pid_to_write,
237 _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
238 if (!_dbus_write_pid_file (pidfile,
242 _dbus_verbose ("pid file write failed\n");
243 _DBUS_ASSERT_ERROR_IS_SET(error);
249 _dbus_verbose ("No pid file requested\n");
252 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
257 _dbus_verbose ("writing our pid to pipe %d\n",
260 if (!_dbus_string_init (&pid))
262 _DBUS_SET_OOM (error);
266 if (!_dbus_string_append_int (&pid, pid_to_write) ||
267 !_dbus_string_append (&pid, "\n"))
269 _dbus_string_free (&pid);
270 _DBUS_SET_OOM (error);
274 bytes = _dbus_string_get_length (&pid);
275 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
277 /* _dbus_pipe_write sets error only on failure, not short write */
278 if (error != NULL && !dbus_error_is_set(error))
280 dbus_set_error (error, DBUS_ERROR_FAILED,
281 "Printing message bus PID: did not write enough bytes\n");
283 _dbus_string_free (&pid);
287 _dbus_string_free (&pid);
291 _dbus_verbose ("No pid pipe to write to\n");
298 * Verify that after the fork we can successfully change to this user.
300 * @param user the username given in the daemon configuration
301 * @returns #TRUE if username is valid
304 _dbus_verify_daemon_user (const char *user)
308 _dbus_string_init_const (&u, user);
310 return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
314 /* The HAVE_LIBAUDIT case lives in selinux.c */
315 #ifndef HAVE_LIBAUDIT
317 * Changes the user and group the bus is running as.
319 * @param user the user to become
320 * @param error return location for errors
321 * @returns #FALSE on failure
324 _dbus_change_to_daemon_user (const char *user,
331 _dbus_string_init_const (&u, user);
333 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
335 dbus_set_error (error, DBUS_ERROR_FAILED,
336 "User '%s' does not appear to exist?",
341 /* setgroups() only works if we are a privileged process,
342 * so we don't return error on failure; the only possible
343 * failure is that we don't have perms to do it.
345 * not sure this is right, maybe if setuid()
346 * is going to work then setgroups() should also work.
348 if (setgroups (0, NULL) < 0)
349 _dbus_warn ("Failed to drop supplementary groups: %s",
350 _dbus_strerror (errno));
352 /* Set GID first, or the setuid may remove our permission
355 if (setgid (gid) < 0)
357 dbus_set_error (error, _dbus_error_from_errno (errno),
358 "Failed to set GID to %lu: %s", gid,
359 _dbus_strerror (errno));
363 if (setuid (uid) < 0)
365 dbus_set_error (error, _dbus_error_from_errno (errno),
366 "Failed to set UID to %lu: %s", uid,
367 _dbus_strerror (errno));
373 #endif /* !HAVE_LIBAUDIT */
375 #ifdef HAVE_SETRLIMIT
377 /* We assume that if we have setrlimit, we also have getrlimit and
386 _dbus_rlimit_save_fd_limit (DBusError *error)
390 self = dbus_new0 (DBusRLimit, 1);
394 _DBUS_SET_OOM (error);
398 if (getrlimit (RLIMIT_NOFILE, &self->lim) < 0)
400 dbus_set_error (error, _dbus_error_from_errno (errno),
401 "Failed to get fd limit: %s", _dbus_strerror (errno));
410 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int desired,
415 /* No point to doing this practically speaking
416 * if we're not uid 0. We expect the system
417 * bus to use this before we change UID, and
418 * the session bus takes the Linux default,
419 * currently 1024 for cur and 4096 for max.
423 /* not an error, we're probably the session bus */
427 if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
429 dbus_set_error (error, _dbus_error_from_errno (errno),
430 "Failed to get fd limit: %s", _dbus_strerror (errno));
434 if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= desired)
436 /* not an error, everything is fine */
440 /* Ignore "maximum limit", assume we have the "superuser"
441 * privileges. On Linux this is CAP_SYS_RESOURCE.
443 lim.rlim_cur = lim.rlim_max = desired;
445 if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
447 dbus_set_error (error, _dbus_error_from_errno (errno),
448 "Failed to set fd limit to %u: %s",
449 desired, _dbus_strerror (errno));
457 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
460 if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
462 dbus_set_error (error, _dbus_error_from_errno (errno),
463 "Failed to restore old fd limit: %s",
464 _dbus_strerror (errno));
471 #else /* !HAVE_SETRLIMIT */
474 fd_limit_not_supported (DBusError *error)
476 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
477 "cannot change fd limit on this platform");
481 _dbus_rlimit_save_fd_limit (DBusError *error)
483 fd_limit_not_supported (error);
488 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int desired,
491 fd_limit_not_supported (error);
496 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
499 fd_limit_not_supported (error);
506 _dbus_rlimit_free (DBusRLimit *lim)
511 /** Installs a UNIX signal handler
513 * @param sig the signal to handle
514 * @param handler the handler
517 _dbus_set_signal_handler (int sig,
518 DBusSignalHandler handler)
520 struct sigaction act;
523 sigemptyset (&empty_mask);
524 act.sa_handler = handler;
525 act.sa_mask = empty_mask;
527 sigaction (sig, &act, NULL);
530 /** Checks if a file exists
532 * @param file full path to the file
533 * @returns #TRUE if file exists
536 _dbus_file_exists (const char *file)
538 return (access (file, F_OK) == 0);
541 /** Checks if user is at the console
543 * @param username user to check
544 * @param error return location for errors
545 * @returns #TRUE is the user is at the consolei and there are no errors
548 _dbus_user_at_console (const char *username,
556 if (!_dbus_string_init (&f))
558 _DBUS_SET_OOM (error);
562 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
564 _DBUS_SET_OOM (error);
568 _dbus_string_init_const (&u, username);
570 if (!_dbus_concat_dir_and_file (&f, &u))
572 _DBUS_SET_OOM (error);
576 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
579 _dbus_string_free (&f);
586 * Checks whether the filename is an absolute path
588 * @param filename the filename
589 * @returns #TRUE if an absolute path
592 _dbus_path_is_absolute (const DBusString *filename)
594 if (_dbus_string_get_length (filename) > 0)
595 return _dbus_string_get_byte (filename, 0) == '/';
603 * @param filename the filename to stat
604 * @param statbuf the stat info to fill in
605 * @param error return location for error
606 * @returns #FALSE if error was set
609 _dbus_stat (const DBusString *filename,
613 const char *filename_c;
616 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
618 filename_c = _dbus_string_get_const_data (filename);
620 if (stat (filename_c, &sb) < 0)
622 dbus_set_error (error, _dbus_error_from_errno (errno),
623 "%s", _dbus_strerror (errno));
627 statbuf->mode = sb.st_mode;
628 statbuf->nlink = sb.st_nlink;
629 statbuf->uid = sb.st_uid;
630 statbuf->gid = sb.st_gid;
631 statbuf->size = sb.st_size;
632 statbuf->atime = sb.st_atime;
633 statbuf->mtime = sb.st_mtime;
634 statbuf->ctime = sb.st_ctime;
641 * Internals of directory iterator
645 DIR *d; /**< The DIR* from opendir() */
650 * Open a directory to iterate over.
652 * @param filename the directory name
653 * @param error exception return object or #NULL
654 * @returns new iterator, or #NULL on error
657 _dbus_directory_open (const DBusString *filename,
662 const char *filename_c;
664 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
666 filename_c = _dbus_string_get_const_data (filename);
668 d = opendir (filename_c);
671 dbus_set_error (error, _dbus_error_from_errno (errno),
672 "Failed to read directory \"%s\": %s",
674 _dbus_strerror (errno));
677 iter = dbus_new0 (DBusDirIter, 1);
681 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
682 "Could not allocate memory for directory iterator");
692 * Get next file in the directory. Will not return "." or ".." on
693 * UNIX. If an error occurs, the contents of "filename" are
694 * undefined. The error is never set if the function succeeds.
696 * This function is not re-entrant, and not necessarily thread-safe.
697 * Only use it for test code or single-threaded utilities.
699 * @param iter the iterator
700 * @param filename string to be set to the next file in the dir
701 * @param error return location for error
702 * @returns #TRUE if filename was filled in with a new filename
705 _dbus_directory_get_next_file (DBusDirIter *iter,
706 DBusString *filename,
712 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
716 ent = readdir (iter->d);
723 dbus_set_error (error,
724 _dbus_error_from_errno (err),
725 "%s", _dbus_strerror (err));
729 else if (ent->d_name[0] == '.' &&
730 (ent->d_name[1] == '\0' ||
731 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
735 _dbus_string_set_length (filename, 0);
736 if (!_dbus_string_append (filename, ent->d_name))
738 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
739 "No memory to read directory entry");
750 * Closes a directory iteration.
753 _dbus_directory_close (DBusDirIter *iter)
760 fill_user_info_from_group (struct group *g,
764 _dbus_assert (g->gr_name != NULL);
766 info->gid = g->gr_gid;
767 info->groupname = _dbus_strdup (g->gr_name);
769 /* info->members = dbus_strdupv (g->gr_mem) */
771 if (info->groupname == NULL)
773 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
781 fill_group_info (DBusGroupInfo *info,
783 const DBusString *groupname,
786 const char *group_c_str;
788 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
789 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
792 group_c_str = _dbus_string_get_const_data (groupname);
796 /* For now assuming that the getgrnam() and getgrgid() flavors
797 * always correspond to the pwnam flavors, if not we have
798 * to add more configure checks.
801 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
810 /* retrieve maximum needed size for buf */
811 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
813 /* sysconf actually returns a long, but everything else expects size_t,
814 * so just recast here.
815 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
817 if ((long) buflen <= 0)
823 buf = dbus_malloc (buflen);
826 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
831 #ifdef HAVE_POSIX_GETPWNAM_R
833 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
836 result = getgrgid_r (gid, &g_str, buf, buflen,
839 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
841 #endif /* !HAVE_POSIX_GETPWNAM_R */
842 /* Try a bigger buffer if ERANGE was returned:
843 https://bugs.freedesktop.org/show_bug.cgi?id=16727
845 if (result == ERANGE && buflen < 512 * 1024)
856 if (result == 0 && g == &g_str)
858 b = fill_user_info_from_group (g, info, error);
864 dbus_set_error (error, _dbus_error_from_errno (errno),
865 "Group %s unknown or failed to look it up\n",
866 group_c_str ? group_c_str : "???");
871 #else /* ! HAVE_GETPWNAM_R */
873 /* I guess we're screwed on thread safety here */
876 g = getgrnam (group_c_str);
880 return fill_user_info_from_group (g, info, error);
884 dbus_set_error (error, _dbus_error_from_errno (errno),
885 "Group %s unknown or failed to look it up\n",
886 group_c_str ? group_c_str : "???");
890 #endif /* ! HAVE_GETPWNAM_R */
894 * Initializes the given DBusGroupInfo struct
895 * with information about the given group name.
897 * @param info the group info struct
898 * @param groupname name of group
899 * @param error the error return
900 * @returns #FALSE if error is set
903 _dbus_group_info_fill (DBusGroupInfo *info,
904 const DBusString *groupname,
907 return fill_group_info (info, DBUS_GID_UNSET,
913 * Initializes the given DBusGroupInfo struct
914 * with information about the given group ID.
916 * @param info the group info struct
917 * @param gid group ID
918 * @param error the error return
919 * @returns #FALSE if error is set
922 _dbus_group_info_fill_gid (DBusGroupInfo *info,
926 return fill_group_info (info, gid, NULL, error);
930 * Parse a UNIX user from the bus config file. On Windows, this should
931 * simply always fail (just return #FALSE).
933 * @param username the username text
934 * @param uid_p place to return the uid
935 * @returns #TRUE on success
938 _dbus_parse_unix_user_from_config (const DBusString *username,
941 return _dbus_get_user_id (username, uid_p);
946 * Parse a UNIX group from the bus config file. On Windows, this should
947 * simply always fail (just return #FALSE).
949 * @param groupname the groupname text
950 * @param gid_p place to return the gid
951 * @returns #TRUE on success
954 _dbus_parse_unix_group_from_config (const DBusString *groupname,
957 return _dbus_get_group_id (groupname, gid_p);
961 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
962 * just calls _dbus_groups_from_uid(). On Windows, should always
963 * fail since we don't know any UNIX groups.
966 * @param group_ids return location for array of group IDs
967 * @param n_group_ids return location for length of returned array
968 * @returns #TRUE if the UID existed and we got some credentials
971 _dbus_unix_groups_from_uid (dbus_uid_t uid,
972 dbus_gid_t **group_ids,
975 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
979 * Checks to see if the UNIX user ID is at the console.
980 * Should always fail on Windows (set the error to
981 * #DBUS_ERROR_NOT_SUPPORTED).
983 * @param uid UID of person to check
984 * @param error return location for errors
985 * @returns #TRUE if the UID is the same as the console user and there are no errors
988 _dbus_unix_user_is_at_console (dbus_uid_t uid,
991 return _dbus_is_console_user (uid, error);
996 * Checks to see if the UNIX user ID matches the UID of
997 * the process. Should always return #FALSE on Windows.
999 * @param uid the UNIX user ID
1000 * @returns #TRUE if this uid owns the process.
1003 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1005 return uid == _dbus_geteuid ();
1009 * Checks to see if the Windows user SID matches the owner of
1010 * the process. Should always return #FALSE on UNIX.
1012 * @param windows_sid the Windows user SID
1013 * @returns #TRUE if this user owns the process.
1016 _dbus_windows_user_is_process_owner (const char *windows_sid)
1021 /** @} */ /* End of DBusInternalsUtils functions */
1024 * @addtogroup DBusString
1029 * Get the directory name from a complete filename
1030 * @param filename the filename
1031 * @param dirname string to append directory name to
1032 * @returns #FALSE if no memory
1035 _dbus_string_get_dirname (const DBusString *filename,
1036 DBusString *dirname)
1040 _dbus_assert (filename != dirname);
1041 _dbus_assert (filename != NULL);
1042 _dbus_assert (dirname != NULL);
1044 /* Ignore any separators on the end */
1045 sep = _dbus_string_get_length (filename);
1047 return _dbus_string_append (dirname, "."); /* empty string passed in */
1049 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1052 _dbus_assert (sep >= 0);
1055 return _dbus_string_append (dirname, "/");
1057 /* Now find the previous separator */
1058 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1060 return _dbus_string_append (dirname, ".");
1062 /* skip multiple separators */
1063 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1066 _dbus_assert (sep >= 0);
1069 _dbus_string_get_byte (filename, 0) == '/')
1070 return _dbus_string_append (dirname, "/");
1072 return _dbus_string_copy_len (filename, 0, sep - 0,
1073 dirname, _dbus_string_get_length (dirname));
1075 /** @} */ /* DBusString stuff */
1078 string_squash_nonprintable (DBusString *str)
1083 buf = _dbus_string_get_udata (str);
1084 len = _dbus_string_get_length (str);
1086 for (i = 0; i < len; i++)
1088 unsigned char c = (unsigned char) buf[i];
1091 else if (c < 0x20 || c > 127)
1097 * Get a printable string describing the command used to execute
1098 * the process with pid. This string should only be used for
1099 * informative purposes such as logging; it may not be trusted.
1101 * The command is guaranteed to be printable ASCII and no longer
1104 * @param pid Process id
1105 * @param str Append command to this string
1106 * @param max_len Maximum length of returned command
1107 * @param error return location for errors
1108 * @returns #FALSE on error
1111 _dbus_command_for_pid (unsigned long pid,
1116 /* This is all Linux-specific for now */
1121 if (!_dbus_string_init (&path))
1123 _DBUS_SET_OOM (error);
1127 if (!_dbus_string_init (&cmdline))
1129 _DBUS_SET_OOM (error);
1130 _dbus_string_free (&path);
1134 if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1137 fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1140 dbus_set_error (error,
1141 _dbus_error_from_errno (errno),
1142 "Failed to open \"%s\": %s",
1143 _dbus_string_get_const_data (&path),
1144 _dbus_strerror (errno));
1148 if (!_dbus_read (fd, &cmdline, max_len))
1150 dbus_set_error (error,
1151 _dbus_error_from_errno (errno),
1152 "Failed to read from \"%s\": %s",
1153 _dbus_string_get_const_data (&path),
1154 _dbus_strerror (errno));
1155 _dbus_close (fd, NULL);
1159 if (!_dbus_close (fd, error))
1162 string_squash_nonprintable (&cmdline);
1164 if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1167 _dbus_string_free (&cmdline);
1168 _dbus_string_free (&path);
1171 _DBUS_SET_OOM (error);
1173 _dbus_string_free (&cmdline);
1174 _dbus_string_free (&path);
1179 * Replace the DBUS_PREFIX in the given path, in-place, by the
1180 * current D-Bus installation directory. On Unix this function
1181 * does nothing, successfully.
1183 * @param path path to edit
1184 * @return #FALSE on OOM
1187 _dbus_replace_install_prefix (DBusString *path)
1193 ensure_owned_directory (const char *label,
1194 const DBusString *string,
1198 const char *dir = _dbus_string_get_const_data (string);
1201 if (create && !_dbus_ensure_directory (string, error))
1205 * The stat()-based checks in this function are to protect against
1206 * mistakes, not malice. We are working in a directory that is meant
1207 * to be trusted; but if a user has used `su` or similar to escalate
1208 * their privileges without correctly clearing the environment, the
1209 * XDG_RUNTIME_DIR in the environment might still be the user's
1210 * and not root's. We don't want to write root-owned files into that
1211 * directory, so just warn and don't provide support for transient
1212 * services in that case.
1214 * In particular, we use stat() and not lstat() so that if we later
1215 * decide to use a different directory name for transient services,
1216 * we can drop in a compatibility symlink without breaking older
1220 if (stat (dir, &buf) != 0)
1222 int saved_errno = errno;
1224 dbus_set_error (error, _dbus_error_from_errno (saved_errno),
1225 "%s \"%s\" not available: %s", label, dir,
1226 _dbus_strerror (saved_errno));
1230 if (!S_ISDIR (buf.st_mode))
1232 dbus_set_error (error, DBUS_ERROR_FAILED, "%s \"%s\" is not a directory",
1237 if (buf.st_uid != geteuid ())
1239 dbus_set_error (error, DBUS_ERROR_FAILED,
1240 "%s \"%s\" is owned by uid %ld, not our uid %ld",
1241 label, dir, (long) buf.st_uid, (long) geteuid ());
1245 /* This is just because we have the stat() results already, so we might
1246 * as well check opportunistically. */
1247 if ((S_IWOTH | S_IWGRP) & buf.st_mode)
1249 dbus_set_error (error, DBUS_ERROR_FAILED,
1250 "%s \"%s\" can be written by others (mode 0%o)",
1251 label, dir, buf.st_mode);
1258 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
1259 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
1262 * Returns the standard directories for a session bus to look for
1263 * transient service activation files.
1265 * @param dirs the directory list we are returning
1266 * @returns #FALSE on error
1269 _dbus_set_up_transient_session_servicedirs (DBusList **dirs,
1272 const char *xdg_runtime_dir;
1273 DBusString services;
1276 dbus_bool_t ret = FALSE;
1279 if (!_dbus_string_init (&dbus1))
1281 _DBUS_SET_OOM (error);
1285 if (!_dbus_string_init (&services))
1287 _dbus_string_free (&dbus1);
1288 _DBUS_SET_OOM (error);
1292 if (!_dbus_string_init (&xrd))
1294 _dbus_string_free (&dbus1);
1295 _dbus_string_free (&services);
1296 _DBUS_SET_OOM (error);
1300 xdg_runtime_dir = _dbus_getenv ("XDG_RUNTIME_DIR");
1302 /* Not an error, we just can't have transient session services */
1303 if (xdg_runtime_dir == NULL)
1305 _dbus_verbose ("XDG_RUNTIME_DIR is unset: transient session services "
1306 "not available here\n");
1311 if (!_dbus_string_append (&xrd, xdg_runtime_dir) ||
1312 !_dbus_string_append_printf (&dbus1, "%s/dbus-1",
1314 !_dbus_string_append_printf (&services, "%s/dbus-1/services",
1317 _DBUS_SET_OOM (error);
1321 if (!ensure_owned_directory ("XDG_RUNTIME_DIR", &xrd, FALSE, error) ||
1322 !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &dbus1, TRUE,
1324 !ensure_owned_directory ("XDG_RUNTIME_DIR subdirectory", &services,
1328 if (!_dbus_string_steal_data (&services, &data) ||
1329 !_dbus_list_append (dirs, data))
1331 _DBUS_SET_OOM (error);
1335 _dbus_verbose ("Transient service directory is %s\n", data);
1336 /* Ownership was transferred to @dirs */
1341 _dbus_string_free (&dbus1);
1342 _dbus_string_free (&services);
1343 _dbus_string_free (&xrd);
1349 * Returns the standard directories for a session bus to look for service
1352 * On UNIX this should be the standard xdg freedesktop.org data directories:
1354 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
1355 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1361 * @param dirs the directory list we are returning
1362 * @returns #FALSE on OOM
1366 _dbus_get_standard_session_servicedirs (DBusList **dirs)
1368 const char *xdg_data_home;
1369 const char *xdg_data_dirs;
1370 DBusString servicedir_path;
1372 if (!_dbus_string_init (&servicedir_path))
1375 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
1376 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
1378 if (xdg_data_home != NULL)
1380 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
1385 const DBusString *homedir;
1386 DBusString local_share;
1388 if (!_dbus_homedir_from_current_process (&homedir))
1391 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
1394 _dbus_string_init_const (&local_share, "/.local/share");
1395 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
1399 if (!_dbus_string_append (&servicedir_path, ":"))
1402 if (xdg_data_dirs != NULL)
1404 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
1407 if (!_dbus_string_append (&servicedir_path, ":"))
1412 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
1417 * add configured datadir to defaults
1418 * this may be the same as an xdg dir
1419 * however the config parser should take
1420 * care of duplicates
1422 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
1425 if (!_dbus_split_paths_and_append (&servicedir_path,
1426 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
1430 _dbus_string_free (&servicedir_path);
1434 _dbus_string_free (&servicedir_path);
1440 * Returns the standard directories for a system bus to look for service
1443 * On UNIX this should be the standard xdg freedesktop.org data directories:
1445 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1451 * On Windows there is no system bus and this function can return nothing.
1453 * @param dirs the directory list we are returning
1454 * @returns #FALSE on OOM
1458 _dbus_get_standard_system_servicedirs (DBusList **dirs)
1461 * DBUS_DATADIR may be the same as one of the standard directories. However,
1462 * the config parser should take care of the duplicates.
1464 * Also, append /lib as counterpart of /usr/share on the root
1465 * directory (the root directory does not know /share), in order to
1466 * facilitate early boot system bus activation where /usr might not
1469 static const char standard_search_path[] =
1474 DBusString servicedir_path;
1476 _dbus_string_init_const (&servicedir_path, standard_search_path);
1478 return _dbus_split_paths_and_append (&servicedir_path,
1479 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
1484 * Get the absolute path of the system.conf file
1485 * (there is no system bus on Windows so this can just
1486 * return FALSE and print a warning or something)
1488 * @param str the string to append to, which must be empty on entry
1489 * @returns #FALSE if no memory
1492 _dbus_get_system_config_file (DBusString *str)
1494 _dbus_assert (_dbus_string_get_length (str) == 0);
1496 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
1500 * Get the absolute path of the session.conf file.
1502 * @param str the string to append to, which must be empty on entry
1503 * @returns #FALSE if no memory
1506 _dbus_get_session_config_file (DBusString *str)
1508 _dbus_assert (_dbus_string_get_length (str) == 0);
1510 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);