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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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>
47 #include <sys/prctl.h>
48 #include <sys/capability.h>
50 #endif /* HAVE_LIBAUDIT */
52 #ifdef HAVE_SYS_SYSLIMITS_H
53 #include <sys/syslimits.h>
61 * @addtogroup DBusInternalsUtils
67 * Does the chdir, fork, setsid, etc. to become a daemon process.
69 * @param pidfile #NULL, or pidfile to create
70 * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
71 * @param error return location for errors
72 * @param keep_umask #TRUE to keep the original umask
73 * @returns #FALSE on failure
76 _dbus_become_daemon (const DBusString *pidfile,
77 DBusPipe *print_pid_pipe,
79 dbus_bool_t keep_umask)
85 _dbus_verbose ("Becoming a daemon...\n");
87 _dbus_verbose ("chdir to /\n");
90 dbus_set_error (error, DBUS_ERROR_FAILED,
91 "Could not chdir() to root directory");
95 _dbus_verbose ("forking...\n");
96 switch ((child_pid = fork ()))
99 _dbus_verbose ("fork failed\n");
100 dbus_set_error (error, _dbus_error_from_errno (errno),
101 "Failed to fork daemon: %s", _dbus_strerror (errno));
106 _dbus_verbose ("in child, closing std file descriptors\n");
108 /* silently ignore failures here, if someone
109 * doesn't have /dev/null we may as well try
113 dev_null_fd = open ("/dev/null", O_RDWR);
114 if (dev_null_fd >= 0)
116 dup2 (dev_null_fd, 0);
117 dup2 (dev_null_fd, 1);
119 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
120 if (s == NULL || *s == '\0')
121 dup2 (dev_null_fd, 2);
123 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
128 /* Get a predictable umask */
129 _dbus_verbose ("setting umask\n");
133 _dbus_verbose ("calling setsid()\n");
135 _dbus_assert_not_reached ("setsid() failed");
140 if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
143 _dbus_verbose ("pid file or pipe write failed: %s\n",
145 kill (child_pid, SIGTERM);
149 _dbus_verbose ("parent exiting\n");
159 * Creates a file containing the process ID.
161 * @param filename the filename to write to
162 * @param pid our process ID
163 * @param error return location for errors
164 * @returns #FALSE on failure
167 _dbus_write_pid_file (const DBusString *filename,
171 const char *cfilename;
175 cfilename = _dbus_string_get_const_data (filename);
177 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
181 dbus_set_error (error, _dbus_error_from_errno (errno),
182 "Failed to open \"%s\": %s", cfilename,
183 _dbus_strerror (errno));
187 if ((f = fdopen (fd, "w")) == NULL)
189 dbus_set_error (error, _dbus_error_from_errno (errno),
190 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
191 _dbus_close (fd, NULL);
195 if (fprintf (f, "%lu\n", pid) < 0)
197 dbus_set_error (error, _dbus_error_from_errno (errno),
198 "Failed to write to \"%s\": %s", cfilename,
199 _dbus_strerror (errno));
205 if (fclose (f) == EOF)
207 dbus_set_error (error, _dbus_error_from_errno (errno),
208 "Failed to close \"%s\": %s", cfilename,
209 _dbus_strerror (errno));
217 * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
218 * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
221 * @param pidfile the file to write to or #NULL
222 * @param print_pid_pipe the pipe to write to or #NULL
223 * @param pid_to_write the pid to write out
224 * @param error error on failure
225 * @returns FALSE if error is set
228 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
229 DBusPipe *print_pid_pipe,
230 dbus_pid_t pid_to_write,
235 _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
236 if (!_dbus_write_pid_file (pidfile,
240 _dbus_verbose ("pid file write failed\n");
241 _DBUS_ASSERT_ERROR_IS_SET(error);
247 _dbus_verbose ("No pid file requested\n");
250 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
255 _dbus_verbose ("writing our pid to pipe %d\n", print_pid_pipe->fd_or_handle);
257 if (!_dbus_string_init (&pid))
259 _DBUS_SET_OOM (error);
263 if (!_dbus_string_append_int (&pid, pid_to_write) ||
264 !_dbus_string_append (&pid, "\n"))
266 _dbus_string_free (&pid);
267 _DBUS_SET_OOM (error);
271 bytes = _dbus_string_get_length (&pid);
272 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
274 /* _dbus_pipe_write sets error only on failure, not short write */
275 if (error != NULL && !dbus_error_is_set(error))
277 dbus_set_error (error, DBUS_ERROR_FAILED,
278 "Printing message bus PID: did not write enough bytes\n");
280 _dbus_string_free (&pid);
284 _dbus_string_free (&pid);
288 _dbus_verbose ("No pid pipe to write to\n");
295 * Verify that after the fork we can successfully change to this user.
297 * @param user the username given in the daemon configuration
298 * @returns #TRUE if username is valid
301 _dbus_verify_daemon_user (const char *user)
305 _dbus_string_init_const (&u, user);
307 return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
311 * Changes the user and group the bus is running as.
313 * @param user the user to become
314 * @param error return location for errors
315 * @returns #FALSE on failure
318 _dbus_change_to_daemon_user (const char *user,
325 dbus_bool_t we_were_root;
329 _dbus_string_init_const (&u, user);
331 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
333 dbus_set_error (error, DBUS_ERROR_FAILED,
334 "User '%s' does not appear to exist?",
340 we_were_root = _dbus_geteuid () == 0;
342 /* have a tmp set of caps that we use to transition to the usr/grp dbus should
343 * run as ... doesn't really help. But keeps people happy.
348 cap_value_t new_cap_list[] = { CAP_AUDIT_WRITE };
349 cap_value_t tmp_cap_list[] = { CAP_AUDIT_WRITE, CAP_SETUID, CAP_SETGID };
350 cap_t tmp_caps = cap_init();
352 if (!tmp_caps || !(new_caps = cap_init ()))
354 dbus_set_error (error, DBUS_ERROR_FAILED,
355 "Failed to initialize drop of capabilities: %s\n",
356 _dbus_strerror (errno));
364 /* assume these work... */
365 cap_set_flag (new_caps, CAP_PERMITTED, 1, new_cap_list, CAP_SET);
366 cap_set_flag (new_caps, CAP_EFFECTIVE, 1, new_cap_list, CAP_SET);
367 cap_set_flag (tmp_caps, CAP_PERMITTED, 3, tmp_cap_list, CAP_SET);
368 cap_set_flag (tmp_caps, CAP_EFFECTIVE, 3, tmp_cap_list, CAP_SET);
370 if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
372 dbus_set_error (error, _dbus_error_from_errno (errno),
373 "Failed to set keep-capabilities: %s\n",
374 _dbus_strerror (errno));
379 if (cap_set_proc (tmp_caps) == -1)
381 dbus_set_error (error, DBUS_ERROR_FAILED,
382 "Failed to drop capabilities: %s\n",
383 _dbus_strerror (errno));
389 #endif /* HAVE_LIBAUDIT */
391 /* setgroups() only works if we are a privileged process,
392 * so we don't return error on failure; the only possible
393 * failure is that we don't have perms to do it.
395 * not sure this is right, maybe if setuid()
396 * is going to work then setgroups() should also work.
398 if (setgroups (0, NULL) < 0)
399 _dbus_warn ("Failed to drop supplementary groups: %s\n",
400 _dbus_strerror (errno));
402 /* Set GID first, or the setuid may remove our permission
405 if (setgid (gid) < 0)
407 dbus_set_error (error, _dbus_error_from_errno (errno),
408 "Failed to set GID to %lu: %s", gid,
409 _dbus_strerror (errno));
413 if (setuid (uid) < 0)
415 dbus_set_error (error, _dbus_error_from_errno (errno),
416 "Failed to set UID to %lu: %s", uid,
417 _dbus_strerror (errno));
424 if (cap_set_proc (new_caps))
426 dbus_set_error (error, DBUS_ERROR_FAILED,
427 "Failed to drop capabilities: %s\n",
428 _dbus_strerror (errno));
433 /* should always work, if it did above */
434 if (prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0) == -1)
436 dbus_set_error (error, _dbus_error_from_errno (errno),
437 "Failed to unset keep-capabilities: %s\n",
438 _dbus_strerror (errno));
450 /* should always work, if it did above */
451 prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0);
459 /** Installs a UNIX signal handler
461 * @param sig the signal to handle
462 * @param handler the handler
465 _dbus_set_signal_handler (int sig,
466 DBusSignalHandler handler)
468 struct sigaction act;
471 sigemptyset (&empty_mask);
472 act.sa_handler = handler;
473 act.sa_mask = empty_mask;
475 sigaction (sig, &act, NULL);
480 * Removes a directory; Directory must be empty
482 * @param filename directory filename
483 * @param error initialized error object
484 * @returns #TRUE on success
487 _dbus_delete_directory (const DBusString *filename,
490 const char *filename_c;
492 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
494 filename_c = _dbus_string_get_const_data (filename);
496 if (rmdir (filename_c) != 0)
498 dbus_set_error (error, DBUS_ERROR_FAILED,
499 "Failed to remove directory %s: %s\n",
500 filename_c, _dbus_strerror (errno));
507 /** Checks if a file exists
509 * @param file full path to the file
510 * @returns #TRUE if file exists
513 _dbus_file_exists (const char *file)
515 return (access (file, F_OK) == 0);
518 /** Checks if user is at the console
520 * @param username user to check
521 * @param error return location for errors
522 * @returns #TRUE is the user is at the consolei and there are no errors
525 _dbus_user_at_console (const char *username,
533 if (!_dbus_string_init (&f))
535 _DBUS_SET_OOM (error);
539 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
541 _DBUS_SET_OOM (error);
546 if (!_dbus_string_append (&f, username))
548 _DBUS_SET_OOM (error);
552 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
555 _dbus_string_free (&f);
562 * Checks whether the filename is an absolute path
564 * @param filename the filename
565 * @returns #TRUE if an absolute path
568 _dbus_path_is_absolute (const DBusString *filename)
570 if (_dbus_string_get_length (filename) > 0)
571 return _dbus_string_get_byte (filename, 0) == '/';
579 * @param filename the filename to stat
580 * @param statbuf the stat info to fill in
581 * @param error return location for error
582 * @returns #FALSE if error was set
585 _dbus_stat (const DBusString *filename,
589 const char *filename_c;
592 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
594 filename_c = _dbus_string_get_const_data (filename);
596 if (stat (filename_c, &sb) < 0)
598 dbus_set_error (error, _dbus_error_from_errno (errno),
599 "%s", _dbus_strerror (errno));
603 statbuf->mode = sb.st_mode;
604 statbuf->nlink = sb.st_nlink;
605 statbuf->uid = sb.st_uid;
606 statbuf->gid = sb.st_gid;
607 statbuf->size = sb.st_size;
608 statbuf->atime = sb.st_atime;
609 statbuf->mtime = sb.st_mtime;
610 statbuf->ctime = sb.st_ctime;
617 * Internals of directory iterator
621 DIR *d; /**< The DIR* from opendir() */
626 * Open a directory to iterate over.
628 * @param filename the directory name
629 * @param error exception return object or #NULL
630 * @returns new iterator, or #NULL on error
633 _dbus_directory_open (const DBusString *filename,
638 const char *filename_c;
640 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
642 filename_c = _dbus_string_get_const_data (filename);
644 d = opendir (filename_c);
647 dbus_set_error (error, _dbus_error_from_errno (errno),
648 "Failed to read directory \"%s\": %s",
650 _dbus_strerror (errno));
653 iter = dbus_new0 (DBusDirIter, 1);
657 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
658 "Could not allocate memory for directory iterator");
667 /* Calculate the required buffer size (in bytes) for directory
668 * entries read from the given directory handle. Return -1 if this
669 * this cannot be done.
671 * If you use autoconf, include fpathconf and dirfd in your
672 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
673 * and use them where available.
676 dirent_buf_size(DIR * dirp, size_t *size)
679 # if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
680 # if defined(HAVE_DIRFD)
681 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
682 # elif defined(HAVE_DDFD)
683 name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
685 name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
686 # endif /* HAVE_DIRFD */
688 # if defined(NAME_MAX)
693 # elif defined(MAXNAMELEN)
694 name_max = MAXNAMELEN;
696 # if defined(NAME_MAX)
699 # error "buffer size for readdir_r cannot be determined"
703 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
711 * Get next file in the directory. Will not return "." or ".." on
712 * UNIX. If an error occurs, the contents of "filename" are
713 * undefined. The error is never set if the function succeeds.
715 * @param iter the iterator
716 * @param filename string to be set to the next file in the dir
717 * @param error return location for error
718 * @returns #TRUE if filename was filled in with a new filename
721 _dbus_directory_get_next_file (DBusDirIter *iter,
722 DBusString *filename,
725 struct dirent *d, *ent;
729 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
731 if (!dirent_buf_size (iter->d, &buf_size))
733 dbus_set_error (error, DBUS_ERROR_FAILED,
734 "Can't calculate buffer size when reading directory");
738 d = (struct dirent *)dbus_malloc (buf_size);
741 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
742 "No memory to read directory entry");
747 err = readdir_r (iter->d, d, &ent);
751 dbus_set_error (error,
752 _dbus_error_from_errno (err),
753 "%s", _dbus_strerror (err));
758 else if (ent->d_name[0] == '.' &&
759 (ent->d_name[1] == '\0' ||
760 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
764 _dbus_string_set_length (filename, 0);
765 if (!_dbus_string_append (filename, ent->d_name))
767 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
768 "No memory to read directory entry");
781 * Closes a directory iteration.
784 _dbus_directory_close (DBusDirIter *iter)
791 fill_user_info_from_group (struct group *g,
795 _dbus_assert (g->gr_name != NULL);
797 info->gid = g->gr_gid;
798 info->groupname = _dbus_strdup (g->gr_name);
800 /* info->members = dbus_strdupv (g->gr_mem) */
802 if (info->groupname == NULL)
804 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
812 fill_group_info (DBusGroupInfo *info,
814 const DBusString *groupname,
817 const char *group_c_str;
819 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
820 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
823 group_c_str = _dbus_string_get_const_data (groupname);
827 /* For now assuming that the getgrnam() and getgrgid() flavors
828 * always correspond to the pwnam flavors, if not we have
829 * to add more configure checks.
832 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
841 /* retrieve maximum needed size for buf */
842 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
844 /* sysconf actually returns a long, but everything else expects size_t,
845 * so just recast here.
846 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
848 if ((long) buflen <= 0)
854 buf = dbus_malloc (buflen);
857 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
862 #ifdef HAVE_POSIX_GETPWNAM_R
864 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
867 result = getgrgid_r (gid, &g_str, buf, buflen,
870 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
872 #endif /* !HAVE_POSIX_GETPWNAM_R */
873 /* Try a bigger buffer if ERANGE was returned:
874 https://bugs.freedesktop.org/show_bug.cgi?id=16727
876 if (result == ERANGE && buflen < 512 * 1024)
887 if (result == 0 && g == &g_str)
889 b = fill_user_info_from_group (g, info, error);
895 dbus_set_error (error, _dbus_error_from_errno (errno),
896 "Group %s unknown or failed to look it up\n",
897 group_c_str ? group_c_str : "???");
902 #else /* ! HAVE_GETPWNAM_R */
904 /* I guess we're screwed on thread safety here */
907 g = getgrnam (group_c_str);
911 return fill_user_info_from_group (g, info, error);
915 dbus_set_error (error, _dbus_error_from_errno (errno),
916 "Group %s unknown or failed to look it up\n",
917 group_c_str ? group_c_str : "???");
921 #endif /* ! HAVE_GETPWNAM_R */
925 * Initializes the given DBusGroupInfo struct
926 * with information about the given group name.
928 * @param info the group info struct
929 * @param groupname name of group
930 * @param error the error return
931 * @returns #FALSE if error is set
934 _dbus_group_info_fill (DBusGroupInfo *info,
935 const DBusString *groupname,
938 return fill_group_info (info, DBUS_GID_UNSET,
944 * Initializes the given DBusGroupInfo struct
945 * with information about the given group ID.
947 * @param info the group info struct
948 * @param gid group ID
949 * @param error the error return
950 * @returns #FALSE if error is set
953 _dbus_group_info_fill_gid (DBusGroupInfo *info,
957 return fill_group_info (info, gid, NULL, error);
961 * Parse a UNIX user from the bus config file. On Windows, this should
962 * simply always fail (just return #FALSE).
964 * @param username the username text
965 * @param uid_p place to return the uid
966 * @returns #TRUE on success
969 _dbus_parse_unix_user_from_config (const DBusString *username,
972 return _dbus_get_user_id (username, uid_p);
977 * Parse a UNIX group from the bus config file. On Windows, this should
978 * simply always fail (just return #FALSE).
980 * @param groupname the groupname text
981 * @param gid_p place to return the gid
982 * @returns #TRUE on success
985 _dbus_parse_unix_group_from_config (const DBusString *groupname,
988 return _dbus_get_group_id (groupname, gid_p);
992 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
993 * just calls _dbus_groups_from_uid(). On Windows, should always
994 * fail since we don't know any UNIX groups.
997 * @param group_ids return location for array of group IDs
998 * @param n_group_ids return location for length of returned array
999 * @returns #TRUE if the UID existed and we got some credentials
1002 _dbus_unix_groups_from_uid (dbus_uid_t uid,
1003 dbus_gid_t **group_ids,
1006 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
1010 * Checks to see if the UNIX user ID is at the console.
1011 * Should always fail on Windows (set the error to
1012 * #DBUS_ERROR_NOT_SUPPORTED).
1014 * @param uid UID of person to check
1015 * @param error return location for errors
1016 * @returns #TRUE if the UID is the same as the console user and there are no errors
1019 _dbus_unix_user_is_at_console (dbus_uid_t uid,
1022 return _dbus_is_console_user (uid, error);
1027 * Checks to see if the UNIX user ID matches the UID of
1028 * the process. Should always return #FALSE on Windows.
1030 * @param uid the UNIX user ID
1031 * @returns #TRUE if this uid owns the process.
1034 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1036 return uid == _dbus_geteuid ();
1040 * Checks to see if the Windows user SID matches the owner of
1041 * the process. Should always return #FALSE on UNIX.
1043 * @param windows_sid the Windows user SID
1044 * @returns #TRUE if this user owns the process.
1047 _dbus_windows_user_is_process_owner (const char *windows_sid)
1052 /** @} */ /* End of DBusInternalsUtils functions */
1055 * @addtogroup DBusString
1060 * Get the directory name from a complete filename
1061 * @param filename the filename
1062 * @param dirname string to append directory name to
1063 * @returns #FALSE if no memory
1066 _dbus_string_get_dirname (const DBusString *filename,
1067 DBusString *dirname)
1071 _dbus_assert (filename != dirname);
1072 _dbus_assert (filename != NULL);
1073 _dbus_assert (dirname != NULL);
1075 /* Ignore any separators on the end */
1076 sep = _dbus_string_get_length (filename);
1078 return _dbus_string_append (dirname, "."); /* empty string passed in */
1080 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1083 _dbus_assert (sep >= 0);
1086 return _dbus_string_append (dirname, "/");
1088 /* Now find the previous separator */
1089 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1091 return _dbus_string_append (dirname, ".");
1093 /* skip multiple separators */
1094 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1097 _dbus_assert (sep >= 0);
1100 _dbus_string_get_byte (filename, 0) == '/')
1101 return _dbus_string_append (dirname, "/");
1103 return _dbus_string_copy_len (filename, 0, sep - 0,
1104 dirname, _dbus_string_get_length (dirname));
1106 /** @} */ /* DBusString stuff */