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_fd file descriptor 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,
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_fd >= 0)
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_write_socket (print_pid_fd, &pid, 0, bytes) != bytes)
162 dbus_set_error (error, DBUS_ERROR_FAILED,
163 "Printing message bus PID: %s\n",
164 _dbus_strerror (errno));
165 _dbus_string_free (&pid);
166 kill (child_pid, SIGTERM);
170 _dbus_string_free (&pid);
172 _dbus_verbose ("parent exiting\n");
177 _dbus_verbose ("calling setsid()\n");
179 _dbus_assert_not_reached ("setsid() failed");
186 * Creates a file containing the process ID.
188 * @param filename the filename to write to
189 * @param pid our process ID
190 * @param error return location for errors
191 * @returns #FALSE on failure
194 _dbus_write_pid_file (const DBusString *filename,
198 const char *cfilename;
202 cfilename = _dbus_string_get_const_data (filename);
204 fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
208 dbus_set_error (error, _dbus_error_from_errno (errno),
209 "Failed to open \"%s\": %s", cfilename,
210 _dbus_strerror (errno));
214 if ((f = fdopen (fd, "w")) == NULL)
216 dbus_set_error (error, _dbus_error_from_errno (errno),
217 "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
218 _dbus_close (fd, NULL);
222 if (fprintf (f, "%lu\n", pid) < 0)
224 dbus_set_error (error, _dbus_error_from_errno (errno),
225 "Failed to write to \"%s\": %s", cfilename,
226 _dbus_strerror (errno));
232 if (fclose (f) == EOF)
234 dbus_set_error (error, _dbus_error_from_errno (errno),
235 "Failed to close \"%s\": %s", cfilename,
236 _dbus_strerror (errno));
245 * Changes the user and group the bus is running as.
247 * @param uid the new user ID
248 * @param gid the new group ID
249 * @param error return location for errors
250 * @returns #FALSE on failure
253 _dbus_change_identity (dbus_uid_t uid,
257 /* setgroups() only works if we are a privileged process,
258 * so we don't return error on failure; the only possible
259 * failure is that we don't have perms to do it.
261 * not sure this is right, maybe if setuid()
262 * is going to work then setgroups() should also work.
264 if (setgroups (0, NULL) < 0)
265 _dbus_warn ("Failed to drop supplementary groups: %s\n",
266 _dbus_strerror (errno));
268 /* Set GID first, or the setuid may remove our permission
271 if (setgid (gid) < 0)
273 dbus_set_error (error, _dbus_error_from_errno (errno),
274 "Failed to set GID to %lu: %s", gid,
275 _dbus_strerror (errno));
279 if (setuid (uid) < 0)
281 dbus_set_error (error, _dbus_error_from_errno (errno),
282 "Failed to set UID to %lu: %s", uid,
283 _dbus_strerror (errno));
290 /** Installs a UNIX signal handler
292 * @param sig the signal to handle
293 * @param handler the handler
296 _dbus_set_signal_handler (int sig,
297 DBusSignalHandler handler)
299 struct sigaction act;
302 sigemptyset (&empty_mask);
303 act.sa_handler = handler;
304 act.sa_mask = empty_mask;
306 sigaction (sig, &act, NULL);
311 * Removes a directory; Directory must be empty
313 * @param filename directory filename
314 * @param error initialized error object
315 * @returns #TRUE on success
318 _dbus_delete_directory (const DBusString *filename,
321 const char *filename_c;
323 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
325 filename_c = _dbus_string_get_const_data (filename);
327 if (rmdir (filename_c) != 0)
329 dbus_set_error (error, DBUS_ERROR_FAILED,
330 "Failed to remove directory %s: %s\n",
331 filename_c, _dbus_strerror (errno));
338 /** Checks if a file exists
340 * @param file full path to the file
341 * @returns #TRUE if file exists
344 _dbus_file_exists (const char *file)
346 return (access (file, F_OK) == 0);
349 /** Checks if user is at the console
351 * @param username user to check
352 * @param error return location for errors
353 * @returns #TRUE is the user is at the consolei and there are no errors
356 _dbus_user_at_console (const char *username,
364 if (!_dbus_string_init (&f))
366 _DBUS_SET_OOM (error);
370 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
372 _DBUS_SET_OOM (error);
377 if (!_dbus_string_append (&f, username))
379 _DBUS_SET_OOM (error);
383 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
386 _dbus_string_free (&f);
393 * Checks whether the filename is an absolute path
395 * @param filename the filename
396 * @returns #TRUE if an absolute path
399 _dbus_path_is_absolute (const DBusString *filename)
401 if (_dbus_string_get_length (filename) > 0)
402 return _dbus_string_get_byte (filename, 0) == '/';
410 * @param filename the filename to stat
411 * @param statbuf the stat info to fill in
412 * @param error return location for error
413 * @returns #FALSE if error was set
416 _dbus_stat (const DBusString *filename,
420 const char *filename_c;
423 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
425 filename_c = _dbus_string_get_const_data (filename);
427 if (stat (filename_c, &sb) < 0)
429 dbus_set_error (error, _dbus_error_from_errno (errno),
430 "%s", _dbus_strerror (errno));
434 statbuf->mode = sb.st_mode;
435 statbuf->nlink = sb.st_nlink;
436 statbuf->uid = sb.st_uid;
437 statbuf->gid = sb.st_gid;
438 statbuf->size = sb.st_size;
439 statbuf->atime = sb.st_atime;
440 statbuf->mtime = sb.st_mtime;
441 statbuf->ctime = sb.st_ctime;
448 * Internals of directory iterator
452 DIR *d; /**< The DIR* from opendir() */
457 * Open a directory to iterate over.
459 * @param filename the directory name
460 * @param error exception return object or #NULL
461 * @returns new iterator, or #NULL on error
464 _dbus_directory_open (const DBusString *filename,
469 const char *filename_c;
471 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
473 filename_c = _dbus_string_get_const_data (filename);
475 d = opendir (filename_c);
478 dbus_set_error (error, _dbus_error_from_errno (errno),
479 "Failed to read directory \"%s\": %s",
481 _dbus_strerror (errno));
484 iter = dbus_new0 (DBusDirIter, 1);
488 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
489 "Could not allocate memory for directory iterator");
498 /* Calculate the required buffer size (in bytes) for directory
499 * entries read from the given directory handle. Return -1 if this
500 * this cannot be done.
502 * If you use autoconf, include fpathconf and dirfd in your
503 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
504 * and use them where available.
507 dirent_buf_size(DIR * dirp, size_t *size)
510 # if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
511 # if defined(HAVE_DIRFD)
512 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
514 name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
515 # endif /* HAVE_DIRFD */
517 # if defined(NAME_MAX)
522 # elif defined(MAXNAMELEN)
523 name_max = MAXNAMELEN;
525 # if defined(NAME_MAX)
528 # error "buffer size for readdir_r cannot be determined"
532 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
540 * Get next file in the directory. Will not return "." or ".." on
541 * UNIX. If an error occurs, the contents of "filename" are
542 * undefined. The error is never set if the function succeeds.
544 * @param iter the iterator
545 * @param filename string to be set to the next file in the dir
546 * @param error return location for error
547 * @returns #TRUE if filename was filled in with a new filename
550 _dbus_directory_get_next_file (DBusDirIter *iter,
551 DBusString *filename,
554 struct dirent *d, *ent;
558 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
560 if (!dirent_buf_size (iter->d, &buf_size))
562 dbus_set_error (error, DBUS_ERROR_FAILED,
563 "Can't calculate buffer size when reading directory");
567 d = (struct dirent *)dbus_malloc (buf_size);
570 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
571 "No memory to read directory entry");
576 err = readdir_r (iter->d, d, &ent);
580 dbus_set_error (error,
581 _dbus_error_from_errno (err),
582 "%s", _dbus_strerror (err));
587 else if (ent->d_name[0] == '.' &&
588 (ent->d_name[1] == '\0' ||
589 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
593 _dbus_string_set_length (filename, 0);
594 if (!_dbus_string_append (filename, ent->d_name))
596 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
597 "No memory to read directory entry");
610 * Closes a directory iteration.
613 _dbus_directory_close (DBusDirIter *iter)
620 fill_user_info_from_group (struct group *g,
624 _dbus_assert (g->gr_name != NULL);
626 info->gid = g->gr_gid;
627 info->groupname = _dbus_strdup (g->gr_name);
629 /* info->members = dbus_strdupv (g->gr_mem) */
631 if (info->groupname == NULL)
633 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
641 fill_group_info (DBusGroupInfo *info,
643 const DBusString *groupname,
646 const char *group_c_str;
648 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
649 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
652 group_c_str = _dbus_string_get_const_data (groupname);
656 /* For now assuming that the getgrnam() and getgrgid() flavors
657 * always correspond to the pwnam flavors, if not we have
658 * to add more configure checks.
661 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
669 #ifdef HAVE_POSIX_GETPWNAM_R
672 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
675 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
678 g = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
680 #endif /* !HAVE_POSIX_GETPWNAM_R */
681 if (result == 0 && g == &g_str)
683 return fill_user_info_from_group (g, info, error);
687 dbus_set_error (error, _dbus_error_from_errno (errno),
688 "Group %s unknown or failed to look it up\n",
689 group_c_str ? group_c_str : "???");
693 #else /* ! HAVE_GETPWNAM_R */
695 /* I guess we're screwed on thread safety here */
698 g = getgrnam (group_c_str);
702 return fill_user_info_from_group (g, info, error);
706 dbus_set_error (error, _dbus_error_from_errno (errno),
707 "Group %s unknown or failed to look it up\n",
708 group_c_str ? group_c_str : "???");
712 #endif /* ! HAVE_GETPWNAM_R */
716 * Initializes the given DBusGroupInfo struct
717 * with information about the given group name.
719 * @param info the group info struct
720 * @param groupname name of group
721 * @param error the error return
722 * @returns #FALSE if error is set
725 _dbus_group_info_fill (DBusGroupInfo *info,
726 const DBusString *groupname,
729 return fill_group_info (info, DBUS_GID_UNSET,
735 * Initializes the given DBusGroupInfo struct
736 * with information about the given group ID.
738 * @param info the group info struct
739 * @param gid group ID
740 * @param error the error return
741 * @returns #FALSE if error is set
744 _dbus_group_info_fill_gid (DBusGroupInfo *info,
748 return fill_group_info (info, gid, NULL, error);
751 /** @} */ /* End of DBusInternalsUtils functions */
754 * @addtogroup DBusString
759 * Get the directory name from a complete filename
760 * @param filename the filename
761 * @param dirname string to append directory name to
762 * @returns #FALSE if no memory
765 _dbus_string_get_dirname (const DBusString *filename,
770 _dbus_assert (filename != dirname);
771 _dbus_assert (filename != NULL);
772 _dbus_assert (dirname != NULL);
774 /* Ignore any separators on the end */
775 sep = _dbus_string_get_length (filename);
777 return _dbus_string_append (dirname, "."); /* empty string passed in */
779 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
782 _dbus_assert (sep >= 0);
785 return _dbus_string_append (dirname, "/");
787 /* Now find the previous separator */
788 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
790 return _dbus_string_append (dirname, ".");
792 /* skip multiple separators */
793 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
796 _dbus_assert (sep >= 0);
799 _dbus_string_get_byte (filename, 0) == '/')
800 return _dbus_string_append (dirname, "/");
802 return _dbus_string_copy_len (filename, 0, sep - 0,
803 dirname, _dbus_string_get_length (dirname));
805 /** @} */ /* DBusString stuff */