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 * @returns #FALSE on failure
75 _dbus_become_daemon (const DBusString *pidfile,
76 DBusPipe *print_pid_pipe,
83 _dbus_verbose ("Becoming a daemon...\n");
85 _dbus_verbose ("chdir to /\n");
88 dbus_set_error (error, DBUS_ERROR_FAILED,
89 "Could not chdir() to root directory");
93 _dbus_verbose ("forking...\n");
94 switch ((child_pid = fork ()))
97 _dbus_verbose ("fork failed\n");
98 dbus_set_error (error, _dbus_error_from_errno (errno),
99 "Failed to fork daemon: %s", _dbus_strerror (errno));
104 _dbus_verbose ("in child, closing std file descriptors\n");
106 /* silently ignore failures here, if someone
107 * doesn't have /dev/null we may as well try
111 dev_null_fd = open ("/dev/null", O_RDWR);
112 if (dev_null_fd >= 0)
114 dup2 (dev_null_fd, 0);
115 dup2 (dev_null_fd, 1);
117 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
118 if (s == NULL || *s == '\0')
119 dup2 (dev_null_fd, 2);
121 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
124 /* Get a predictable umask */
125 _dbus_verbose ("setting umask\n");
128 _dbus_verbose ("calling setsid()\n");
130 _dbus_assert_not_reached ("setsid() failed");
135 if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
138 _dbus_verbose ("pid file or pipe write failed: %s\n",
140 kill (child_pid, SIGTERM);
144 _dbus_verbose ("parent exiting\n");
154 * Creates a file containing the process ID.
156 * @param filename the filename to write to
157 * @param pid our process ID
158 * @param error return location for errors
159 * @returns #FALSE on failure
162 _dbus_write_pid_file (const DBusString *filename,
166 const char *cfilename;
170 cfilename = _dbus_string_get_const_data (filename);
172 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
176 dbus_set_error (error, _dbus_error_from_errno (errno),
177 "Failed to open \"%s\": %s", cfilename,
178 _dbus_strerror (errno));
182 if ((f = fdopen (fd, "w")) == NULL)
184 dbus_set_error (error, _dbus_error_from_errno (errno),
185 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
186 _dbus_close (fd, NULL);
190 if (fprintf (f, "%lu\n", pid) < 0)
192 dbus_set_error (error, _dbus_error_from_errno (errno),
193 "Failed to write to \"%s\": %s", cfilename,
194 _dbus_strerror (errno));
200 if (fclose (f) == EOF)
202 dbus_set_error (error, _dbus_error_from_errno (errno),
203 "Failed to close \"%s\": %s", cfilename,
204 _dbus_strerror (errno));
212 * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
213 * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
216 * @param pidfile the file to write to or #NULL
217 * @param print_pid_pipe the pipe to write to or #NULL
218 * @param pid_to_write the pid to write out
219 * @param error error on failure
220 * @returns FALSE if error is set
223 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
224 DBusPipe *print_pid_pipe,
225 dbus_pid_t pid_to_write,
230 _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
231 if (!_dbus_write_pid_file (pidfile,
235 _dbus_verbose ("pid file write failed\n");
236 _DBUS_ASSERT_ERROR_IS_SET(error);
242 _dbus_verbose ("No pid file requested\n");
245 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
250 _dbus_verbose ("writing our pid to pipe %d\n", print_pid_pipe->fd_or_handle);
252 if (!_dbus_string_init (&pid))
254 _DBUS_SET_OOM (error);
258 if (!_dbus_string_append_int (&pid, pid_to_write) ||
259 !_dbus_string_append (&pid, "\n"))
261 _dbus_string_free (&pid);
262 _DBUS_SET_OOM (error);
266 bytes = _dbus_string_get_length (&pid);
267 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
269 /* _dbus_pipe_write sets error only on failure, not short write */
270 if (error != NULL && !dbus_error_is_set(error))
272 dbus_set_error (error, DBUS_ERROR_FAILED,
273 "Printing message bus PID: did not write enough bytes\n");
275 _dbus_string_free (&pid);
279 _dbus_string_free (&pid);
283 _dbus_verbose ("No pid pipe to write to\n");
290 * Verify that after the fork we can successfully change to this user.
292 * @param user the username given in the daemon configuration
293 * @returns #TRUE if username is valid
296 _dbus_verify_daemon_user (const char *user)
300 _dbus_string_init_const (&u, user);
302 return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
306 * Changes the user and group the bus is running as.
308 * @param user the user to become
309 * @param error return location for errors
310 * @returns #FALSE on failure
313 _dbus_change_to_daemon_user (const char *user,
320 dbus_bool_t we_were_root;
324 _dbus_string_init_const (&u, user);
326 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
328 dbus_set_error (error, DBUS_ERROR_FAILED,
329 "User '%s' does not appear to exist?",
335 we_were_root = _dbus_geteuid () == 0;
337 /* have a tmp set of caps that we use to transition to the usr/grp dbus should
338 * run as ... doesn't really help. But keeps people happy.
343 cap_value_t new_cap_list[] = { CAP_AUDIT_WRITE };
344 cap_value_t tmp_cap_list[] = { CAP_AUDIT_WRITE, CAP_SETUID, CAP_SETGID };
345 cap_t tmp_caps = cap_init();
347 if (!tmp_caps || !(new_caps = cap_init ()))
349 dbus_set_error (error, DBUS_ERROR_FAILED,
350 "Failed to initialize drop of capabilities: %s\n",
351 _dbus_strerror (errno));
359 /* assume these work... */
360 cap_set_flag (new_caps, CAP_PERMITTED, 1, new_cap_list, CAP_SET);
361 cap_set_flag (new_caps, CAP_EFFECTIVE, 1, new_cap_list, CAP_SET);
362 cap_set_flag (tmp_caps, CAP_PERMITTED, 3, tmp_cap_list, CAP_SET);
363 cap_set_flag (tmp_caps, CAP_EFFECTIVE, 3, tmp_cap_list, CAP_SET);
365 if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
367 dbus_set_error (error, _dbus_error_from_errno (errno),
368 "Failed to set keep-capabilities: %s\n",
369 _dbus_strerror (errno));
374 if (cap_set_proc (tmp_caps) == -1)
376 dbus_set_error (error, DBUS_ERROR_FAILED,
377 "Failed to drop capabilities: %s\n",
378 _dbus_strerror (errno));
384 #endif /* HAVE_LIBAUDIT */
386 /* setgroups() only works if we are a privileged process,
387 * so we don't return error on failure; the only possible
388 * failure is that we don't have perms to do it.
390 * not sure this is right, maybe if setuid()
391 * is going to work then setgroups() should also work.
393 if (setgroups (0, NULL) < 0)
394 _dbus_warn ("Failed to drop supplementary groups: %s\n",
395 _dbus_strerror (errno));
397 /* Set GID first, or the setuid may remove our permission
400 if (setgid (gid) < 0)
402 dbus_set_error (error, _dbus_error_from_errno (errno),
403 "Failed to set GID to %lu: %s", gid,
404 _dbus_strerror (errno));
408 if (setuid (uid) < 0)
410 dbus_set_error (error, _dbus_error_from_errno (errno),
411 "Failed to set UID to %lu: %s", uid,
412 _dbus_strerror (errno));
419 if (cap_set_proc (new_caps))
421 dbus_set_error (error, DBUS_ERROR_FAILED,
422 "Failed to drop capabilities: %s\n",
423 _dbus_strerror (errno));
428 /* should always work, if it did above */
429 if (prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0) == -1)
431 dbus_set_error (error, _dbus_error_from_errno (errno),
432 "Failed to unset keep-capabilities: %s\n",
433 _dbus_strerror (errno));
445 /* should always work, if it did above */
446 prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0);
454 /** Installs a UNIX signal handler
456 * @param sig the signal to handle
457 * @param handler the handler
460 _dbus_set_signal_handler (int sig,
461 DBusSignalHandler handler)
463 struct sigaction act;
466 sigemptyset (&empty_mask);
467 act.sa_handler = handler;
468 act.sa_mask = empty_mask;
470 sigaction (sig, &act, NULL);
475 * Removes a directory; Directory must be empty
477 * @param filename directory filename
478 * @param error initialized error object
479 * @returns #TRUE on success
482 _dbus_delete_directory (const DBusString *filename,
485 const char *filename_c;
487 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
489 filename_c = _dbus_string_get_const_data (filename);
491 if (rmdir (filename_c) != 0)
493 dbus_set_error (error, DBUS_ERROR_FAILED,
494 "Failed to remove directory %s: %s\n",
495 filename_c, _dbus_strerror (errno));
502 /** Checks if a file exists
504 * @param file full path to the file
505 * @returns #TRUE if file exists
508 _dbus_file_exists (const char *file)
510 return (access (file, F_OK) == 0);
513 /** Checks if user is at the console
515 * @param username user to check
516 * @param error return location for errors
517 * @returns #TRUE is the user is at the consolei and there are no errors
520 _dbus_user_at_console (const char *username,
528 if (!_dbus_string_init (&f))
530 _DBUS_SET_OOM (error);
534 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
536 _DBUS_SET_OOM (error);
541 if (!_dbus_string_append (&f, username))
543 _DBUS_SET_OOM (error);
547 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
550 _dbus_string_free (&f);
557 * Checks whether the filename is an absolute path
559 * @param filename the filename
560 * @returns #TRUE if an absolute path
563 _dbus_path_is_absolute (const DBusString *filename)
565 if (_dbus_string_get_length (filename) > 0)
566 return _dbus_string_get_byte (filename, 0) == '/';
574 * @param filename the filename to stat
575 * @param statbuf the stat info to fill in
576 * @param error return location for error
577 * @returns #FALSE if error was set
580 _dbus_stat (const DBusString *filename,
584 const char *filename_c;
587 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
589 filename_c = _dbus_string_get_const_data (filename);
591 if (stat (filename_c, &sb) < 0)
593 dbus_set_error (error, _dbus_error_from_errno (errno),
594 "%s", _dbus_strerror (errno));
598 statbuf->mode = sb.st_mode;
599 statbuf->nlink = sb.st_nlink;
600 statbuf->uid = sb.st_uid;
601 statbuf->gid = sb.st_gid;
602 statbuf->size = sb.st_size;
603 statbuf->atime = sb.st_atime;
604 statbuf->mtime = sb.st_mtime;
605 statbuf->ctime = sb.st_ctime;
612 * Internals of directory iterator
616 DIR *d; /**< The DIR* from opendir() */
621 * Open a directory to iterate over.
623 * @param filename the directory name
624 * @param error exception return object or #NULL
625 * @returns new iterator, or #NULL on error
628 _dbus_directory_open (const DBusString *filename,
633 const char *filename_c;
635 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
637 filename_c = _dbus_string_get_const_data (filename);
639 d = opendir (filename_c);
642 dbus_set_error (error, _dbus_error_from_errno (errno),
643 "Failed to read directory \"%s\": %s",
645 _dbus_strerror (errno));
648 iter = dbus_new0 (DBusDirIter, 1);
652 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
653 "Could not allocate memory for directory iterator");
662 /* Calculate the required buffer size (in bytes) for directory
663 * entries read from the given directory handle. Return -1 if this
664 * this cannot be done.
666 * If you use autoconf, include fpathconf and dirfd in your
667 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
668 * and use them where available.
671 dirent_buf_size(DIR * dirp, size_t *size)
674 # if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
675 # if defined(HAVE_DIRFD)
676 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
677 # elif defined(HAVE_DDFD)
678 name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
680 name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
681 # endif /* HAVE_DIRFD */
683 # if defined(NAME_MAX)
688 # elif defined(MAXNAMELEN)
689 name_max = MAXNAMELEN;
691 # if defined(NAME_MAX)
694 # error "buffer size for readdir_r cannot be determined"
698 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
706 * Get next file in the directory. Will not return "." or ".." on
707 * UNIX. If an error occurs, the contents of "filename" are
708 * undefined. The error is never set if the function succeeds.
710 * @param iter the iterator
711 * @param filename string to be set to the next file in the dir
712 * @param error return location for error
713 * @returns #TRUE if filename was filled in with a new filename
716 _dbus_directory_get_next_file (DBusDirIter *iter,
717 DBusString *filename,
720 struct dirent *d, *ent;
724 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
726 if (!dirent_buf_size (iter->d, &buf_size))
728 dbus_set_error (error, DBUS_ERROR_FAILED,
729 "Can't calculate buffer size when reading directory");
733 d = (struct dirent *)dbus_malloc (buf_size);
736 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
737 "No memory to read directory entry");
742 err = readdir_r (iter->d, d, &ent);
746 dbus_set_error (error,
747 _dbus_error_from_errno (err),
748 "%s", _dbus_strerror (err));
753 else if (ent->d_name[0] == '.' &&
754 (ent->d_name[1] == '\0' ||
755 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
759 _dbus_string_set_length (filename, 0);
760 if (!_dbus_string_append (filename, ent->d_name))
762 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
763 "No memory to read directory entry");
776 * Closes a directory iteration.
779 _dbus_directory_close (DBusDirIter *iter)
786 fill_user_info_from_group (struct group *g,
790 _dbus_assert (g->gr_name != NULL);
792 info->gid = g->gr_gid;
793 info->groupname = _dbus_strdup (g->gr_name);
795 /* info->members = dbus_strdupv (g->gr_mem) */
797 if (info->groupname == NULL)
799 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
807 fill_group_info (DBusGroupInfo *info,
809 const DBusString *groupname,
812 const char *group_c_str;
814 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
815 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
818 group_c_str = _dbus_string_get_const_data (groupname);
822 /* For now assuming that the getgrnam() and getgrgid() flavors
823 * always correspond to the pwnam flavors, if not we have
824 * to add more configure checks.
827 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
836 /* retrieve maximum needed size for buf */
837 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
839 /* sysconf actually returns a long, but everything else expects size_t,
840 * so just recast here.
841 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
843 if ((long) buflen <= 0)
849 buf = dbus_malloc (buflen);
852 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
857 #ifdef HAVE_POSIX_GETPWNAM_R
859 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
862 result = getgrgid_r (gid, &g_str, buf, buflen,
865 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
867 #endif /* !HAVE_POSIX_GETPWNAM_R */
868 /* Try a bigger buffer if ERANGE was returned:
869 https://bugs.freedesktop.org/show_bug.cgi?id=16727
871 if (result == ERANGE && buflen < 512 * 1024)
882 if (result == 0 && g == &g_str)
884 b = fill_user_info_from_group (g, info, error);
890 dbus_set_error (error, _dbus_error_from_errno (errno),
891 "Group %s unknown or failed to look it up\n",
892 group_c_str ? group_c_str : "???");
897 #else /* ! HAVE_GETPWNAM_R */
899 /* I guess we're screwed on thread safety here */
902 g = getgrnam (group_c_str);
906 return fill_user_info_from_group (g, info, error);
910 dbus_set_error (error, _dbus_error_from_errno (errno),
911 "Group %s unknown or failed to look it up\n",
912 group_c_str ? group_c_str : "???");
916 #endif /* ! HAVE_GETPWNAM_R */
920 * Initializes the given DBusGroupInfo struct
921 * with information about the given group name.
923 * @param info the group info struct
924 * @param groupname name of group
925 * @param error the error return
926 * @returns #FALSE if error is set
929 _dbus_group_info_fill (DBusGroupInfo *info,
930 const DBusString *groupname,
933 return fill_group_info (info, DBUS_GID_UNSET,
939 * Initializes the given DBusGroupInfo struct
940 * with information about the given group ID.
942 * @param info the group info struct
943 * @param gid group ID
944 * @param error the error return
945 * @returns #FALSE if error is set
948 _dbus_group_info_fill_gid (DBusGroupInfo *info,
952 return fill_group_info (info, gid, NULL, error);
956 * Parse a UNIX user from the bus config file. On Windows, this should
957 * simply always fail (just return #FALSE).
959 * @param username the username text
960 * @param uid_p place to return the uid
961 * @returns #TRUE on success
964 _dbus_parse_unix_user_from_config (const DBusString *username,
967 return _dbus_get_user_id (username, uid_p);
972 * Parse a UNIX group from the bus config file. On Windows, this should
973 * simply always fail (just return #FALSE).
975 * @param groupname the groupname text
976 * @param gid_p place to return the gid
977 * @returns #TRUE on success
980 _dbus_parse_unix_group_from_config (const DBusString *groupname,
983 return _dbus_get_group_id (groupname, gid_p);
987 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
988 * just calls _dbus_groups_from_uid(). On Windows, should always
989 * fail since we don't know any UNIX groups.
992 * @param group_ids return location for array of group IDs
993 * @param n_group_ids return location for length of returned array
994 * @returns #TRUE if the UID existed and we got some credentials
997 _dbus_unix_groups_from_uid (dbus_uid_t uid,
998 dbus_gid_t **group_ids,
1001 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
1005 * Checks to see if the UNIX user ID is at the console.
1006 * Should always fail on Windows (set the error to
1007 * #DBUS_ERROR_NOT_SUPPORTED).
1009 * @param uid UID of person to check
1010 * @param error return location for errors
1011 * @returns #TRUE if the UID is the same as the console user and there are no errors
1014 _dbus_unix_user_is_at_console (dbus_uid_t uid,
1017 return _dbus_is_console_user (uid, error);
1022 * Checks to see if the UNIX user ID matches the UID of
1023 * the process. Should always return #FALSE on Windows.
1025 * @param uid the UNIX user ID
1026 * @returns #TRUE if this uid owns the process.
1029 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1031 return uid == _dbus_geteuid ();
1035 * Checks to see if the Windows user SID matches the owner of
1036 * the process. Should always return #FALSE on UNIX.
1038 * @param windows_sid the Windows user SID
1039 * @returns #TRUE if this user owns the process.
1042 _dbus_windows_user_is_process_owner (const char *windows_sid)
1047 /** @} */ /* End of DBusInternalsUtils functions */
1050 * @addtogroup DBusString
1055 * Get the directory name from a complete filename
1056 * @param filename the filename
1057 * @param dirname string to append directory name to
1058 * @returns #FALSE if no memory
1061 _dbus_string_get_dirname (const DBusString *filename,
1062 DBusString *dirname)
1066 _dbus_assert (filename != dirname);
1067 _dbus_assert (filename != NULL);
1068 _dbus_assert (dirname != NULL);
1070 /* Ignore any separators on the end */
1071 sep = _dbus_string_get_length (filename);
1073 return _dbus_string_append (dirname, "."); /* empty string passed in */
1075 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1078 _dbus_assert (sep >= 0);
1081 return _dbus_string_append (dirname, "/");
1083 /* Now find the previous separator */
1084 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1086 return _dbus_string_append (dirname, ".");
1088 /* skip multiple separators */
1089 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1092 _dbus_assert (sep >= 0);
1095 _dbus_string_get_byte (filename, 0) == '/')
1096 return _dbus_string_append (dirname, "/");
1098 return _dbus_string_copy_len (filename, 0, sep - 0,
1099 dirname, _dbus_string_get_length (dirname));
1101 /** @} */ /* DBusString stuff */