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-pipe.h"
30 #include "dbus-protocol.h"
31 #include "dbus-string.h"
32 #define DBUS_USERDB_INCLUDES_PRIVATE 1
33 #include "dbus-userdb.h"
34 #include "dbus-test.h"
36 #include <sys/types.h>
45 #ifdef HAVE_SYS_RESOURCE_H
46 #include <sys/resource.h>
49 #include <sys/socket.h>
57 #ifdef HAVE_SYS_SYSLIMITS_H
58 #include <sys/syslimits.h>
62 #include <systemd/sd-daemon.h>
70 * @addtogroup DBusInternalsUtils
76 * Does the chdir, fork, setsid, etc. to become a daemon process.
78 * @param pidfile #NULL, or pidfile to create
79 * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
80 * @param error return location for errors
81 * @param keep_umask #TRUE to keep the original umask
82 * @returns #FALSE on failure
85 _dbus_become_daemon (const DBusString *pidfile,
86 DBusPipe *print_pid_pipe,
88 dbus_bool_t keep_umask)
94 _dbus_verbose ("Becoming a daemon...\n");
96 _dbus_verbose ("chdir to /\n");
99 dbus_set_error (error, DBUS_ERROR_FAILED,
100 "Could not chdir() to root directory");
104 _dbus_verbose ("forking...\n");
105 switch ((child_pid = fork ()))
108 _dbus_verbose ("fork failed\n");
109 dbus_set_error (error, _dbus_error_from_errno (errno),
110 "Failed to fork daemon: %s", _dbus_strerror (errno));
115 _dbus_verbose ("in child, closing std file descriptors\n");
117 /* silently ignore failures here, if someone
118 * doesn't have /dev/null we may as well try
122 dev_null_fd = open ("/dev/null", O_RDWR);
123 if (dev_null_fd >= 0)
125 dup2 (dev_null_fd, 0);
126 dup2 (dev_null_fd, 1);
128 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
129 if (s == NULL || *s == '\0')
130 dup2 (dev_null_fd, 2);
132 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
138 /* Get a predictable umask */
139 _dbus_verbose ("setting umask\n");
143 _dbus_verbose ("calling setsid()\n");
145 _dbus_assert_not_reached ("setsid() failed");
150 if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
153 _dbus_verbose ("pid file or pipe write failed: %s\n",
155 kill (child_pid, SIGTERM);
159 _dbus_verbose ("parent exiting\n");
169 * Creates a file containing the process ID.
171 * @param filename the filename to write to
172 * @param pid our process ID
173 * @param error return location for errors
174 * @returns #FALSE on failure
177 _dbus_write_pid_file (const DBusString *filename,
181 const char *cfilename;
185 cfilename = _dbus_string_get_const_data (filename);
187 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
191 dbus_set_error (error, _dbus_error_from_errno (errno),
192 "Failed to open \"%s\": %s", cfilename,
193 _dbus_strerror (errno));
197 if ((f = fdopen (fd, "w")) == NULL)
199 dbus_set_error (error, _dbus_error_from_errno (errno),
200 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
201 _dbus_close (fd, NULL);
205 if (fprintf (f, "%lu\n", pid) < 0)
207 dbus_set_error (error, _dbus_error_from_errno (errno),
208 "Failed to write to \"%s\": %s", cfilename,
209 _dbus_strerror (errno));
215 if (fclose (f) == EOF)
217 dbus_set_error (error, _dbus_error_from_errno (errno),
218 "Failed to close \"%s\": %s", cfilename,
219 _dbus_strerror (errno));
227 * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
228 * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
231 * @param pidfile the file to write to or #NULL
232 * @param print_pid_pipe the pipe to write to or #NULL
233 * @param pid_to_write the pid to write out
234 * @param error error on failure
235 * @returns FALSE if error is set
238 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
239 DBusPipe *print_pid_pipe,
240 dbus_pid_t pid_to_write,
245 _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
246 if (!_dbus_write_pid_file (pidfile,
250 _dbus_verbose ("pid file write failed\n");
251 _DBUS_ASSERT_ERROR_IS_SET(error);
257 _dbus_verbose ("No pid file requested\n");
260 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
265 _dbus_verbose ("writing our pid to pipe %d\n",
268 if (!_dbus_string_init (&pid))
270 _DBUS_SET_OOM (error);
274 if (!_dbus_string_append_int (&pid, pid_to_write) ||
275 !_dbus_string_append (&pid, "\n"))
277 _dbus_string_free (&pid);
278 _DBUS_SET_OOM (error);
282 bytes = _dbus_string_get_length (&pid);
283 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
285 /* _dbus_pipe_write sets error only on failure, not short write */
286 if (error != NULL && !dbus_error_is_set(error))
288 dbus_set_error (error, DBUS_ERROR_FAILED,
289 "Printing message bus PID: did not write enough bytes\n");
291 _dbus_string_free (&pid);
295 _dbus_string_free (&pid);
299 _dbus_verbose ("No pid pipe to write to\n");
306 * Verify that after the fork we can successfully change to this user.
308 * @param user the username given in the daemon configuration
309 * @returns #TRUE if username is valid
312 _dbus_verify_daemon_user (const char *user)
316 _dbus_string_init_const (&u, user);
318 return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
322 /* The HAVE_LIBAUDIT case lives in selinux.c */
323 #ifndef HAVE_LIBAUDIT
325 * Changes the user and group the bus is running as.
327 * @param user the user to become
328 * @param error return location for errors
329 * @returns #FALSE on failure
332 _dbus_change_to_daemon_user (const char *user,
339 _dbus_string_init_const (&u, user);
341 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
343 dbus_set_error (error, DBUS_ERROR_FAILED,
344 "User '%s' does not appear to exist?",
349 /* setgroups() only works if we are a privileged process,
350 * so we don't return error on failure; the only possible
351 * failure is that we don't have perms to do it.
353 * not sure this is right, maybe if setuid()
354 * is going to work then setgroups() should also work.
356 if (setgroups (0, NULL) < 0)
357 _dbus_warn ("Failed to drop supplementary groups: %s\n",
358 _dbus_strerror (errno));
360 /* Set GID first, or the setuid may remove our permission
363 if (setgid (gid) < 0)
365 dbus_set_error (error, _dbus_error_from_errno (errno),
366 "Failed to set GID to %lu: %s", gid,
367 _dbus_strerror (errno));
371 if (setuid (uid) < 0)
373 dbus_set_error (error, _dbus_error_from_errno (errno),
374 "Failed to set UID to %lu: %s", uid,
375 _dbus_strerror (errno));
381 #endif /* !HAVE_LIBAUDIT */
383 #ifdef HAVE_SETRLIMIT
385 /* We assume that if we have setrlimit, we also have getrlimit and
394 _dbus_rlimit_save_fd_limit (DBusError *error)
398 self = dbus_new0 (DBusRLimit, 1);
402 _DBUS_SET_OOM (error);
406 if (getrlimit (RLIMIT_NOFILE, &self->lim) < 0)
408 dbus_set_error (error, _dbus_error_from_errno (errno),
409 "Failed to get fd limit: %s", _dbus_strerror (errno));
418 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int desired,
423 /* No point to doing this practically speaking
424 * if we're not uid 0. We expect the system
425 * bus to use this before we change UID, and
426 * the session bus takes the Linux default,
427 * currently 1024 for cur and 4096 for max.
431 /* not an error, we're probably the session bus */
435 if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
437 dbus_set_error (error, _dbus_error_from_errno (errno),
438 "Failed to get fd limit: %s", _dbus_strerror (errno));
442 if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= desired)
444 /* not an error, everything is fine */
448 /* Ignore "maximum limit", assume we have the "superuser"
449 * privileges. On Linux this is CAP_SYS_RESOURCE.
451 lim.rlim_cur = lim.rlim_max = desired;
453 if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
455 dbus_set_error (error, _dbus_error_from_errno (errno),
456 "Failed to set fd limit to %u: %s",
457 desired, _dbus_strerror (errno));
465 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
468 if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
470 dbus_set_error (error, _dbus_error_from_errno (errno),
471 "Failed to restore old fd limit: %s",
472 _dbus_strerror (errno));
479 #else /* !HAVE_SETRLIMIT */
482 fd_limit_not_supported (DBusError *error)
484 dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
485 "cannot change fd limit on this platform");
489 _dbus_rlimit_save_fd_limit (DBusError *error)
491 fd_limit_not_supported (error);
496 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int desired,
499 fd_limit_not_supported (error);
504 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
507 fd_limit_not_supported (error);
514 _dbus_rlimit_free (DBusRLimit *lim)
520 _dbus_init_system_log (dbus_bool_t is_daemon)
523 int logopts = LOG_PID;
525 #if HAVE_DECL_LOG_PERROR
527 if (!is_daemon || sd_booted () <= 0)
529 logopts |= LOG_PERROR;
532 openlog ("dbus", logopts, LOG_DAEMON);
537 * Log a message to the system log file (e.g. syslog on Unix).
539 * @param severity a severity value
540 * @param msg a printf-style format string
543 _dbus_system_log (DBusSystemLogSeverity severity, const char *msg, ...)
547 va_start (args, msg);
549 _dbus_system_logv (severity, msg, args);
555 * Log a message to the system log file (e.g. syslog on Unix).
557 * @param severity a severity value
558 * @param msg a printf-style format string
559 * @param args arguments for the format string
561 * If the FATAL severity is given, this function will terminate the program
562 * with an error code.
565 _dbus_system_logv (DBusSystemLogSeverity severity, const char *msg, va_list args)
572 case DBUS_SYSTEM_LOG_INFO:
573 flags = LOG_DAEMON | LOG_NOTICE;
575 case DBUS_SYSTEM_LOG_WARNING:
576 flags = LOG_DAEMON | LOG_WARNING;
578 case DBUS_SYSTEM_LOG_SECURITY:
579 flags = LOG_AUTH | LOG_NOTICE;
581 case DBUS_SYSTEM_LOG_FATAL:
582 flags = LOG_DAEMON|LOG_CRIT;
588 DBUS_VA_COPY (tmp, args);
589 vsyslog (flags, msg, tmp);
593 #if !defined(HAVE_SYSLOG_H) || !HAVE_DECL_LOG_PERROR
595 /* vsyslog() won't write to stderr, so we'd better do it */
596 DBUS_VA_COPY (tmp, args);
597 fprintf (stderr, "dbus[" DBUS_PID_FORMAT "]: ", _dbus_getpid ());
598 vfprintf (stderr, msg, tmp);
599 fputc ('\n', stderr);
604 if (severity == DBUS_SYSTEM_LOG_FATAL)
608 /** Installs a UNIX signal handler
610 * @param sig the signal to handle
611 * @param handler the handler
614 _dbus_set_signal_handler (int sig,
615 DBusSignalHandler handler)
617 struct sigaction act;
620 sigemptyset (&empty_mask);
621 act.sa_handler = handler;
622 act.sa_mask = empty_mask;
624 sigaction (sig, &act, NULL);
627 /** Checks if a file exists
629 * @param file full path to the file
630 * @returns #TRUE if file exists
633 _dbus_file_exists (const char *file)
635 return (access (file, F_OK) == 0);
638 /** Checks if user is at the console
640 * @param username user to check
641 * @param error return location for errors
642 * @returns #TRUE is the user is at the consolei and there are no errors
645 _dbus_user_at_console (const char *username,
653 if (!_dbus_string_init (&f))
655 _DBUS_SET_OOM (error);
659 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
661 _DBUS_SET_OOM (error);
665 _dbus_string_init_const (&u, username);
667 if (!_dbus_concat_dir_and_file (&f, &u))
669 _DBUS_SET_OOM (error);
673 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
676 _dbus_string_free (&f);
683 * Checks whether the filename is an absolute path
685 * @param filename the filename
686 * @returns #TRUE if an absolute path
689 _dbus_path_is_absolute (const DBusString *filename)
691 if (_dbus_string_get_length (filename) > 0)
692 return _dbus_string_get_byte (filename, 0) == '/';
700 * @param filename the filename to stat
701 * @param statbuf the stat info to fill in
702 * @param error return location for error
703 * @returns #FALSE if error was set
706 _dbus_stat (const DBusString *filename,
710 const char *filename_c;
713 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
715 filename_c = _dbus_string_get_const_data (filename);
717 if (stat (filename_c, &sb) < 0)
719 dbus_set_error (error, _dbus_error_from_errno (errno),
720 "%s", _dbus_strerror (errno));
724 statbuf->mode = sb.st_mode;
725 statbuf->nlink = sb.st_nlink;
726 statbuf->uid = sb.st_uid;
727 statbuf->gid = sb.st_gid;
728 statbuf->size = sb.st_size;
729 statbuf->atime = sb.st_atime;
730 statbuf->mtime = sb.st_mtime;
731 statbuf->ctime = sb.st_ctime;
738 * Internals of directory iterator
742 DIR *d; /**< The DIR* from opendir() */
747 * Open a directory to iterate over.
749 * @param filename the directory name
750 * @param error exception return object or #NULL
751 * @returns new iterator, or #NULL on error
754 _dbus_directory_open (const DBusString *filename,
759 const char *filename_c;
761 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
763 filename_c = _dbus_string_get_const_data (filename);
765 d = opendir (filename_c);
768 dbus_set_error (error, _dbus_error_from_errno (errno),
769 "Failed to read directory \"%s\": %s",
771 _dbus_strerror (errno));
774 iter = dbus_new0 (DBusDirIter, 1);
778 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
779 "Could not allocate memory for directory iterator");
789 * Get next file in the directory. Will not return "." or ".." on
790 * UNIX. If an error occurs, the contents of "filename" are
791 * undefined. The error is never set if the function succeeds.
793 * This function is not re-entrant, and not necessarily thread-safe.
794 * Only use it for test code or single-threaded utilities.
796 * @param iter the iterator
797 * @param filename string to be set to the next file in the dir
798 * @param error return location for error
799 * @returns #TRUE if filename was filled in with a new filename
802 _dbus_directory_get_next_file (DBusDirIter *iter,
803 DBusString *filename,
809 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
813 ent = readdir (iter->d);
820 dbus_set_error (error,
821 _dbus_error_from_errno (err),
822 "%s", _dbus_strerror (err));
826 else if (ent->d_name[0] == '.' &&
827 (ent->d_name[1] == '\0' ||
828 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
832 _dbus_string_set_length (filename, 0);
833 if (!_dbus_string_append (filename, ent->d_name))
835 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
836 "No memory to read directory entry");
847 * Closes a directory iteration.
850 _dbus_directory_close (DBusDirIter *iter)
857 fill_user_info_from_group (struct group *g,
861 _dbus_assert (g->gr_name != NULL);
863 info->gid = g->gr_gid;
864 info->groupname = _dbus_strdup (g->gr_name);
866 /* info->members = dbus_strdupv (g->gr_mem) */
868 if (info->groupname == NULL)
870 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
878 fill_group_info (DBusGroupInfo *info,
880 const DBusString *groupname,
883 const char *group_c_str;
885 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
886 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
889 group_c_str = _dbus_string_get_const_data (groupname);
893 /* For now assuming that the getgrnam() and getgrgid() flavors
894 * always correspond to the pwnam flavors, if not we have
895 * to add more configure checks.
898 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
907 /* retrieve maximum needed size for buf */
908 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
910 /* sysconf actually returns a long, but everything else expects size_t,
911 * so just recast here.
912 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
914 if ((long) buflen <= 0)
920 buf = dbus_malloc (buflen);
923 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
928 #ifdef HAVE_POSIX_GETPWNAM_R
930 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
933 result = getgrgid_r (gid, &g_str, buf, buflen,
936 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
938 #endif /* !HAVE_POSIX_GETPWNAM_R */
939 /* Try a bigger buffer if ERANGE was returned:
940 https://bugs.freedesktop.org/show_bug.cgi?id=16727
942 if (result == ERANGE && buflen < 512 * 1024)
953 if (result == 0 && g == &g_str)
955 b = fill_user_info_from_group (g, info, error);
961 dbus_set_error (error, _dbus_error_from_errno (errno),
962 "Group %s unknown or failed to look it up\n",
963 group_c_str ? group_c_str : "???");
968 #else /* ! HAVE_GETPWNAM_R */
970 /* I guess we're screwed on thread safety here */
973 g = getgrnam (group_c_str);
977 return fill_user_info_from_group (g, info, error);
981 dbus_set_error (error, _dbus_error_from_errno (errno),
982 "Group %s unknown or failed to look it up\n",
983 group_c_str ? group_c_str : "???");
987 #endif /* ! HAVE_GETPWNAM_R */
991 * Initializes the given DBusGroupInfo struct
992 * with information about the given group name.
994 * @param info the group info struct
995 * @param groupname name of group
996 * @param error the error return
997 * @returns #FALSE if error is set
1000 _dbus_group_info_fill (DBusGroupInfo *info,
1001 const DBusString *groupname,
1004 return fill_group_info (info, DBUS_GID_UNSET,
1010 * Initializes the given DBusGroupInfo struct
1011 * with information about the given group ID.
1013 * @param info the group info struct
1014 * @param gid group ID
1015 * @param error the error return
1016 * @returns #FALSE if error is set
1019 _dbus_group_info_fill_gid (DBusGroupInfo *info,
1023 return fill_group_info (info, gid, NULL, error);
1027 * Parse a UNIX user from the bus config file. On Windows, this should
1028 * simply always fail (just return #FALSE).
1030 * @param username the username text
1031 * @param uid_p place to return the uid
1032 * @returns #TRUE on success
1035 _dbus_parse_unix_user_from_config (const DBusString *username,
1038 return _dbus_get_user_id (username, uid_p);
1043 * Parse a UNIX group from the bus config file. On Windows, this should
1044 * simply always fail (just return #FALSE).
1046 * @param groupname the groupname text
1047 * @param gid_p place to return the gid
1048 * @returns #TRUE on success
1051 _dbus_parse_unix_group_from_config (const DBusString *groupname,
1054 return _dbus_get_group_id (groupname, gid_p);
1058 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
1059 * just calls _dbus_groups_from_uid(). On Windows, should always
1060 * fail since we don't know any UNIX groups.
1062 * @param uid the UID
1063 * @param group_ids return location for array of group IDs
1064 * @param n_group_ids return location for length of returned array
1065 * @returns #TRUE if the UID existed and we got some credentials
1068 _dbus_unix_groups_from_uid (dbus_uid_t uid,
1069 dbus_gid_t **group_ids,
1072 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
1076 * Checks to see if the UNIX user ID is at the console.
1077 * Should always fail on Windows (set the error to
1078 * #DBUS_ERROR_NOT_SUPPORTED).
1080 * @param uid UID of person to check
1081 * @param error return location for errors
1082 * @returns #TRUE if the UID is the same as the console user and there are no errors
1085 _dbus_unix_user_is_at_console (dbus_uid_t uid,
1088 return _dbus_is_console_user (uid, error);
1093 * Checks to see if the UNIX user ID matches the UID of
1094 * the process. Should always return #FALSE on Windows.
1096 * @param uid the UNIX user ID
1097 * @returns #TRUE if this uid owns the process.
1100 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1102 return uid == _dbus_geteuid ();
1106 * Checks to see if the Windows user SID matches the owner of
1107 * the process. Should always return #FALSE on UNIX.
1109 * @param windows_sid the Windows user SID
1110 * @returns #TRUE if this user owns the process.
1113 _dbus_windows_user_is_process_owner (const char *windows_sid)
1118 /** @} */ /* End of DBusInternalsUtils functions */
1121 * @addtogroup DBusString
1126 * Get the directory name from a complete filename
1127 * @param filename the filename
1128 * @param dirname string to append directory name to
1129 * @returns #FALSE if no memory
1132 _dbus_string_get_dirname (const DBusString *filename,
1133 DBusString *dirname)
1137 _dbus_assert (filename != dirname);
1138 _dbus_assert (filename != NULL);
1139 _dbus_assert (dirname != NULL);
1141 /* Ignore any separators on the end */
1142 sep = _dbus_string_get_length (filename);
1144 return _dbus_string_append (dirname, "."); /* empty string passed in */
1146 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1149 _dbus_assert (sep >= 0);
1152 return _dbus_string_append (dirname, "/");
1154 /* Now find the previous separator */
1155 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1157 return _dbus_string_append (dirname, ".");
1159 /* skip multiple separators */
1160 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1163 _dbus_assert (sep >= 0);
1166 _dbus_string_get_byte (filename, 0) == '/')
1167 return _dbus_string_append (dirname, "/");
1169 return _dbus_string_copy_len (filename, 0, sep - 0,
1170 dirname, _dbus_string_get_length (dirname));
1172 /** @} */ /* DBusString stuff */
1175 string_squash_nonprintable (DBusString *str)
1180 buf = _dbus_string_get_data (str);
1181 len = _dbus_string_get_length (str);
1183 for (i = 0; i < len; i++)
1185 unsigned char c = (unsigned char) buf[i];
1188 else if (c < 0x20 || c > 127)
1194 * Get a printable string describing the command used to execute
1195 * the process with pid. This string should only be used for
1196 * informative purposes such as logging; it may not be trusted.
1198 * The command is guaranteed to be printable ASCII and no longer
1201 * @param pid Process id
1202 * @param str Append command to this string
1203 * @param max_len Maximum length of returned command
1204 * @param error return location for errors
1205 * @returns #FALSE on error
1208 _dbus_command_for_pid (unsigned long pid,
1213 /* This is all Linux-specific for now */
1218 if (!_dbus_string_init (&path))
1220 _DBUS_SET_OOM (error);
1224 if (!_dbus_string_init (&cmdline))
1226 _DBUS_SET_OOM (error);
1227 _dbus_string_free (&path);
1231 if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1234 fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1237 dbus_set_error (error,
1238 _dbus_error_from_errno (errno),
1239 "Failed to open \"%s\": %s",
1240 _dbus_string_get_const_data (&path),
1241 _dbus_strerror (errno));
1245 if (!_dbus_read (fd, &cmdline, max_len))
1247 dbus_set_error (error,
1248 _dbus_error_from_errno (errno),
1249 "Failed to read from \"%s\": %s",
1250 _dbus_string_get_const_data (&path),
1251 _dbus_strerror (errno));
1252 _dbus_close (fd, NULL);
1256 if (!_dbus_close (fd, error))
1259 string_squash_nonprintable (&cmdline);
1261 if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1264 _dbus_string_free (&cmdline);
1265 _dbus_string_free (&path);
1268 _DBUS_SET_OOM (error);
1270 _dbus_string_free (&cmdline);
1271 _dbus_string_free (&path);
1276 * Replace the DBUS_PREFIX in the given path, in-place, by the
1277 * current D-Bus installation directory. On Unix this function
1278 * does nothing, successfully.
1280 * @param path path to edit
1281 * @return #FALSE on OOM
1284 _dbus_replace_install_prefix (DBusString *path)
1289 #define DBUS_UNIX_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
1290 #define DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR "/dbus-1/system-services"
1293 * Returns the standard directories for a session bus to look for service
1296 * On UNIX this should be the standard xdg freedesktop.org data directories:
1298 * XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}
1299 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1305 * @param dirs the directory list we are returning
1306 * @returns #FALSE on OOM
1310 _dbus_get_standard_session_servicedirs (DBusList **dirs)
1312 const char *xdg_data_home;
1313 const char *xdg_data_dirs;
1314 DBusString servicedir_path;
1316 if (!_dbus_string_init (&servicedir_path))
1319 xdg_data_home = _dbus_getenv ("XDG_DATA_HOME");
1320 xdg_data_dirs = _dbus_getenv ("XDG_DATA_DIRS");
1322 if (xdg_data_home != NULL)
1324 if (!_dbus_string_append (&servicedir_path, xdg_data_home))
1329 const DBusString *homedir;
1330 DBusString local_share;
1332 if (!_dbus_homedir_from_current_process (&homedir))
1335 if (!_dbus_string_append (&servicedir_path, _dbus_string_get_const_data (homedir)))
1338 _dbus_string_init_const (&local_share, "/.local/share");
1339 if (!_dbus_concat_dir_and_file (&servicedir_path, &local_share))
1343 if (!_dbus_string_append (&servicedir_path, ":"))
1346 if (xdg_data_dirs != NULL)
1348 if (!_dbus_string_append (&servicedir_path, xdg_data_dirs))
1351 if (!_dbus_string_append (&servicedir_path, ":"))
1356 if (!_dbus_string_append (&servicedir_path, "/usr/local/share:/usr/share:"))
1361 * add configured datadir to defaults
1362 * this may be the same as an xdg dir
1363 * however the config parser should take
1364 * care of duplicates
1366 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR))
1369 if (!_dbus_split_paths_and_append (&servicedir_path,
1370 DBUS_UNIX_STANDARD_SESSION_SERVICEDIR,
1374 _dbus_string_free (&servicedir_path);
1378 _dbus_string_free (&servicedir_path);
1384 * Returns the standard directories for a system bus to look for service
1387 * On UNIX this should be the standard xdg freedesktop.org data directories:
1389 * XDG_DATA_DIRS=${XDG_DATA_DIRS-/usr/local/share:/usr/share}
1395 * On Windows there is no system bus and this function can return nothing.
1397 * @param dirs the directory list we are returning
1398 * @returns #FALSE on OOM
1402 _dbus_get_standard_system_servicedirs (DBusList **dirs)
1405 * DBUS_DATADIR may be the same as one of the standard directories. However,
1406 * the config parser should take care of the duplicates.
1408 * Also, append /lib as counterpart of /usr/share on the root
1409 * directory (the root directory does not know /share), in order to
1410 * facilitate early boot system bus activation where /usr might not
1413 static const char standard_search_path[] =
1418 DBusString servicedir_path;
1420 _dbus_string_init_const (&servicedir_path, standard_search_path);
1422 return _dbus_split_paths_and_append (&servicedir_path,
1423 DBUS_UNIX_STANDARD_SYSTEM_SERVICEDIR,
1428 * Get the absolute path of the system.conf file
1429 * (there is no system bus on Windows so this can just
1430 * return FALSE and print a warning or something)
1432 * @param str the string to append to, which must be empty on entry
1433 * @returns #FALSE if no memory
1436 _dbus_get_system_config_file (DBusString *str)
1438 _dbus_assert (_dbus_string_get_length (str) == 0);
1440 return _dbus_string_append (str, DBUS_SYSTEM_CONFIG_FILE);
1444 * Get the absolute path of the session.conf file.
1446 * @param str the string to append to, which must be empty on entry
1447 * @returns #FALSE if no memory
1450 _dbus_get_session_config_file (DBusString *str)
1452 _dbus_assert (_dbus_string_get_length (str) == 0);
1454 return _dbus_string_append (str, DBUS_SESSION_CONFIG_FILE);