1 /* -*- mode: C; c-file-style: "gnu" -*- */
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 #ifdef HAVE_SYS_SYSLIMITS_H
48 #include <sys/syslimits.h>
56 * @addtogroup DBusInternalsUtils
61 * Does the chdir, fork, setsid, etc. to become a daemon process.
63 * @param pidfile #NULL, or pidfile to create
64 * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
65 * @param error return location for errors
66 * @returns #FALSE on failure
69 _dbus_become_daemon (const DBusString *pidfile,
70 DBusPipe *print_pid_pipe,
77 _dbus_verbose ("Becoming a daemon...\n");
79 _dbus_verbose ("chdir to /\n");
82 dbus_set_error (error, DBUS_ERROR_FAILED,
83 "Could not chdir() to root directory");
87 _dbus_verbose ("forking...\n");
88 switch ((child_pid = fork ()))
91 _dbus_verbose ("fork failed\n");
92 dbus_set_error (error, _dbus_error_from_errno (errno),
93 "Failed to fork daemon: %s", _dbus_strerror (errno));
98 _dbus_verbose ("in child, closing std file descriptors\n");
100 /* silently ignore failures here, if someone
101 * doesn't have /dev/null we may as well try
105 dev_null_fd = open ("/dev/null", O_RDWR);
106 if (dev_null_fd >= 0)
108 dup2 (dev_null_fd, 0);
109 dup2 (dev_null_fd, 1);
111 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
112 if (s == NULL || *s == '\0')
113 dup2 (dev_null_fd, 2);
115 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
118 /* Get a predictable umask */
119 _dbus_verbose ("setting umask\n");
126 _dbus_verbose ("parent writing pid file\n");
127 if (!_dbus_write_pid_file (pidfile,
131 _dbus_verbose ("pid file write failed, killing child\n");
132 kill (child_pid, SIGTERM);
137 /* Write PID if requested */
138 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
143 if (!_dbus_string_init (&pid))
145 _DBUS_SET_OOM (error);
146 kill (child_pid, SIGTERM);
150 if (!_dbus_string_append_int (&pid, child_pid) ||
151 !_dbus_string_append (&pid, "\n"))
153 _dbus_string_free (&pid);
154 _DBUS_SET_OOM (error);
155 kill (child_pid, SIGTERM);
159 bytes = _dbus_string_get_length (&pid);
160 if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
162 /* _dbus_pipe_write sets error only on failure, not short write */
163 if (error != NULL && !dbus_error_is_set(error))
165 dbus_set_error (error, DBUS_ERROR_FAILED,
166 "Printing message bus PID: did not write enough bytes\n");
168 _dbus_string_free (&pid);
169 kill (child_pid, SIGTERM);
173 _dbus_string_free (&pid);
175 _dbus_verbose ("parent exiting\n");
180 _dbus_verbose ("calling setsid()\n");
182 _dbus_assert_not_reached ("setsid() failed");
189 * Creates a file containing the process ID.
191 * @param filename the filename to write to
192 * @param pid our process ID
193 * @param error return location for errors
194 * @returns #FALSE on failure
197 _dbus_write_pid_file (const DBusString *filename,
201 const char *cfilename;
205 cfilename = _dbus_string_get_const_data (filename);
207 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
211 dbus_set_error (error, _dbus_error_from_errno (errno),
212 "Failed to open \"%s\": %s", cfilename,
213 _dbus_strerror (errno));
217 if ((f = fdopen (fd, "w")) == NULL)
219 dbus_set_error (error, _dbus_error_from_errno (errno),
220 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
221 _dbus_close (fd, NULL);
225 if (fprintf (f, "%lu\n", pid) < 0)
227 dbus_set_error (error, _dbus_error_from_errno (errno),
228 "Failed to write to \"%s\": %s", cfilename,
229 _dbus_strerror (errno));
235 if (fclose (f) == EOF)
237 dbus_set_error (error, _dbus_error_from_errno (errno),
238 "Failed to close \"%s\": %s", cfilename,
239 _dbus_strerror (errno));
247 * Verify that after the fork we can successfully change to this user.
249 * @param user the username given in the daemon configuration
250 * @returns #TRUE if username is valid
253 _dbus_verify_daemon_user (const char *user)
257 _dbus_string_init_const (&u, user);
259 return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
263 * Changes the user and group the bus is running as.
265 * @param user the user to become
266 * @param error return location for errors
267 * @returns #FALSE on failure
270 _dbus_change_to_daemon_user (const char *user,
277 _dbus_string_init_const (&u, user);
279 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
281 dbus_set_error (error, DBUS_ERROR_FAILED,
282 "User '%s' does not appear to exist?",
287 /* setgroups() only works if we are a privileged process,
288 * so we don't return error on failure; the only possible
289 * failure is that we don't have perms to do it.
291 * not sure this is right, maybe if setuid()
292 * is going to work then setgroups() should also work.
294 if (setgroups (0, NULL) < 0)
295 _dbus_warn ("Failed to drop supplementary groups: %s\n",
296 _dbus_strerror (errno));
298 /* Set GID first, or the setuid may remove our permission
301 if (setgid (gid) < 0)
303 dbus_set_error (error, _dbus_error_from_errno (errno),
304 "Failed to set GID to %lu: %s", gid,
305 _dbus_strerror (errno));
309 if (setuid (uid) < 0)
311 dbus_set_error (error, _dbus_error_from_errno (errno),
312 "Failed to set UID to %lu: %s", uid,
313 _dbus_strerror (errno));
320 /** Installs a UNIX signal handler
322 * @param sig the signal to handle
323 * @param handler the handler
326 _dbus_set_signal_handler (int sig,
327 DBusSignalHandler handler)
329 struct sigaction act;
332 sigemptyset (&empty_mask);
333 act.sa_handler = handler;
334 act.sa_mask = empty_mask;
336 sigaction (sig, &act, NULL);
341 * Removes a directory; Directory must be empty
343 * @param filename directory filename
344 * @param error initialized error object
345 * @returns #TRUE on success
348 _dbus_delete_directory (const DBusString *filename,
351 const char *filename_c;
353 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
355 filename_c = _dbus_string_get_const_data (filename);
357 if (rmdir (filename_c) != 0)
359 dbus_set_error (error, DBUS_ERROR_FAILED,
360 "Failed to remove directory %s: %s\n",
361 filename_c, _dbus_strerror (errno));
368 /** Checks if a file exists
370 * @param file full path to the file
371 * @returns #TRUE if file exists
374 _dbus_file_exists (const char *file)
376 return (access (file, F_OK) == 0);
379 /** Checks if user is at the console
381 * @param username user to check
382 * @param error return location for errors
383 * @returns #TRUE is the user is at the consolei and there are no errors
386 _dbus_user_at_console (const char *username,
394 if (!_dbus_string_init (&f))
396 _DBUS_SET_OOM (error);
400 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
402 _DBUS_SET_OOM (error);
407 if (!_dbus_string_append (&f, username))
409 _DBUS_SET_OOM (error);
413 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
416 _dbus_string_free (&f);
423 * Checks whether the filename is an absolute path
425 * @param filename the filename
426 * @returns #TRUE if an absolute path
429 _dbus_path_is_absolute (const DBusString *filename)
431 if (_dbus_string_get_length (filename) > 0)
432 return _dbus_string_get_byte (filename, 0) == '/';
440 * @param filename the filename to stat
441 * @param statbuf the stat info to fill in
442 * @param error return location for error
443 * @returns #FALSE if error was set
446 _dbus_stat (const DBusString *filename,
450 const char *filename_c;
453 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
455 filename_c = _dbus_string_get_const_data (filename);
457 if (stat (filename_c, &sb) < 0)
459 dbus_set_error (error, _dbus_error_from_errno (errno),
460 "%s", _dbus_strerror (errno));
464 statbuf->mode = sb.st_mode;
465 statbuf->nlink = sb.st_nlink;
466 statbuf->uid = sb.st_uid;
467 statbuf->gid = sb.st_gid;
468 statbuf->size = sb.st_size;
469 statbuf->atime = sb.st_atime;
470 statbuf->mtime = sb.st_mtime;
471 statbuf->ctime = sb.st_ctime;
478 * Internals of directory iterator
482 DIR *d; /**< The DIR* from opendir() */
487 * Open a directory to iterate over.
489 * @param filename the directory name
490 * @param error exception return object or #NULL
491 * @returns new iterator, or #NULL on error
494 _dbus_directory_open (const DBusString *filename,
499 const char *filename_c;
501 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
503 filename_c = _dbus_string_get_const_data (filename);
505 d = opendir (filename_c);
508 dbus_set_error (error, _dbus_error_from_errno (errno),
509 "Failed to read directory \"%s\": %s",
511 _dbus_strerror (errno));
514 iter = dbus_new0 (DBusDirIter, 1);
518 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
519 "Could not allocate memory for directory iterator");
528 /* Calculate the required buffer size (in bytes) for directory
529 * entries read from the given directory handle. Return -1 if this
530 * this cannot be done.
532 * If you use autoconf, include fpathconf and dirfd in your
533 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
534 * and use them where available.
537 dirent_buf_size(DIR * dirp, size_t *size)
540 # if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
541 # if defined(HAVE_DIRFD)
542 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
543 # elif defined(HAVE_DDFD)
544 name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
546 name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
547 # endif /* HAVE_DIRFD */
549 # if defined(NAME_MAX)
554 # elif defined(MAXNAMELEN)
555 name_max = MAXNAMELEN;
557 # if defined(NAME_MAX)
560 # error "buffer size for readdir_r cannot be determined"
564 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
572 * Get next file in the directory. Will not return "." or ".." on
573 * UNIX. If an error occurs, the contents of "filename" are
574 * undefined. The error is never set if the function succeeds.
576 * @param iter the iterator
577 * @param filename string to be set to the next file in the dir
578 * @param error return location for error
579 * @returns #TRUE if filename was filled in with a new filename
582 _dbus_directory_get_next_file (DBusDirIter *iter,
583 DBusString *filename,
586 struct dirent *d, *ent;
590 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
592 if (!dirent_buf_size (iter->d, &buf_size))
594 dbus_set_error (error, DBUS_ERROR_FAILED,
595 "Can't calculate buffer size when reading directory");
599 d = (struct dirent *)dbus_malloc (buf_size);
602 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
603 "No memory to read directory entry");
608 err = readdir_r (iter->d, d, &ent);
612 dbus_set_error (error,
613 _dbus_error_from_errno (err),
614 "%s", _dbus_strerror (err));
619 else if (ent->d_name[0] == '.' &&
620 (ent->d_name[1] == '\0' ||
621 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
625 _dbus_string_set_length (filename, 0);
626 if (!_dbus_string_append (filename, ent->d_name))
628 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
629 "No memory to read directory entry");
642 * Closes a directory iteration.
645 _dbus_directory_close (DBusDirIter *iter)
652 fill_user_info_from_group (struct group *g,
656 _dbus_assert (g->gr_name != NULL);
658 info->gid = g->gr_gid;
659 info->groupname = _dbus_strdup (g->gr_name);
661 /* info->members = dbus_strdupv (g->gr_mem) */
663 if (info->groupname == NULL)
665 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
673 fill_group_info (DBusGroupInfo *info,
675 const DBusString *groupname,
678 const char *group_c_str;
680 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
681 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
684 group_c_str = _dbus_string_get_const_data (groupname);
688 /* For now assuming that the getgrnam() and getgrgid() flavors
689 * always correspond to the pwnam flavors, if not we have
690 * to add more configure checks.
693 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
701 #ifdef HAVE_POSIX_GETPWNAM_R
704 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
707 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
710 g = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
712 #endif /* !HAVE_POSIX_GETPWNAM_R */
713 if (result == 0 && g == &g_str)
715 return fill_user_info_from_group (g, info, error);
719 dbus_set_error (error, _dbus_error_from_errno (errno),
720 "Group %s unknown or failed to look it up\n",
721 group_c_str ? group_c_str : "???");
725 #else /* ! HAVE_GETPWNAM_R */
727 /* I guess we're screwed on thread safety here */
730 g = getgrnam (group_c_str);
734 return fill_user_info_from_group (g, info, error);
738 dbus_set_error (error, _dbus_error_from_errno (errno),
739 "Group %s unknown or failed to look it up\n",
740 group_c_str ? group_c_str : "???");
744 #endif /* ! HAVE_GETPWNAM_R */
748 * Initializes the given DBusGroupInfo struct
749 * with information about the given group name.
751 * @param info the group info struct
752 * @param groupname name of group
753 * @param error the error return
754 * @returns #FALSE if error is set
757 _dbus_group_info_fill (DBusGroupInfo *info,
758 const DBusString *groupname,
761 return fill_group_info (info, DBUS_GID_UNSET,
767 * Initializes the given DBusGroupInfo struct
768 * with information about the given group ID.
770 * @param info the group info struct
771 * @param gid group ID
772 * @param error the error return
773 * @returns #FALSE if error is set
776 _dbus_group_info_fill_gid (DBusGroupInfo *info,
780 return fill_group_info (info, gid, NULL, error);
784 * Parse a UNIX user from the bus config file. On Windows, this should
785 * simply always fail (just return #FALSE).
787 * @param username the username text
788 * @param uid_p place to return the uid
789 * @returns #TRUE on success
792 _dbus_parse_unix_user_from_config (const DBusString *username,
795 return _dbus_get_user_id (username, uid_p);
800 * Parse a UNIX group from the bus config file. On Windows, this should
801 * simply always fail (just return #FALSE).
803 * @param groupname the groupname text
804 * @param gid_p place to return the gid
805 * @returns #TRUE on success
808 _dbus_parse_unix_group_from_config (const DBusString *groupname,
811 return _dbus_get_group_id (groupname, gid_p);
815 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
816 * just calls _dbus_groups_from_uid(). On Windows, should always
817 * fail since we don't know any UNIX groups.
820 * @param group_ids return location for array of group IDs
821 * @param n_group_ids return location for length of returned array
822 * @returns #TRUE if the UID existed and we got some credentials
825 _dbus_unix_groups_from_uid (dbus_uid_t uid,
826 dbus_gid_t **group_ids,
829 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
833 * Checks to see if the UNIX user ID is at the console.
834 * Should always fail on Windows (set the error to
835 * #DBUS_ERROR_NOT_SUPPORTED).
837 * @param uid UID of person to check
838 * @param error return location for errors
839 * @returns #TRUE if the UID is the same as the console user and there are no errors
842 _dbus_unix_user_is_at_console (dbus_uid_t uid,
845 return _dbus_is_console_user (uid, error);
850 * Checks to see if the UNIX user ID matches the UID of
851 * the process. Should always return #FALSE on Windows.
853 * @param uid the UNIX user ID
854 * @returns #TRUE if this uid owns the process.
857 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
859 return uid == _dbus_getuid ();
863 * Checks to see if the Windows user SID matches the owner of
864 * the process. Should always return #FALSE on UNIX.
866 * @param windows_sid the Windows user SID
867 * @returns #TRUE if this user owns the process.
870 _dbus_windows_user_is_process_owner (const char *windows_sid)
875 /** @} */ /* End of DBusInternalsUtils functions */
878 * @addtogroup DBusString
883 * Get the directory name from a complete filename
884 * @param filename the filename
885 * @param dirname string to append directory name to
886 * @returns #FALSE if no memory
889 _dbus_string_get_dirname (const DBusString *filename,
894 _dbus_assert (filename != dirname);
895 _dbus_assert (filename != NULL);
896 _dbus_assert (dirname != NULL);
898 /* Ignore any separators on the end */
899 sep = _dbus_string_get_length (filename);
901 return _dbus_string_append (dirname, "."); /* empty string passed in */
903 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
906 _dbus_assert (sep >= 0);
909 return _dbus_string_append (dirname, "/");
911 /* Now find the previous separator */
912 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
914 return _dbus_string_append (dirname, ".");
916 /* skip multiple separators */
917 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
920 _dbus_assert (sep >= 0);
923 _dbus_string_get_byte (filename, 0) == '/')
924 return _dbus_string_append (dirname, "/");
926 return _dbus_string_copy_len (filename, 0, sep - 0,
927 dirname, _dbus_string_get_length (dirname));
929 /** @} */ /* DBusString stuff */