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
24 #include "dbus-sysdeps.h"
25 #include "dbus-sysdeps-unix.h"
26 #include "dbus-internals.h"
27 #include "dbus-protocol.h"
28 #include "dbus-string.h"
29 #define DBUS_USERDB_INCLUDES_PRIVATE 1
30 #include "dbus-userdb.h"
31 #include "dbus-test.h"
33 #include <sys/types.h>
43 #include <sys/socket.h>
48 #include <sys/prctl.h>
49 #include <sys/capability.h>
51 #endif /* HAVE_LIBAUDIT */
53 #ifdef HAVE_SYS_SYSLIMITS_H
54 #include <sys/syslimits.h>
62 * @addtogroup DBusInternalsUtils
68 * Does the chdir, fork, setsid, etc. to become a daemon process.
70 * @param pidfile #NULL, or pidfile to create
71 * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
72 * @param error return location for errors
73 * @param keep_umask #TRUE to keep the original umask
74 * @returns #FALSE on failure
77 _dbus_become_daemon (const DBusString *pidfile,
78 DBusPipe *print_pid_pipe,
80 dbus_bool_t keep_umask)
86 _dbus_verbose ("Becoming a daemon...\n");
88 _dbus_verbose ("chdir to /\n");
91 dbus_set_error (error, DBUS_ERROR_FAILED,
92 "Could not chdir() to root directory");
96 _dbus_verbose ("forking...\n");
97 switch ((child_pid = fork ()))
100 _dbus_verbose ("fork failed\n");
101 dbus_set_error (error, _dbus_error_from_errno (errno),
102 "Failed to fork daemon: %s", _dbus_strerror (errno));
107 _dbus_verbose ("in child, closing std file descriptors\n");
109 /* silently ignore failures here, if someone
110 * doesn't have /dev/null we may as well try
114 dev_null_fd = open ("/dev/null", O_RDWR);
115 if (dev_null_fd >= 0)
117 dup2 (dev_null_fd, 0);
118 dup2 (dev_null_fd, 1);
120 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
121 if (s == NULL || *s == '\0')
122 dup2 (dev_null_fd, 2);
124 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
129 /* Get a predictable umask */
130 _dbus_verbose ("setting umask\n");
134 _dbus_verbose ("calling setsid()\n");
136 _dbus_assert_not_reached ("setsid() failed");
141 if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
144 _dbus_verbose ("pid file or pipe write failed: %s\n",
146 kill (child_pid, SIGTERM);
150 _dbus_verbose ("parent exiting\n");
160 * Creates a file containing the process ID.
162 * @param filename the filename to write to
163 * @param pid our process ID
164 * @param error return location for errors
165 * @returns #FALSE on failure
168 _dbus_write_pid_file (const DBusString *filename,
172 const char *cfilename;
176 cfilename = _dbus_string_get_const_data (filename);
178 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
182 dbus_set_error (error, _dbus_error_from_errno (errno),
183 "Failed to open \"%s\": %s", cfilename,
184 _dbus_strerror (errno));
188 if ((f = fdopen (fd, "w")) == NULL)
190 dbus_set_error (error, _dbus_error_from_errno (errno),
191 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
192 _dbus_close (fd, NULL);
196 if (fprintf (f, "%lu\n", pid) < 0)
198 dbus_set_error (error, _dbus_error_from_errno (errno),
199 "Failed to write to \"%s\": %s", cfilename,
200 _dbus_strerror (errno));
206 if (fclose (f) == EOF)
208 dbus_set_error (error, _dbus_error_from_errno (errno),
209 "Failed to close \"%s\": %s", cfilename,
210 _dbus_strerror (errno));
218 * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
219 * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
222 * @param pidfile the file to write to or #NULL
223 * @param print_pid_pipe the pipe to write to or #NULL
224 * @param pid_to_write the pid to write out
225 * @param error error on failure
226 * @returns FALSE if error is set
229 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
230 DBusPipe *print_pid_pipe,
231 dbus_pid_t pid_to_write,
236 _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
237 if (!_dbus_write_pid_file (pidfile,
241 _dbus_verbose ("pid file write failed\n");
242 _DBUS_ASSERT_ERROR_IS_SET(error);
248 _dbus_verbose ("No pid file requested\n");
251 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
256 _dbus_verbose ("writing our pid to pipe %d\n", print_pid_pipe->fd_or_handle);
258 if (!_dbus_string_init (&pid))
260 _DBUS_SET_OOM (error);
264 if (!_dbus_string_append_int (&pid, pid_to_write) ||
265 !_dbus_string_append (&pid, "\n"))
267 _dbus_string_free (&pid);
268 _DBUS_SET_OOM (error);
272 bytes = _dbus_string_get_length (&pid);
273 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
275 /* _dbus_pipe_write sets error only on failure, not short write */
276 if (error != NULL && !dbus_error_is_set(error))
278 dbus_set_error (error, DBUS_ERROR_FAILED,
279 "Printing message bus PID: did not write enough bytes\n");
281 _dbus_string_free (&pid);
285 _dbus_string_free (&pid);
289 _dbus_verbose ("No pid pipe to write to\n");
296 * Verify that after the fork we can successfully change to this user.
298 * @param user the username given in the daemon configuration
299 * @returns #TRUE if username is valid
302 _dbus_verify_daemon_user (const char *user)
306 _dbus_string_init_const (&u, user);
308 return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
312 * Changes the user and group the bus is running as.
314 * @param user the user to become
315 * @param error return location for errors
316 * @returns #FALSE on failure
319 _dbus_change_to_daemon_user (const char *user,
326 dbus_bool_t we_were_root;
330 _dbus_string_init_const (&u, user);
332 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
334 dbus_set_error (error, DBUS_ERROR_FAILED,
335 "User '%s' does not appear to exist?",
341 we_were_root = _dbus_geteuid () == 0;
343 /* have a tmp set of caps that we use to transition to the usr/grp dbus should
344 * run as ... doesn't really help. But keeps people happy.
349 cap_value_t new_cap_list[] = { CAP_AUDIT_WRITE };
350 cap_value_t tmp_cap_list[] = { CAP_AUDIT_WRITE, CAP_SETUID, CAP_SETGID };
351 cap_t tmp_caps = cap_init();
353 if (!tmp_caps || !(new_caps = cap_init ()))
355 dbus_set_error (error, DBUS_ERROR_FAILED,
356 "Failed to initialize drop of capabilities: %s\n",
357 _dbus_strerror (errno));
365 /* assume these work... */
366 cap_set_flag (new_caps, CAP_PERMITTED, 1, new_cap_list, CAP_SET);
367 cap_set_flag (new_caps, CAP_EFFECTIVE, 1, new_cap_list, CAP_SET);
368 cap_set_flag (tmp_caps, CAP_PERMITTED, 3, tmp_cap_list, CAP_SET);
369 cap_set_flag (tmp_caps, CAP_EFFECTIVE, 3, tmp_cap_list, CAP_SET);
371 if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
373 dbus_set_error (error, _dbus_error_from_errno (errno),
374 "Failed to set keep-capabilities: %s\n",
375 _dbus_strerror (errno));
380 if (cap_set_proc (tmp_caps) == -1)
382 dbus_set_error (error, DBUS_ERROR_FAILED,
383 "Failed to drop capabilities: %s\n",
384 _dbus_strerror (errno));
390 #endif /* HAVE_LIBAUDIT */
392 /* setgroups() only works if we are a privileged process,
393 * so we don't return error on failure; the only possible
394 * failure is that we don't have perms to do it.
396 * not sure this is right, maybe if setuid()
397 * is going to work then setgroups() should also work.
399 if (setgroups (0, NULL) < 0)
400 _dbus_warn ("Failed to drop supplementary groups: %s\n",
401 _dbus_strerror (errno));
403 /* Set GID first, or the setuid may remove our permission
406 if (setgid (gid) < 0)
408 dbus_set_error (error, _dbus_error_from_errno (errno),
409 "Failed to set GID to %lu: %s", gid,
410 _dbus_strerror (errno));
414 if (setuid (uid) < 0)
416 dbus_set_error (error, _dbus_error_from_errno (errno),
417 "Failed to set UID to %lu: %s", uid,
418 _dbus_strerror (errno));
425 if (cap_set_proc (new_caps))
427 dbus_set_error (error, DBUS_ERROR_FAILED,
428 "Failed to drop capabilities: %s\n",
429 _dbus_strerror (errno));
434 /* should always work, if it did above */
435 if (prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0) == -1)
437 dbus_set_error (error, _dbus_error_from_errno (errno),
438 "Failed to unset keep-capabilities: %s\n",
439 _dbus_strerror (errno));
451 /* should always work, if it did above */
452 prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0);
461 _dbus_init_system_log (void)
463 openlog ("dbus", LOG_PID, LOG_DAEMON);
467 * Log an informative message. Intended for use primarily by
470 * @param msg a printf-style format string
471 * @param args arguments for the format string
474 _dbus_log_info (const char *msg, va_list args)
476 vsyslog (LOG_DAEMON|LOG_NOTICE, msg, args);
480 * Log a security-related message. Intended for use primarily by
483 * @param msg a printf-style format string
484 * @param args arguments for the format string
487 _dbus_log_security (const char *msg, va_list args)
489 vsyslog (LOG_AUTH|LOG_NOTICE, msg, args);
492 /** Installs a UNIX signal handler
494 * @param sig the signal to handle
495 * @param handler the handler
498 _dbus_set_signal_handler (int sig,
499 DBusSignalHandler handler)
501 struct sigaction act;
504 sigemptyset (&empty_mask);
505 act.sa_handler = handler;
506 act.sa_mask = empty_mask;
508 sigaction (sig, &act, NULL);
513 * Removes a directory; Directory must be empty
515 * @param filename directory filename
516 * @param error initialized error object
517 * @returns #TRUE on success
520 _dbus_delete_directory (const DBusString *filename,
523 const char *filename_c;
525 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
527 filename_c = _dbus_string_get_const_data (filename);
529 if (rmdir (filename_c) != 0)
531 dbus_set_error (error, DBUS_ERROR_FAILED,
532 "Failed to remove directory %s: %s\n",
533 filename_c, _dbus_strerror (errno));
540 /** Checks if a file exists
542 * @param file full path to the file
543 * @returns #TRUE if file exists
546 _dbus_file_exists (const char *file)
548 return (access (file, F_OK) == 0);
551 /** Checks if user is at the console
553 * @param username user to check
554 * @param error return location for errors
555 * @returns #TRUE is the user is at the consolei and there are no errors
558 _dbus_user_at_console (const char *username,
566 if (!_dbus_string_init (&f))
568 _DBUS_SET_OOM (error);
572 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
574 _DBUS_SET_OOM (error);
579 if (!_dbus_string_append (&f, username))
581 _DBUS_SET_OOM (error);
585 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
588 _dbus_string_free (&f);
595 * Checks whether the filename is an absolute path
597 * @param filename the filename
598 * @returns #TRUE if an absolute path
601 _dbus_path_is_absolute (const DBusString *filename)
603 if (_dbus_string_get_length (filename) > 0)
604 return _dbus_string_get_byte (filename, 0) == '/';
612 * @param filename the filename to stat
613 * @param statbuf the stat info to fill in
614 * @param error return location for error
615 * @returns #FALSE if error was set
618 _dbus_stat (const DBusString *filename,
622 const char *filename_c;
625 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
627 filename_c = _dbus_string_get_const_data (filename);
629 if (stat (filename_c, &sb) < 0)
631 dbus_set_error (error, _dbus_error_from_errno (errno),
632 "%s", _dbus_strerror (errno));
636 statbuf->mode = sb.st_mode;
637 statbuf->nlink = sb.st_nlink;
638 statbuf->uid = sb.st_uid;
639 statbuf->gid = sb.st_gid;
640 statbuf->size = sb.st_size;
641 statbuf->atime = sb.st_atime;
642 statbuf->mtime = sb.st_mtime;
643 statbuf->ctime = sb.st_ctime;
650 * Internals of directory iterator
654 DIR *d; /**< The DIR* from opendir() */
659 * Open a directory to iterate over.
661 * @param filename the directory name
662 * @param error exception return object or #NULL
663 * @returns new iterator, or #NULL on error
666 _dbus_directory_open (const DBusString *filename,
671 const char *filename_c;
673 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
675 filename_c = _dbus_string_get_const_data (filename);
677 d = opendir (filename_c);
680 dbus_set_error (error, _dbus_error_from_errno (errno),
681 "Failed to read directory \"%s\": %s",
683 _dbus_strerror (errno));
686 iter = dbus_new0 (DBusDirIter, 1);
690 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
691 "Could not allocate memory for directory iterator");
700 /* Calculate the required buffer size (in bytes) for directory
701 * entries read from the given directory handle. Return -1 if this
702 * this cannot be done.
704 * If you use autoconf, include fpathconf and dirfd in your
705 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
706 * and use them where available.
709 dirent_buf_size(DIR * dirp, size_t *size)
712 # if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
713 # if defined(HAVE_DIRFD)
714 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
715 # elif defined(HAVE_DDFD)
716 name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
718 name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
719 # endif /* HAVE_DIRFD */
721 # if defined(NAME_MAX)
726 # elif defined(MAXNAMELEN)
727 name_max = MAXNAMELEN;
729 # if defined(NAME_MAX)
732 # error "buffer size for readdir_r cannot be determined"
736 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
744 * Get next file in the directory. Will not return "." or ".." on
745 * UNIX. If an error occurs, the contents of "filename" are
746 * undefined. The error is never set if the function succeeds.
748 * @param iter the iterator
749 * @param filename string to be set to the next file in the dir
750 * @param error return location for error
751 * @returns #TRUE if filename was filled in with a new filename
754 _dbus_directory_get_next_file (DBusDirIter *iter,
755 DBusString *filename,
758 struct dirent *d, *ent;
762 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
764 if (!dirent_buf_size (iter->d, &buf_size))
766 dbus_set_error (error, DBUS_ERROR_FAILED,
767 "Can't calculate buffer size when reading directory");
771 d = (struct dirent *)dbus_malloc (buf_size);
774 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
775 "No memory to read directory entry");
780 err = readdir_r (iter->d, d, &ent);
784 dbus_set_error (error,
785 _dbus_error_from_errno (err),
786 "%s", _dbus_strerror (err));
791 else if (ent->d_name[0] == '.' &&
792 (ent->d_name[1] == '\0' ||
793 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
797 _dbus_string_set_length (filename, 0);
798 if (!_dbus_string_append (filename, ent->d_name))
800 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
801 "No memory to read directory entry");
814 * Closes a directory iteration.
817 _dbus_directory_close (DBusDirIter *iter)
824 fill_user_info_from_group (struct group *g,
828 _dbus_assert (g->gr_name != NULL);
830 info->gid = g->gr_gid;
831 info->groupname = _dbus_strdup (g->gr_name);
833 /* info->members = dbus_strdupv (g->gr_mem) */
835 if (info->groupname == NULL)
837 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
845 fill_group_info (DBusGroupInfo *info,
847 const DBusString *groupname,
850 const char *group_c_str;
852 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
853 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
856 group_c_str = _dbus_string_get_const_data (groupname);
860 /* For now assuming that the getgrnam() and getgrgid() flavors
861 * always correspond to the pwnam flavors, if not we have
862 * to add more configure checks.
865 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
874 /* retrieve maximum needed size for buf */
875 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
877 /* sysconf actually returns a long, but everything else expects size_t,
878 * so just recast here.
879 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
881 if ((long) buflen <= 0)
887 buf = dbus_malloc (buflen);
890 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
895 #ifdef HAVE_POSIX_GETPWNAM_R
897 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
900 result = getgrgid_r (gid, &g_str, buf, buflen,
903 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
905 #endif /* !HAVE_POSIX_GETPWNAM_R */
906 /* Try a bigger buffer if ERANGE was returned:
907 https://bugs.freedesktop.org/show_bug.cgi?id=16727
909 if (result == ERANGE && buflen < 512 * 1024)
920 if (result == 0 && g == &g_str)
922 b = fill_user_info_from_group (g, info, error);
928 dbus_set_error (error, _dbus_error_from_errno (errno),
929 "Group %s unknown or failed to look it up\n",
930 group_c_str ? group_c_str : "???");
935 #else /* ! HAVE_GETPWNAM_R */
937 /* I guess we're screwed on thread safety here */
940 g = getgrnam (group_c_str);
944 return fill_user_info_from_group (g, info, error);
948 dbus_set_error (error, _dbus_error_from_errno (errno),
949 "Group %s unknown or failed to look it up\n",
950 group_c_str ? group_c_str : "???");
954 #endif /* ! HAVE_GETPWNAM_R */
958 * Initializes the given DBusGroupInfo struct
959 * with information about the given group name.
961 * @param info the group info struct
962 * @param groupname name of group
963 * @param error the error return
964 * @returns #FALSE if error is set
967 _dbus_group_info_fill (DBusGroupInfo *info,
968 const DBusString *groupname,
971 return fill_group_info (info, DBUS_GID_UNSET,
977 * Initializes the given DBusGroupInfo struct
978 * with information about the given group ID.
980 * @param info the group info struct
981 * @param gid group ID
982 * @param error the error return
983 * @returns #FALSE if error is set
986 _dbus_group_info_fill_gid (DBusGroupInfo *info,
990 return fill_group_info (info, gid, NULL, error);
994 * Parse a UNIX user from the bus config file. On Windows, this should
995 * simply always fail (just return #FALSE).
997 * @param username the username text
998 * @param uid_p place to return the uid
999 * @returns #TRUE on success
1002 _dbus_parse_unix_user_from_config (const DBusString *username,
1005 return _dbus_get_user_id (username, uid_p);
1010 * Parse a UNIX group from the bus config file. On Windows, this should
1011 * simply always fail (just return #FALSE).
1013 * @param groupname the groupname text
1014 * @param gid_p place to return the gid
1015 * @returns #TRUE on success
1018 _dbus_parse_unix_group_from_config (const DBusString *groupname,
1021 return _dbus_get_group_id (groupname, gid_p);
1025 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
1026 * just calls _dbus_groups_from_uid(). On Windows, should always
1027 * fail since we don't know any UNIX groups.
1029 * @param uid the UID
1030 * @param group_ids return location for array of group IDs
1031 * @param n_group_ids return location for length of returned array
1032 * @returns #TRUE if the UID existed and we got some credentials
1035 _dbus_unix_groups_from_uid (dbus_uid_t uid,
1036 dbus_gid_t **group_ids,
1039 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
1043 * Checks to see if the UNIX user ID is at the console.
1044 * Should always fail on Windows (set the error to
1045 * #DBUS_ERROR_NOT_SUPPORTED).
1047 * @param uid UID of person to check
1048 * @param error return location for errors
1049 * @returns #TRUE if the UID is the same as the console user and there are no errors
1052 _dbus_unix_user_is_at_console (dbus_uid_t uid,
1055 return _dbus_is_console_user (uid, error);
1060 * Checks to see if the UNIX user ID matches the UID of
1061 * the process. Should always return #FALSE on Windows.
1063 * @param uid the UNIX user ID
1064 * @returns #TRUE if this uid owns the process.
1067 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1069 return uid == _dbus_geteuid ();
1073 * Checks to see if the Windows user SID matches the owner of
1074 * the process. Should always return #FALSE on UNIX.
1076 * @param windows_sid the Windows user SID
1077 * @returns #TRUE if this user owns the process.
1080 _dbus_windows_user_is_process_owner (const char *windows_sid)
1085 /** @} */ /* End of DBusInternalsUtils functions */
1088 * @addtogroup DBusString
1093 * Get the directory name from a complete filename
1094 * @param filename the filename
1095 * @param dirname string to append directory name to
1096 * @returns #FALSE if no memory
1099 _dbus_string_get_dirname (const DBusString *filename,
1100 DBusString *dirname)
1104 _dbus_assert (filename != dirname);
1105 _dbus_assert (filename != NULL);
1106 _dbus_assert (dirname != NULL);
1108 /* Ignore any separators on the end */
1109 sep = _dbus_string_get_length (filename);
1111 return _dbus_string_append (dirname, "."); /* empty string passed in */
1113 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1116 _dbus_assert (sep >= 0);
1119 return _dbus_string_append (dirname, "/");
1121 /* Now find the previous separator */
1122 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1124 return _dbus_string_append (dirname, ".");
1126 /* skip multiple separators */
1127 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1130 _dbus_assert (sep >= 0);
1133 _dbus_string_get_byte (filename, 0) == '/')
1134 return _dbus_string_append (dirname, "/");
1136 return _dbus_string_copy_len (filename, 0, sep - 0,
1137 dirname, _dbus_string_get_length (dirname));
1139 /** @} */ /* DBusString stuff */
1142 string_squash_nonprintable (DBusString *str)
1147 buf = _dbus_string_get_data (str);
1148 len = _dbus_string_get_length (str);
1150 for (i = 0; i < len; i++)
1152 unsigned char c = (unsigned char) buf[i];
1155 else if (c < 0x20 || c > 127)
1161 * Get a printable string describing the command used to execute
1162 * the process with pid. This string should only be used for
1163 * informative purposes such as logging; it may not be trusted.
1165 * The command is guaranteed to be printable ASCII and no longer
1168 * @param pid Process id
1169 * @param str Append command to this string
1170 * @param max_len Maximum length of returned command
1171 * @param error return location for errors
1172 * @returns #FALSE on error
1175 _dbus_command_for_pid (unsigned long pid,
1180 /* This is all Linux-specific for now */
1185 if (!_dbus_string_init (&path))
1187 _DBUS_SET_OOM (error);
1191 if (!_dbus_string_init (&cmdline))
1193 _DBUS_SET_OOM (error);
1194 _dbus_string_free (&path);
1198 if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1201 fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1204 dbus_set_error (error,
1205 _dbus_error_from_errno (errno),
1206 "Failed to open \"%s\": %s",
1207 _dbus_string_get_const_data (&path),
1208 _dbus_strerror (errno));
1212 if (!_dbus_read (fd, &cmdline, max_len))
1214 dbus_set_error (error,
1215 _dbus_error_from_errno (errno),
1216 "Failed to read from \"%s\": %s",
1217 _dbus_string_get_const_data (&path),
1218 _dbus_strerror (errno));
1222 if (!_dbus_close (fd, error))
1225 string_squash_nonprintable (&cmdline);
1227 if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1230 _dbus_string_free (&cmdline);
1231 _dbus_string_free (&path);
1234 _DBUS_SET_OOM (error);
1236 _dbus_string_free (&cmdline);
1237 _dbus_string_free (&path);