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));
248 * Changes the user and group the bus is running as.
250 * @param uid the new user ID
251 * @param gid the new group ID
252 * @param error return location for errors
253 * @returns #FALSE on failure
256 _dbus_change_identity (dbus_uid_t uid,
260 /* setgroups() only works if we are a privileged process,
261 * so we don't return error on failure; the only possible
262 * failure is that we don't have perms to do it.
264 * not sure this is right, maybe if setuid()
265 * is going to work then setgroups() should also work.
267 if (setgroups (0, NULL) < 0)
268 _dbus_warn ("Failed to drop supplementary groups: %s\n",
269 _dbus_strerror (errno));
271 /* Set GID first, or the setuid may remove our permission
274 if (setgid (gid) < 0)
276 dbus_set_error (error, _dbus_error_from_errno (errno),
277 "Failed to set GID to %lu: %s", gid,
278 _dbus_strerror (errno));
282 if (setuid (uid) < 0)
284 dbus_set_error (error, _dbus_error_from_errno (errno),
285 "Failed to set UID to %lu: %s", uid,
286 _dbus_strerror (errno));
293 /** Installs a UNIX signal handler
295 * @param sig the signal to handle
296 * @param handler the handler
299 _dbus_set_signal_handler (int sig,
300 DBusSignalHandler handler)
302 struct sigaction act;
305 sigemptyset (&empty_mask);
306 act.sa_handler = handler;
307 act.sa_mask = empty_mask;
309 sigaction (sig, &act, NULL);
314 * Removes a directory; Directory must be empty
316 * @param filename directory filename
317 * @param error initialized error object
318 * @returns #TRUE on success
321 _dbus_delete_directory (const DBusString *filename,
324 const char *filename_c;
326 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
328 filename_c = _dbus_string_get_const_data (filename);
330 if (rmdir (filename_c) != 0)
332 dbus_set_error (error, DBUS_ERROR_FAILED,
333 "Failed to remove directory %s: %s\n",
334 filename_c, _dbus_strerror (errno));
341 /** Checks if a file exists
343 * @param file full path to the file
344 * @returns #TRUE if file exists
347 _dbus_file_exists (const char *file)
349 return (access (file, F_OK) == 0);
352 /** Checks if user is at the console
354 * @param username user to check
355 * @param error return location for errors
356 * @returns #TRUE is the user is at the consolei and there are no errors
359 _dbus_user_at_console (const char *username,
367 if (!_dbus_string_init (&f))
369 _DBUS_SET_OOM (error);
373 if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
375 _DBUS_SET_OOM (error);
380 if (!_dbus_string_append (&f, username))
382 _DBUS_SET_OOM (error);
386 result = _dbus_file_exists (_dbus_string_get_const_data (&f));
389 _dbus_string_free (&f);
396 * Checks whether the filename is an absolute path
398 * @param filename the filename
399 * @returns #TRUE if an absolute path
402 _dbus_path_is_absolute (const DBusString *filename)
404 if (_dbus_string_get_length (filename) > 0)
405 return _dbus_string_get_byte (filename, 0) == '/';
413 * @param filename the filename to stat
414 * @param statbuf the stat info to fill in
415 * @param error return location for error
416 * @returns #FALSE if error was set
419 _dbus_stat (const DBusString *filename,
423 const char *filename_c;
426 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
428 filename_c = _dbus_string_get_const_data (filename);
430 if (stat (filename_c, &sb) < 0)
432 dbus_set_error (error, _dbus_error_from_errno (errno),
433 "%s", _dbus_strerror (errno));
437 statbuf->mode = sb.st_mode;
438 statbuf->nlink = sb.st_nlink;
439 statbuf->uid = sb.st_uid;
440 statbuf->gid = sb.st_gid;
441 statbuf->size = sb.st_size;
442 statbuf->atime = sb.st_atime;
443 statbuf->mtime = sb.st_mtime;
444 statbuf->ctime = sb.st_ctime;
451 * Internals of directory iterator
455 DIR *d; /**< The DIR* from opendir() */
460 * Open a directory to iterate over.
462 * @param filename the directory name
463 * @param error exception return object or #NULL
464 * @returns new iterator, or #NULL on error
467 _dbus_directory_open (const DBusString *filename,
472 const char *filename_c;
474 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
476 filename_c = _dbus_string_get_const_data (filename);
478 d = opendir (filename_c);
481 dbus_set_error (error, _dbus_error_from_errno (errno),
482 "Failed to read directory \"%s\": %s",
484 _dbus_strerror (errno));
487 iter = dbus_new0 (DBusDirIter, 1);
491 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
492 "Could not allocate memory for directory iterator");
501 /* Calculate the required buffer size (in bytes) for directory
502 * entries read from the given directory handle. Return -1 if this
503 * this cannot be done.
505 * If you use autoconf, include fpathconf and dirfd in your
506 * AC_CHECK_FUNCS list. Otherwise use some other method to detect
507 * and use them where available.
510 dirent_buf_size(DIR * dirp, size_t *size)
513 # if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
514 # if defined(HAVE_DIRFD)
515 name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
516 # elif defined(HAVE_DDFD)
517 name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
519 name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
520 # endif /* HAVE_DIRFD */
522 # if defined(NAME_MAX)
527 # elif defined(MAXNAMELEN)
528 name_max = MAXNAMELEN;
530 # if defined(NAME_MAX)
533 # error "buffer size for readdir_r cannot be determined"
537 *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
545 * Get next file in the directory. Will not return "." or ".." on
546 * UNIX. If an error occurs, the contents of "filename" are
547 * undefined. The error is never set if the function succeeds.
549 * @param iter the iterator
550 * @param filename string to be set to the next file in the dir
551 * @param error return location for error
552 * @returns #TRUE if filename was filled in with a new filename
555 _dbus_directory_get_next_file (DBusDirIter *iter,
556 DBusString *filename,
559 struct dirent *d, *ent;
563 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
565 if (!dirent_buf_size (iter->d, &buf_size))
567 dbus_set_error (error, DBUS_ERROR_FAILED,
568 "Can't calculate buffer size when reading directory");
572 d = (struct dirent *)dbus_malloc (buf_size);
575 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
576 "No memory to read directory entry");
581 err = readdir_r (iter->d, d, &ent);
585 dbus_set_error (error,
586 _dbus_error_from_errno (err),
587 "%s", _dbus_strerror (err));
592 else if (ent->d_name[0] == '.' &&
593 (ent->d_name[1] == '\0' ||
594 (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
598 _dbus_string_set_length (filename, 0);
599 if (!_dbus_string_append (filename, ent->d_name))
601 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
602 "No memory to read directory entry");
615 * Closes a directory iteration.
618 _dbus_directory_close (DBusDirIter *iter)
625 fill_user_info_from_group (struct group *g,
629 _dbus_assert (g->gr_name != NULL);
631 info->gid = g->gr_gid;
632 info->groupname = _dbus_strdup (g->gr_name);
634 /* info->members = dbus_strdupv (g->gr_mem) */
636 if (info->groupname == NULL)
638 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
646 fill_group_info (DBusGroupInfo *info,
648 const DBusString *groupname,
651 const char *group_c_str;
653 _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
654 _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
657 group_c_str = _dbus_string_get_const_data (groupname);
661 /* For now assuming that the getgrnam() and getgrgid() flavors
662 * always correspond to the pwnam flavors, if not we have
663 * to add more configure checks.
666 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
674 #ifdef HAVE_POSIX_GETPWNAM_R
677 result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
680 result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
683 g = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
685 #endif /* !HAVE_POSIX_GETPWNAM_R */
686 if (result == 0 && g == &g_str)
688 return fill_user_info_from_group (g, info, error);
692 dbus_set_error (error, _dbus_error_from_errno (errno),
693 "Group %s unknown or failed to look it up\n",
694 group_c_str ? group_c_str : "???");
698 #else /* ! HAVE_GETPWNAM_R */
700 /* I guess we're screwed on thread safety here */
703 g = getgrnam (group_c_str);
707 return fill_user_info_from_group (g, info, error);
711 dbus_set_error (error, _dbus_error_from_errno (errno),
712 "Group %s unknown or failed to look it up\n",
713 group_c_str ? group_c_str : "???");
717 #endif /* ! HAVE_GETPWNAM_R */
721 * Initializes the given DBusGroupInfo struct
722 * with information about the given group name.
724 * @param info the group info struct
725 * @param groupname name of group
726 * @param error the error return
727 * @returns #FALSE if error is set
730 _dbus_group_info_fill (DBusGroupInfo *info,
731 const DBusString *groupname,
734 return fill_group_info (info, DBUS_GID_UNSET,
740 * Initializes the given DBusGroupInfo struct
741 * with information about the given group ID.
743 * @param info the group info struct
744 * @param gid group ID
745 * @param error the error return
746 * @returns #FALSE if error is set
749 _dbus_group_info_fill_gid (DBusGroupInfo *info,
753 return fill_group_info (info, gid, NULL, error);
756 /** @} */ /* End of DBusInternalsUtils functions */
759 * @addtogroup DBusString
764 * Get the directory name from a complete filename
765 * @param filename the filename
766 * @param dirname string to append directory name to
767 * @returns #FALSE if no memory
770 _dbus_string_get_dirname (const DBusString *filename,
775 _dbus_assert (filename != dirname);
776 _dbus_assert (filename != NULL);
777 _dbus_assert (dirname != NULL);
779 /* Ignore any separators on the end */
780 sep = _dbus_string_get_length (filename);
782 return _dbus_string_append (dirname, "."); /* empty string passed in */
784 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
787 _dbus_assert (sep >= 0);
790 return _dbus_string_append (dirname, "/");
792 /* Now find the previous separator */
793 _dbus_string_find_byte_backward (filename, sep, '/', &sep);
795 return _dbus_string_append (dirname, ".");
797 /* skip multiple separators */
798 while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
801 _dbus_assert (sep >= 0);
804 _dbus_string_get_byte (filename, 0) == '/')
805 return _dbus_string_append (dirname, "/");
807 return _dbus_string_copy_len (filename, 0, sep - 0,
808 dirname, _dbus_string_get_length (dirname));
810 /** @} */ /* DBusString stuff */