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>
46 #include <sys/socket.h>
51 #ifdef HAVE_SYS_SYSLIMITS_H
52 #include <sys/syslimits.h>
60 * @addtogroup DBusInternalsUtils
66 * Does the chdir, fork, setsid, etc. to become a daemon process.
68 * @param pidfile #NULL, or pidfile to create
69 * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
70 * @param error return location for errors
71 * @param keep_umask #TRUE to keep the original umask
72 * @returns #FALSE on failure
75 _dbus_become_daemon (const DBusString *pidfile,
76 DBusPipe *print_pid_pipe,
78 dbus_bool_t keep_umask)
84 _dbus_verbose ("Becoming a daemon...\n");
86 _dbus_verbose ("chdir to /\n");
89 dbus_set_error (error, DBUS_ERROR_FAILED,
90 "Could not chdir() to root directory");
94 _dbus_verbose ("forking...\n");
95 switch ((child_pid = fork ()))
98 _dbus_verbose ("fork failed\n");
99 dbus_set_error (error, _dbus_error_from_errno (errno),
100 "Failed to fork daemon: %s", _dbus_strerror (errno));
105 _dbus_verbose ("in child, closing std file descriptors\n");
107 /* silently ignore failures here, if someone
108 * doesn't have /dev/null we may as well try
112 dev_null_fd = open ("/dev/null", O_RDWR);
113 if (dev_null_fd >= 0)
115 dup2 (dev_null_fd, 0);
116 dup2 (dev_null_fd, 1);
118 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
119 if (s == NULL || *s == '\0')
120 dup2 (dev_null_fd, 2);
122 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
127 /* Get a predictable umask */
128 _dbus_verbose ("setting umask\n");
132 _dbus_verbose ("calling setsid()\n");
134 _dbus_assert_not_reached ("setsid() failed");
139 if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
142 _dbus_verbose ("pid file or pipe write failed: %s\n",
144 kill (child_pid, SIGTERM);
148 _dbus_verbose ("parent exiting\n");
158 * Creates a file containing the process ID.
160 * @param filename the filename to write to
161 * @param pid our process ID
162 * @param error return location for errors
163 * @returns #FALSE on failure
166 _dbus_write_pid_file (const DBusString *filename,
170 const char *cfilename;
174 cfilename = _dbus_string_get_const_data (filename);
176 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
180 dbus_set_error (error, _dbus_error_from_errno (errno),
181 "Failed to open \"%s\": %s", cfilename,
182 _dbus_strerror (errno));
186 if ((f = fdopen (fd, "w")) == NULL)
188 dbus_set_error (error, _dbus_error_from_errno (errno),
189 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
190 _dbus_close (fd, NULL);
194 if (fprintf (f, "%lu\n", pid) < 0)
196 dbus_set_error (error, _dbus_error_from_errno (errno),
197 "Failed to write to \"%s\": %s", cfilename,
198 _dbus_strerror (errno));
204 if (fclose (f) == EOF)
206 dbus_set_error (error, _dbus_error_from_errno (errno),
207 "Failed to close \"%s\": %s", cfilename,
208 _dbus_strerror (errno));
216 * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
217 * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
220 * @param pidfile the file to write to or #NULL
221 * @param print_pid_pipe the pipe to write to or #NULL
222 * @param pid_to_write the pid to write out
223 * @param error error on failure
224 * @returns FALSE if error is set
227 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
228 DBusPipe *print_pid_pipe,
229 dbus_pid_t pid_to_write,
234 _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
235 if (!_dbus_write_pid_file (pidfile,
239 _dbus_verbose ("pid file write failed\n");
240 _DBUS_ASSERT_ERROR_IS_SET(error);
246 _dbus_verbose ("No pid file requested\n");
249 if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
254 _dbus_verbose ("writing our pid to pipe %"PRIuPTR"\n",
255 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 /* The HAVE_LIBAUDIT case lives in selinux.c */
312 #ifndef HAVE_LIBAUDIT
314 * Changes the user and group the bus is running as.
316 * @param user the user to become
317 * @param error return location for errors
318 * @returns #FALSE on failure
321 _dbus_change_to_daemon_user (const char *user,
328 _dbus_string_init_const (&u, user);
330 if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
332 dbus_set_error (error, DBUS_ERROR_FAILED,
333 "User '%s' does not appear to exist?",
338 /* setgroups() only works if we are a privileged process,
339 * so we don't return error on failure; the only possible
340 * failure is that we don't have perms to do it.
342 * not sure this is right, maybe if setuid()
343 * is going to work then setgroups() should also work.
345 if (setgroups (0, NULL) < 0)
346 _dbus_warn ("Failed to drop supplementary groups: %s\n",
347 _dbus_strerror (errno));
349 /* Set GID first, or the setuid may remove our permission
352 if (setgid (gid) < 0)
354 dbus_set_error (error, _dbus_error_from_errno (errno),
355 "Failed to set GID to %lu: %s", gid,
356 _dbus_strerror (errno));
360 if (setuid (uid) < 0)
362 dbus_set_error (error, _dbus_error_from_errno (errno),
363 "Failed to set UID to %lu: %s", uid,
364 _dbus_strerror (errno));
370 #endif /* !HAVE_LIBAUDIT */
373 _dbus_init_system_log (void)
375 openlog ("dbus", LOG_PID, LOG_DAEMON);
378 * Log a message to the system log file (e.g. syslog on Unix).
380 * @param severity a severity value
381 * @param msg a printf-style format string
382 * @param args arguments for the format string
386 _dbus_system_log (DBusSystemLogSeverity severity, const char *msg, ...)
390 va_start (args, msg);
392 _dbus_system_logv (severity, msg, args);
398 * Log a message to the system log file (e.g. syslog on Unix).
400 * @param severity a severity value
401 * @param msg a printf-style format string
402 * @param args arguments for the format string
404 * If the FATAL severity is given, this function will terminate the program
405 * with an error code.
408 _dbus_system_logv (DBusSystemLogSeverity severity, const char *msg, va_list args)
413 case DBUS_SYSTEM_LOG_INFO:
414 flags = LOG_DAEMON | LOG_NOTICE;
416 case DBUS_SYSTEM_LOG_SECURITY:
417 flags = LOG_AUTH | LOG_NOTICE;
419 case DBUS_SYSTEM_LOG_FATAL:
420 flags = LOG_DAEMON|LOG_CRIT;
426 vsyslog (flags, msg, args);
428 if (severity == DBUS_SYSTEM_LOG_FATAL)
432 /** Installs a UNIX signal handler
434 * @param sig the signal to handle
435 * @param handler the handler
438 _dbus_set_signal_handler (int sig,
439 DBusSignalHandler handler)
441 struct sigaction act;
444 sigemptyset (&empty_mask);
445 act.sa_handler = handler;
446 act.sa_mask = empty_mask;
448 sigaction (sig, &act, NULL);
451 /** Checks if a file exists
453 * @param file full path to the file
454 * @returns #TRUE if file exists
457 _dbus_file_exists (const char *file)
459 return (access (file, F_OK) == 0);
462 /** Checks if user is at the console
464 * @param username user to check
465 * @param error return location for errors
466 * @returns #TRUE is the user is at the consolei and there are no errors
469 _dbus_user_at_console (const char *username,
477 if (!_dbus_string_init (&f))
479 _DBUS_SET_OOM (error);
483 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
485 _DBUS_SET_OOM (error);
490 if (!_dbus_string_append (&f, username))
492 _DBUS_SET_OOM (error);
496 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
499 _dbus_string_free (&f);
506 * Checks whether the filename is an absolute path
508 * @param filename the filename
509 * @returns #TRUE if an absolute path
512 _dbus_path_is_absolute (const DBusString *filename)
514 if (_dbus_string_get_length (filename) > 0)
515 return _dbus_string_get_byte (filename, 0) == '/';
523 * @param filename the filename to stat
524 * @param statbuf the stat info to fill in
525 * @param error return location for error
526 * @returns #FALSE if error was set
529 _dbus_stat (const DBusString *filename,
533 const char *filename_c;
536 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
538 filename_c = _dbus_string_get_const_data (filename);
540 if (stat (filename_c, &sb) < 0)
542 dbus_set_error (error, _dbus_error_from_errno (errno),
543 "%s", _dbus_strerror (errno));
547 statbuf->mode = sb.st_mode;
548 statbuf->nlink = sb.st_nlink;
549 statbuf->uid = sb.st_uid;
550 statbuf->gid = sb.st_gid;
551 statbuf->size = sb.st_size;
552 statbuf->atime = sb.st_atime;
553 statbuf->mtime = sb.st_mtime;
554 statbuf->ctime = sb.st_ctime;
561 * Internals of directory iterator
565 DIR *d; /**< The DIR* from opendir() */
570 * Open a directory to iterate over.
572 * @param filename the directory name
573 * @param error exception return object or #NULL
574 * @returns new iterator, or #NULL on error
577 _dbus_directory_open (const DBusString *filename,
582 const char *filename_c;
584 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
586 filename_c = _dbus_string_get_const_data (filename);
588 d = opendir (filename_c);
591 dbus_set_error (error, _dbus_error_from_errno (errno),
592 "Failed to read directory \"%s\": %s",
594 _dbus_strerror (errno));
597 iter = dbus_new0 (DBusDirIter, 1);
601 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
602 "Could not allocate memory for directory iterator");
612 * Get next file in the directory. Will not return "." or ".." on
613 * UNIX. If an error occurs, the contents of "filename" are
614 * undefined. The error is never set if the function succeeds.
616 * This function is not re-entrant, and not necessarily thread-safe.
617 * Only use it for test code or single-threaded utilities.
619 * @param iter the iterator
620 * @param filename string to be set to the next file in the dir
621 * @param error return location for error
622 * @returns #TRUE if filename was filled in with a new filename
625 _dbus_directory_get_next_file (DBusDirIter *iter,
626 DBusString *filename,
632 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
636 ent = readdir (iter->d);
643 dbus_set_error (error,
644 _dbus_error_from_errno (err),
645 "%s", _dbus_strerror (err));
649 else if (ent->d_name[0] == '.' &&
650 (ent->d_name[1] == '\0' ||
651 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
655 _dbus_string_set_length (filename, 0);
656 if (!_dbus_string_append (filename, ent->d_name))
658 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
659 "No memory to read directory entry");
670 * Closes a directory iteration.
673 _dbus_directory_close (DBusDirIter *iter)
680 fill_user_info_from_group (struct group *g,
684 _dbus_assert (g->gr_name != NULL);
686 info->gid = g->gr_gid;
687 info->groupname = _dbus_strdup (g->gr_name);
689 /* info->members = dbus_strdupv (g->gr_mem) */
691 if (info->groupname == NULL)
693 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
701 fill_group_info (DBusGroupInfo *info,
703 const DBusString *groupname,
706 const char *group_c_str;
708 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
709 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
712 group_c_str = _dbus_string_get_const_data (groupname);
716 /* For now assuming that the getgrnam() and getgrgid() flavors
717 * always correspond to the pwnam flavors, if not we have
718 * to add more configure checks.
721 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
730 /* retrieve maximum needed size for buf */
731 buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
733 /* sysconf actually returns a long, but everything else expects size_t,
734 * so just recast here.
735 * https://bugs.freedesktop.org/show_bug.cgi?id=17061
737 if ((long) buflen <= 0)
743 buf = dbus_malloc (buflen);
746 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
751 #ifdef HAVE_POSIX_GETPWNAM_R
753 result = getgrnam_r (group_c_str, &g_str, buf, buflen,
756 result = getgrgid_r (gid, &g_str, buf, buflen,
759 g = getgrnam_r (group_c_str, &g_str, buf, buflen);
761 #endif /* !HAVE_POSIX_GETPWNAM_R */
762 /* Try a bigger buffer if ERANGE was returned:
763 https://bugs.freedesktop.org/show_bug.cgi?id=16727
765 if (result == ERANGE && buflen < 512 * 1024)
776 if (result == 0 && g == &g_str)
778 b = fill_user_info_from_group (g, info, error);
784 dbus_set_error (error, _dbus_error_from_errno (errno),
785 "Group %s unknown or failed to look it up\n",
786 group_c_str ? group_c_str : "???");
791 #else /* ! HAVE_GETPWNAM_R */
793 /* I guess we're screwed on thread safety here */
796 g = getgrnam (group_c_str);
800 return fill_user_info_from_group (g, info, error);
804 dbus_set_error (error, _dbus_error_from_errno (errno),
805 "Group %s unknown or failed to look it up\n",
806 group_c_str ? group_c_str : "???");
810 #endif /* ! HAVE_GETPWNAM_R */
814 * Initializes the given DBusGroupInfo struct
815 * with information about the given group name.
817 * @param info the group info struct
818 * @param groupname name of group
819 * @param error the error return
820 * @returns #FALSE if error is set
823 _dbus_group_info_fill (DBusGroupInfo *info,
824 const DBusString *groupname,
827 return fill_group_info (info, DBUS_GID_UNSET,
833 * Initializes the given DBusGroupInfo struct
834 * with information about the given group ID.
836 * @param info the group info struct
837 * @param gid group ID
838 * @param error the error return
839 * @returns #FALSE if error is set
842 _dbus_group_info_fill_gid (DBusGroupInfo *info,
846 return fill_group_info (info, gid, NULL, error);
850 * Parse a UNIX user from the bus config file. On Windows, this should
851 * simply always fail (just return #FALSE).
853 * @param username the username text
854 * @param uid_p place to return the uid
855 * @returns #TRUE on success
858 _dbus_parse_unix_user_from_config (const DBusString *username,
861 return _dbus_get_user_id (username, uid_p);
866 * Parse a UNIX group from the bus config file. On Windows, this should
867 * simply always fail (just return #FALSE).
869 * @param groupname the groupname text
870 * @param gid_p place to return the gid
871 * @returns #TRUE on success
874 _dbus_parse_unix_group_from_config (const DBusString *groupname,
877 return _dbus_get_group_id (groupname, gid_p);
881 * Gets all groups corresponding to the given UNIX user ID. On UNIX,
882 * just calls _dbus_groups_from_uid(). On Windows, should always
883 * fail since we don't know any UNIX groups.
886 * @param group_ids return location for array of group IDs
887 * @param n_group_ids return location for length of returned array
888 * @returns #TRUE if the UID existed and we got some credentials
891 _dbus_unix_groups_from_uid (dbus_uid_t uid,
892 dbus_gid_t **group_ids,
895 return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
899 * Checks to see if the UNIX user ID is at the console.
900 * Should always fail on Windows (set the error to
901 * #DBUS_ERROR_NOT_SUPPORTED).
903 * @param uid UID of person to check
904 * @param error return location for errors
905 * @returns #TRUE if the UID is the same as the console user and there are no errors
908 _dbus_unix_user_is_at_console (dbus_uid_t uid,
911 return _dbus_is_console_user (uid, error);
916 * Checks to see if the UNIX user ID matches the UID of
917 * the process. Should always return #FALSE on Windows.
919 * @param uid the UNIX user ID
920 * @returns #TRUE if this uid owns the process.
923 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
925 return uid == _dbus_geteuid ();
929 * Checks to see if the Windows user SID matches the owner of
930 * the process. Should always return #FALSE on UNIX.
932 * @param windows_sid the Windows user SID
933 * @returns #TRUE if this user owns the process.
936 _dbus_windows_user_is_process_owner (const char *windows_sid)
941 /** @} */ /* End of DBusInternalsUtils functions */
944 * @addtogroup DBusString
949 * Get the directory name from a complete filename
950 * @param filename the filename
951 * @param dirname string to append directory name to
952 * @returns #FALSE if no memory
955 _dbus_string_get_dirname (const DBusString *filename,
960 _dbus_assert (filename != dirname);
961 _dbus_assert (filename != NULL);
962 _dbus_assert (dirname != NULL);
964 /* Ignore any separators on the end */
965 sep = _dbus_string_get_length (filename);
967 return _dbus_string_append (dirname, "."); /* empty string passed in */
969 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
972 _dbus_assert (sep >= 0);
975 return _dbus_string_append (dirname, "/");
977 /* Now find the previous separator */
978 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
980 return _dbus_string_append (dirname, ".");
982 /* skip multiple separators */
983 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
986 _dbus_assert (sep >= 0);
989 _dbus_string_get_byte (filename, 0) == '/')
990 return _dbus_string_append (dirname, "/");
992 return _dbus_string_copy_len (filename, 0, sep - 0,
993 dirname, _dbus_string_get_length (dirname));
995 /** @} */ /* DBusString stuff */
998 string_squash_nonprintable (DBusString *str)
1003 buf = _dbus_string_get_data (str);
1004 len = _dbus_string_get_length (str);
1006 for (i = 0; i < len; i++)
1008 unsigned char c = (unsigned char) buf[i];
1011 else if (c < 0x20 || c > 127)
1017 * Get a printable string describing the command used to execute
1018 * the process with pid. This string should only be used for
1019 * informative purposes such as logging; it may not be trusted.
1021 * The command is guaranteed to be printable ASCII and no longer
1024 * @param pid Process id
1025 * @param str Append command to this string
1026 * @param max_len Maximum length of returned command
1027 * @param error return location for errors
1028 * @returns #FALSE on error
1031 _dbus_command_for_pid (unsigned long pid,
1036 /* This is all Linux-specific for now */
1041 if (!_dbus_string_init (&path))
1043 _DBUS_SET_OOM (error);
1047 if (!_dbus_string_init (&cmdline))
1049 _DBUS_SET_OOM (error);
1050 _dbus_string_free (&path);
1054 if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1057 fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1060 dbus_set_error (error,
1061 _dbus_error_from_errno (errno),
1062 "Failed to open \"%s\": %s",
1063 _dbus_string_get_const_data (&path),
1064 _dbus_strerror (errno));
1068 if (!_dbus_read (fd, &cmdline, max_len))
1070 dbus_set_error (error,
1071 _dbus_error_from_errno (errno),
1072 "Failed to read from \"%s\": %s",
1073 _dbus_string_get_const_data (&path),
1074 _dbus_strerror (errno));
1078 if (!_dbus_close (fd, error))
1081 string_squash_nonprintable (&cmdline);
1083 if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1086 _dbus_string_free (&cmdline);
1087 _dbus_string_free (&path);
1090 _DBUS_SET_OOM (error);
1092 _dbus_string_free (&cmdline);
1093 _dbus_string_free (&path);