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>
52 * @addtogroup DBusInternalsUtils
57 * Does the chdir, fork, setsid, etc. to become a daemon process.
59 * @param pidfile #NULL, or pidfile to create
60 * @param print_pid_fd file descriptor to print daemon's pid to, or -1 for none
61 * @param error return location for errors
62 * @returns #FALSE on failure
65 _dbus_become_daemon (const DBusString *pidfile,
73 _dbus_verbose ("Becoming a daemon...\n");
75 _dbus_verbose ("chdir to /\n");
78 dbus_set_error (error, DBUS_ERROR_FAILED,
79 "Could not chdir() to root directory");
83 _dbus_verbose ("forking...\n");
84 switch ((child_pid = fork ()))
87 _dbus_verbose ("fork failed\n");
88 dbus_set_error (error, _dbus_error_from_errno (errno),
89 "Failed to fork daemon: %s", _dbus_strerror (errno));
94 _dbus_verbose ("in child, closing std file descriptors\n");
96 /* silently ignore failures here, if someone
97 * doesn't have /dev/null we may as well try
101 dev_null_fd = open ("/dev/null", O_RDWR);
102 if (dev_null_fd >= 0)
104 dup2 (dev_null_fd, 0);
105 dup2 (dev_null_fd, 1);
107 s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
108 if (s == NULL || *s == '\0')
109 dup2 (dev_null_fd, 2);
111 _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
114 /* Get a predictable umask */
115 _dbus_verbose ("setting umask\n");
122 _dbus_verbose ("parent writing pid file\n");
123 if (!_dbus_write_pid_file (pidfile,
127 _dbus_verbose ("pid file write failed, killing child\n");
128 kill (child_pid, SIGTERM);
133 /* Write PID if requested */
134 if (print_pid_fd >= 0)
139 if (!_dbus_string_init (&pid))
141 _DBUS_SET_OOM (error);
142 kill (child_pid, SIGTERM);
146 if (!_dbus_string_append_int (&pid, child_pid) ||
147 !_dbus_string_append (&pid, "\n"))
149 _dbus_string_free (&pid);
150 _DBUS_SET_OOM (error);
151 kill (child_pid, SIGTERM);
155 bytes = _dbus_string_get_length (&pid);
156 if (_dbus_write_socket (print_pid_fd, &pid, 0, bytes) != bytes)
158 dbus_set_error (error, DBUS_ERROR_FAILED,
159 "Printing message bus PID: %s\n",
160 _dbus_strerror (errno));
161 _dbus_string_free (&pid);
162 kill (child_pid, SIGTERM);
166 _dbus_string_free (&pid);
168 _dbus_verbose ("parent exiting\n");
173 _dbus_verbose ("calling setsid()\n");
175 _dbus_assert_not_reached ("setsid() failed");
182 * Creates a file containing the process ID.
184 * @param filename the filename to write to
185 * @param pid our process ID
186 * @param error return location for errors
187 * @returns #FALSE on failure
190 _dbus_write_pid_file (const DBusString *filename,
194 const char *cfilename;
198 cfilename = _dbus_string_get_const_data (filename);
200 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
204 dbus_set_error (error, _dbus_error_from_errno (errno),
205 "Failed to open \"%s\": %s", cfilename,
206 _dbus_strerror (errno));
210 if ((f = fdopen (fd, "w")) == NULL)
212 dbus_set_error (error, _dbus_error_from_errno (errno),
213 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
214 _dbus_close (fd, NULL);
218 if (fprintf (f, "%lu\n", pid) < 0)
220 dbus_set_error (error, _dbus_error_from_errno (errno),
221 "Failed to write to \"%s\": %s", cfilename,
222 _dbus_strerror (errno));
228 if (fclose (f) == EOF)
230 dbus_set_error (error, _dbus_error_from_errno (errno),
231 "Failed to close \"%s\": %s", cfilename,
232 _dbus_strerror (errno));
241 * Changes the user and group the bus is running as.
243 * @param uid the new user ID
244 * @param gid the new group ID
245 * @param error return location for errors
246 * @returns #FALSE on failure
249 _dbus_change_identity (dbus_uid_t uid,
253 /* setgroups() only works if we are a privileged process,
254 * so we don't return error on failure; the only possible
255 * failure is that we don't have perms to do it.
257 * not sure this is right, maybe if setuid()
258 * is going to work then setgroups() should also work.
260 if (setgroups (0, NULL) < 0)
261 _dbus_warn ("Failed to drop supplementary groups: %s\n",
262 _dbus_strerror (errno));
264 /* Set GID first, or the setuid may remove our permission
267 if (setgid (gid) < 0)
269 dbus_set_error (error, _dbus_error_from_errno (errno),
270 "Failed to set GID to %lu: %s", gid,
271 _dbus_strerror (errno));
275 if (setuid (uid) < 0)
277 dbus_set_error (error, _dbus_error_from_errno (errno),
278 "Failed to set UID to %lu: %s", uid,
279 _dbus_strerror (errno));
286 /** Installs a UNIX signal handler
288 * @param sig the signal to handle
289 * @param handler the handler
292 _dbus_set_signal_handler (int sig,
293 DBusSignalHandler handler)
295 struct sigaction act;
298 sigemptyset (&empty_mask);
299 act.sa_handler = handler;
300 act.sa_mask = empty_mask;
302 sigaction (sig, &act, NULL);
307 * Removes a directory; Directory must be empty
309 * @param filename directory filename
310 * @param error initialized error object
311 * @returns #TRUE on success
314 _dbus_delete_directory (const DBusString *filename,
317 const char *filename_c;
319 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
321 filename_c = _dbus_string_get_const_data (filename);
323 if (rmdir (filename_c) != 0)
325 dbus_set_error (error, DBUS_ERROR_FAILED,
326 "Failed to remove directory %s: %s\n",
327 filename_c, _dbus_strerror (errno));
334 /** Checks if a file exists
336 * @param file full path to the file
337 * @returns #TRUE if file exists
340 _dbus_file_exists (const char *file)
342 return (access (file, F_OK) == 0);
345 /** Checks if user is at the console
347 * @param username user to check
348 * @param error return location for errors
349 * @returns #TRUE is the user is at the consolei and there are no errors
352 _dbus_user_at_console (const char *username,
360 if (!_dbus_string_init (&f))
362 _DBUS_SET_OOM (error);
366 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
368 _DBUS_SET_OOM (error);
373 if (!_dbus_string_append (&f, username))
375 _DBUS_SET_OOM (error);
379 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
382 _dbus_string_free (&f);
389 * Checks whether the filename is an absolute path
391 * @param filename the filename
392 * @returns #TRUE if an absolute path
395 _dbus_path_is_absolute (const DBusString *filename)
397 if (_dbus_string_get_length (filename) > 0)
398 return _dbus_string_get_byte (filename, 0) == '/';
406 * @param filename the filename to stat
407 * @param statbuf the stat info to fill in
408 * @param error return location for error
409 * @returns #FALSE if error was set
412 _dbus_stat (const DBusString *filename,
416 const char *filename_c;
419 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
421 filename_c = _dbus_string_get_const_data (filename);
423 if (stat (filename_c, &sb) < 0)
425 dbus_set_error (error, _dbus_error_from_errno (errno),
426 "%s", _dbus_strerror (errno));
430 statbuf->mode = sb.st_mode;
431 statbuf->nlink = sb.st_nlink;
432 statbuf->uid = sb.st_uid;
433 statbuf->gid = sb.st_gid;
434 statbuf->size = sb.st_size;
435 statbuf->atime = sb.st_atime;
436 statbuf->mtime = sb.st_mtime;
437 statbuf->ctime = sb.st_ctime;
444 * Internals of directory iterator
448 DIR *d; /**< The DIR* from opendir() */
453 * Open a directory to iterate over.
455 * @param filename the directory name
456 * @param error exception return object or #NULL
457 * @returns new iterator, or #NULL on error
460 _dbus_directory_open (const DBusString *filename,
465 const char *filename_c;
467 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
469 filename_c = _dbus_string_get_const_data (filename);
471 d = opendir (filename_c);
474 dbus_set_error (error, _dbus_error_from_errno (errno),
475 "Failed to read directory \"%s\": %s",
477 _dbus_strerror (errno));
480 iter = dbus_new0 (DBusDirIter, 1);
484 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
485 "Could not allocate memory for directory iterator");
494 /* Calculate the required buffer size (in bytes) for directory
495 * entries read from the given directory handle. Return -1 if this
496 * this cannot be done.
498 * If you use autoconf, include fpathconf and dirfd in your
499 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
500 * and use them where available.
503 dirent_buf_size(DIR * dirp, size_t *size)
506 # if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \
507 && defined(_PC_NAME_MAX)
508 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
510 # if defined(NAME_MAX)
516 # if defined(NAME_MAX)
519 # error "buffer size for readdir_r cannot be determined"
523 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
531 * Get next file in the directory. Will not return "." or ".." on
532 * UNIX. If an error occurs, the contents of "filename" are
533 * undefined. The error is never set if the function succeeds.
535 * @param iter the iterator
536 * @param filename string to be set to the next file in the dir
537 * @param error return location for error
538 * @returns #TRUE if filename was filled in with a new filename
541 _dbus_directory_get_next_file (DBusDirIter *iter,
542 DBusString *filename,
545 struct dirent *d, *ent;
549 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
551 if (!dirent_buf_size (iter->d, &buf_size))
553 dbus_set_error (error, DBUS_ERROR_FAILED,
554 "Can't calculate buffer size when reading directory");
558 d = (struct dirent *)dbus_malloc (buf_size);
561 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
562 "No memory to read directory entry");
567 err = readdir_r (iter->d, d, &ent);
571 dbus_set_error (error,
572 _dbus_error_from_errno (err),
573 "%s", _dbus_strerror (err));
578 else if (ent->d_name[0] == '.' &&
579 (ent->d_name[1] == '\0' ||
580 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
584 _dbus_string_set_length (filename, 0);
585 if (!_dbus_string_append (filename, ent->d_name))
587 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
588 "No memory to read directory entry");
601 * Closes a directory iteration.
604 _dbus_directory_close (DBusDirIter *iter)
611 fill_user_info_from_group (struct group *g,
615 _dbus_assert (g->gr_name != NULL);
617 info->gid = g->gr_gid;
618 info->groupname = _dbus_strdup (g->gr_name);
620 /* info->members = dbus_strdupv (g->gr_mem) */
622 if (info->groupname == NULL)
624 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
632 fill_group_info (DBusGroupInfo *info,
634 const DBusString *groupname,
637 const char *group_c_str;
639 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
640 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
643 group_c_str = _dbus_string_get_const_data (groupname);
647 /* For now assuming that the getgrnam() and getgrgid() flavors
648 * always correspond to the pwnam flavors, if not we have
649 * to add more configure checks.
652 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
660 #ifdef HAVE_POSIX_GETPWNAM_R
663 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
666 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
669 g = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
671 #endif /* !HAVE_POSIX_GETPWNAM_R */
672 if (result == 0 && g == &g_str)
674 return fill_user_info_from_group (g, info, error);
678 dbus_set_error (error, _dbus_error_from_errno (errno),
679 "Group %s unknown or failed to look it up\n",
680 group_c_str ? group_c_str : "???");
684 #else /* ! HAVE_GETPWNAM_R */
686 /* I guess we're screwed on thread safety here */
689 g = getgrnam (group_c_str);
693 return fill_user_info_from_group (g, info, error);
697 dbus_set_error (error, _dbus_error_from_errno (errno),
698 "Group %s unknown or failed to look it up\n",
699 group_c_str ? group_c_str : "???");
703 #endif /* ! HAVE_GETPWNAM_R */
707 * Initializes the given DBusGroupInfo struct
708 * with information about the given group name.
710 * @param info the group info struct
711 * @param groupname name of group
712 * @param error the error return
713 * @returns #FALSE if error is set
716 _dbus_group_info_fill (DBusGroupInfo *info,
717 const DBusString *groupname,
720 return fill_group_info (info, DBUS_GID_UNSET,
726 * Initializes the given DBusGroupInfo struct
727 * with information about the given group ID.
729 * @param info the group info struct
730 * @param gid group ID
731 * @param error the error return
732 * @returns #FALSE if error is set
735 _dbus_group_info_fill_gid (DBusGroupInfo *info,
739 return fill_group_info (info, gid, NULL, error);
742 /** @} */ /* End of DBusInternalsUtils functions */
745 * @addtogroup DBusString
750 * Get the directory name from a complete filename
751 * @param filename the filename
752 * @param dirname string to append directory name to
753 * @returns #FALSE if no memory
756 _dbus_string_get_dirname (const DBusString *filename,
761 _dbus_assert (filename != dirname);
762 _dbus_assert (filename != NULL);
763 _dbus_assert (dirname != NULL);
765 /* Ignore any separators on the end */
766 sep = _dbus_string_get_length (filename);
768 return _dbus_string_append (dirname, "."); /* empty string passed in */
770 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
773 _dbus_assert (sep >= 0);
776 return _dbus_string_append (dirname, "/");
778 /* Now find the previous separator */
779 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
781 return _dbus_string_append (dirname, ".");
783 /* skip multiple separators */
784 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
787 _dbus_assert (sep >= 0);
790 _dbus_string_get_byte (filename, 0) == '/')
791 return _dbus_string_append (dirname, "/");
793 return _dbus_string_copy_len (filename, 0, sep - 0,
794 dirname, _dbus_string_get_length (dirname));
796 /** @} */ /* DBusString stuff */