D-Bus  1.4.18
dbus-sysdeps-util-unix.c
00001 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
00002 /* dbus-sysdeps-util-unix.c Would be in dbus-sysdeps-unix.c, but not used in libdbus
00003  * 
00004  * Copyright (C) 2002, 2003, 2004, 2005  Red Hat, Inc.
00005  * Copyright (C) 2003 CodeFactory AB
00006  *
00007  * Licensed under the Academic Free License version 2.1
00008  * 
00009  * This program is free software; you can redistribute it and/or modify
00010  * it under the terms of the GNU General Public License as published by
00011  * the Free Software Foundation; either version 2 of the License, or
00012  * (at your option) any later version.
00013  *
00014  * This program is distributed in the hope that it will be useful,
00015  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00017  * GNU General Public License for more details.
00018  * 
00019  * You should have received a copy of the GNU General Public License
00020  * along with this program; if not, write to the Free Software
00021  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
00022  *
00023  */
00024 
00025 #include <config.h>
00026 #include "dbus-sysdeps.h"
00027 #include "dbus-sysdeps-unix.h"
00028 #include "dbus-internals.h"
00029 #include "dbus-pipe.h"
00030 #include "dbus-protocol.h"
00031 #include "dbus-string.h"
00032 #define DBUS_USERDB_INCLUDES_PRIVATE 1
00033 #include "dbus-userdb.h"
00034 #include "dbus-test.h"
00035 
00036 #include <sys/types.h>
00037 #include <stdlib.h>
00038 #include <string.h>
00039 #include <signal.h>
00040 #include <unistd.h>
00041 #include <stdio.h>
00042 #include <errno.h>
00043 #include <fcntl.h>
00044 #include <sys/stat.h>
00045 #ifdef HAVE_SYS_RESOURCE_H
00046 #include <sys/resource.h>
00047 #endif
00048 #include <grp.h>
00049 #include <sys/socket.h>
00050 #include <dirent.h>
00051 #include <sys/un.h>
00052 #include <syslog.h>
00053 
00054 #ifdef HAVE_SYS_SYSLIMITS_H
00055 #include <sys/syslimits.h>
00056 #endif
00057 
00058 #ifndef O_BINARY
00059 #define O_BINARY 0
00060 #endif
00061 
00077 dbus_bool_t
00078 _dbus_become_daemon (const DBusString *pidfile,
00079                      DBusPipe         *print_pid_pipe,
00080                      DBusError        *error,
00081                      dbus_bool_t       keep_umask)
00082 {
00083   const char *s;
00084   pid_t child_pid;
00085   int dev_null_fd;
00086 
00087   _dbus_verbose ("Becoming a daemon...\n");
00088 
00089   _dbus_verbose ("chdir to /\n");
00090   if (chdir ("/") < 0)
00091     {
00092       dbus_set_error (error, DBUS_ERROR_FAILED,
00093                       "Could not chdir() to root directory");
00094       return FALSE;
00095     }
00096 
00097   _dbus_verbose ("forking...\n");
00098   switch ((child_pid = fork ()))
00099     {
00100     case -1:
00101       _dbus_verbose ("fork failed\n");
00102       dbus_set_error (error, _dbus_error_from_errno (errno),
00103                       "Failed to fork daemon: %s", _dbus_strerror (errno));
00104       return FALSE;
00105       break;
00106 
00107     case 0:
00108       _dbus_verbose ("in child, closing std file descriptors\n");
00109 
00110       /* silently ignore failures here, if someone
00111        * doesn't have /dev/null we may as well try
00112        * to continue anyhow
00113        */
00114       
00115       dev_null_fd = open ("/dev/null", O_RDWR);
00116       if (dev_null_fd >= 0)
00117         {
00118           dup2 (dev_null_fd, 0);
00119           dup2 (dev_null_fd, 1);
00120           
00121           s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
00122           if (s == NULL || *s == '\0')
00123             dup2 (dev_null_fd, 2);
00124           else
00125             _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
00126         }
00127 
00128       if (!keep_umask)
00129         {
00130           /* Get a predictable umask */
00131           _dbus_verbose ("setting umask\n");
00132           umask (022);
00133         }
00134 
00135       _dbus_verbose ("calling setsid()\n");
00136       if (setsid () == -1)
00137         _dbus_assert_not_reached ("setsid() failed");
00138       
00139       break;
00140 
00141     default:
00142       if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
00143                                              child_pid, error))
00144         {
00145           _dbus_verbose ("pid file or pipe write failed: %s\n",
00146                          error->message);
00147           kill (child_pid, SIGTERM);
00148           return FALSE;
00149         }
00150 
00151       _dbus_verbose ("parent exiting\n");
00152       _exit (0);
00153       break;
00154     }
00155   
00156   return TRUE;
00157 }
00158 
00159 
00168 static dbus_bool_t
00169 _dbus_write_pid_file (const DBusString *filename,
00170                       unsigned long     pid,
00171                       DBusError        *error)
00172 {
00173   const char *cfilename;
00174   int fd;
00175   FILE *f;
00176 
00177   cfilename = _dbus_string_get_const_data (filename);
00178   
00179   fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
00180   
00181   if (fd < 0)
00182     {
00183       dbus_set_error (error, _dbus_error_from_errno (errno),
00184                       "Failed to open \"%s\": %s", cfilename,
00185                       _dbus_strerror (errno));
00186       return FALSE;
00187     }
00188 
00189   if ((f = fdopen (fd, "w")) == NULL)
00190     {
00191       dbus_set_error (error, _dbus_error_from_errno (errno),
00192                       "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
00193       _dbus_close (fd, NULL);
00194       return FALSE;
00195     }
00196   
00197   if (fprintf (f, "%lu\n", pid) < 0)
00198     {
00199       dbus_set_error (error, _dbus_error_from_errno (errno),
00200                       "Failed to write to \"%s\": %s", cfilename,
00201                       _dbus_strerror (errno));
00202       
00203       fclose (f);
00204       return FALSE;
00205     }
00206 
00207   if (fclose (f) == EOF)
00208     {
00209       dbus_set_error (error, _dbus_error_from_errno (errno),
00210                       "Failed to close \"%s\": %s", cfilename,
00211                       _dbus_strerror (errno));
00212       return FALSE;
00213     }
00214   
00215   return TRUE;
00216 }
00217 
00229 dbus_bool_t
00230 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
00231                                   DBusPipe         *print_pid_pipe,
00232                                   dbus_pid_t        pid_to_write,
00233                                   DBusError        *error)
00234 {
00235   if (pidfile)
00236     {
00237       _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
00238       if (!_dbus_write_pid_file (pidfile,
00239                                  pid_to_write,
00240                                  error))
00241         {
00242           _dbus_verbose ("pid file write failed\n");
00243           _DBUS_ASSERT_ERROR_IS_SET(error);
00244           return FALSE;
00245         }
00246     }
00247   else
00248     {
00249       _dbus_verbose ("No pid file requested\n");
00250     }
00251 
00252   if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
00253     {
00254       DBusString pid;
00255       int bytes;
00256 
00257       _dbus_verbose ("writing our pid to pipe %"PRIuPTR"\n",
00258                      print_pid_pipe->fd_or_handle);
00259       
00260       if (!_dbus_string_init (&pid))
00261         {
00262           _DBUS_SET_OOM (error);
00263           return FALSE;
00264         }
00265           
00266       if (!_dbus_string_append_int (&pid, pid_to_write) ||
00267           !_dbus_string_append (&pid, "\n"))
00268         {
00269           _dbus_string_free (&pid);
00270           _DBUS_SET_OOM (error);
00271           return FALSE;
00272         }
00273           
00274       bytes = _dbus_string_get_length (&pid);
00275       if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
00276         {
00277           /* _dbus_pipe_write sets error only on failure, not short write */
00278           if (error != NULL && !dbus_error_is_set(error))
00279             {
00280               dbus_set_error (error, DBUS_ERROR_FAILED,
00281                               "Printing message bus PID: did not write enough bytes\n");
00282             }
00283           _dbus_string_free (&pid);
00284           return FALSE;
00285         }
00286           
00287       _dbus_string_free (&pid);
00288     }
00289   else
00290     {
00291       _dbus_verbose ("No pid pipe to write to\n");
00292     }
00293 
00294   return TRUE;
00295 }
00296 
00303 dbus_bool_t
00304 _dbus_verify_daemon_user (const char *user)
00305 {
00306   DBusString u;
00307 
00308   _dbus_string_init_const (&u, user);
00309 
00310   return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
00311 }
00312 
00313 
00314 /* The HAVE_LIBAUDIT case lives in selinux.c */
00315 #ifndef HAVE_LIBAUDIT
00316 
00323 dbus_bool_t
00324 _dbus_change_to_daemon_user  (const char    *user,
00325                               DBusError     *error)
00326 {
00327   dbus_uid_t uid;
00328   dbus_gid_t gid;
00329   DBusString u;
00330 
00331   _dbus_string_init_const (&u, user);
00332 
00333   if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
00334     {
00335       dbus_set_error (error, DBUS_ERROR_FAILED,
00336                       "User '%s' does not appear to exist?",
00337                       user);
00338       return FALSE;
00339     }
00340 
00341   /* setgroups() only works if we are a privileged process,
00342    * so we don't return error on failure; the only possible
00343    * failure is that we don't have perms to do it.
00344    *
00345    * not sure this is right, maybe if setuid()
00346    * is going to work then setgroups() should also work.
00347    */
00348   if (setgroups (0, NULL) < 0)
00349     _dbus_warn ("Failed to drop supplementary groups: %s\n",
00350                 _dbus_strerror (errno));
00351 
00352   /* Set GID first, or the setuid may remove our permission
00353    * to change the GID
00354    */
00355   if (setgid (gid) < 0)
00356     {
00357       dbus_set_error (error, _dbus_error_from_errno (errno),
00358                       "Failed to set GID to %lu: %s", gid,
00359                       _dbus_strerror (errno));
00360       return FALSE;
00361     }
00362 
00363   if (setuid (uid) < 0)
00364     {
00365       dbus_set_error (error, _dbus_error_from_errno (errno),
00366                       "Failed to set UID to %lu: %s", uid,
00367                       _dbus_strerror (errno));
00368       return FALSE;
00369     }
00370 
00371   return TRUE;
00372 }
00373 #endif /* !HAVE_LIBAUDIT */
00374 
00375 #ifdef HAVE_SETRLIMIT
00376 
00377 /* We assume that if we have setrlimit, we also have getrlimit and
00378  * struct rlimit.
00379  */
00380 
00381 struct DBusRLimit {
00382     struct rlimit lim;
00383 };
00384 
00385 DBusRLimit *
00386 _dbus_rlimit_save_fd_limit (DBusError *error)
00387 {
00388   DBusRLimit *self;
00389 
00390   self = dbus_new0 (DBusRLimit, 1);
00391 
00392   if (self == NULL)
00393     {
00394       _DBUS_SET_OOM (error);
00395       return NULL;
00396     }
00397 
00398   if (getrlimit (RLIMIT_NOFILE, &self->lim) < 0)
00399     {
00400       dbus_set_error (error, _dbus_error_from_errno (errno),
00401                       "Failed to get fd limit: %s", _dbus_strerror (errno));
00402       dbus_free (self);
00403       return NULL;
00404     }
00405 
00406   return self;
00407 }
00408 
00409 dbus_bool_t
00410 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int  desired,
00411                                            DBusError    *error)
00412 {
00413   struct rlimit lim;
00414 
00415   /* No point to doing this practically speaking
00416    * if we're not uid 0.  We expect the system
00417    * bus to use this before we change UID, and
00418    * the session bus takes the Linux default,
00419    * currently 1024 for cur and 4096 for max.
00420    */
00421   if (getuid () != 0)
00422     {
00423       /* not an error, we're probably the session bus */
00424       return TRUE;
00425     }
00426 
00427   if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
00428     {
00429       dbus_set_error (error, _dbus_error_from_errno (errno),
00430                       "Failed to get fd limit: %s", _dbus_strerror (errno));
00431       return FALSE;
00432     }
00433 
00434   if (lim.rlim_cur == RLIM_INFINITY || lim.rlim_cur >= desired)
00435     {
00436       /* not an error, everything is fine */
00437       return TRUE;
00438     }
00439 
00440   /* Ignore "maximum limit", assume we have the "superuser"
00441    * privileges.  On Linux this is CAP_SYS_RESOURCE.
00442    */
00443   lim.rlim_cur = lim.rlim_max = desired;
00444 
00445   if (setrlimit (RLIMIT_NOFILE, &lim) < 0)
00446     {
00447       dbus_set_error (error, _dbus_error_from_errno (errno),
00448                       "Failed to set fd limit to %u: %s",
00449                       desired, _dbus_strerror (errno));
00450       return FALSE;
00451     }
00452 
00453   return TRUE;
00454 }
00455 
00456 dbus_bool_t
00457 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
00458                                DBusError  *error)
00459 {
00460   if (setrlimit (RLIMIT_NOFILE, &saved->lim) < 0)
00461     {
00462       dbus_set_error (error, _dbus_error_from_errno (errno),
00463                       "Failed to restore old fd limit: %s",
00464                       _dbus_strerror (errno));
00465       return FALSE;
00466     }
00467 
00468   return TRUE;
00469 }
00470 
00471 #else /* !HAVE_SETRLIMIT */
00472 
00473 static void
00474 fd_limit_not_supported (DBusError *error)
00475 {
00476   dbus_set_error (error, DBUS_ERROR_NOT_SUPPORTED,
00477                   "cannot change fd limit on this platform");
00478 }
00479 
00480 DBusRLimit *
00481 _dbus_rlimit_save_fd_limit (DBusError *error)
00482 {
00483   fd_limit_not_supported (error);
00484   return NULL;
00485 }
00486 
00487 dbus_bool_t
00488 _dbus_rlimit_raise_fd_limit_if_privileged (unsigned int  desired,
00489                                            DBusError    *error)
00490 {
00491   fd_limit_not_supported (error);
00492   return FALSE;
00493 }
00494 
00495 dbus_bool_t
00496 _dbus_rlimit_restore_fd_limit (DBusRLimit *saved,
00497                                DBusError  *error)
00498 {
00499   fd_limit_not_supported (error);
00500   return FALSE;
00501 }
00502 
00503 #endif
00504 
00505 void
00506 _dbus_rlimit_free (DBusRLimit *lim)
00507 {
00508   dbus_free (lim);
00509 }
00510 
00511 void
00512 _dbus_init_system_log (void)
00513 {
00514 #ifdef HAVE_DECL_LOG_PERROR
00515   openlog ("dbus", LOG_PID | LOG_PERROR, LOG_DAEMON);
00516 #else
00517   openlog ("dbus", LOG_PID, LOG_DAEMON);
00518 #endif
00519 }
00520 
00529 void
00530 _dbus_system_log (DBusSystemLogSeverity severity, const char *msg, ...)
00531 {
00532   va_list args;
00533 
00534   va_start (args, msg);
00535 
00536   _dbus_system_logv (severity, msg, args);
00537 
00538   va_end (args);
00539 }
00540 
00551 void
00552 _dbus_system_logv (DBusSystemLogSeverity severity, const char *msg, va_list args)
00553 {
00554   int flags;
00555   switch (severity)
00556     {
00557       case DBUS_SYSTEM_LOG_INFO:
00558         flags =  LOG_DAEMON | LOG_NOTICE;
00559         break;
00560       case DBUS_SYSTEM_LOG_SECURITY:
00561         flags = LOG_AUTH | LOG_NOTICE;
00562         break;
00563       case DBUS_SYSTEM_LOG_FATAL:
00564         flags = LOG_DAEMON|LOG_CRIT;
00565         break;
00566       default:
00567         return;
00568     }
00569 
00570 #ifndef HAVE_DECL_LOG_PERROR
00571     {
00572       /* vsyslog() won't write to stderr, so we'd better do it */
00573       va_list tmp;
00574 
00575       DBUS_VA_COPY (tmp, args);
00576       fprintf (stderr, "dbus[" DBUS_PID_FORMAT "]: ", _dbus_getpid ());
00577       vfprintf (stderr, msg, tmp);
00578       fputc ('\n', stderr);
00579       va_end (tmp);
00580     }
00581 #endif
00582 
00583   vsyslog (flags, msg, args);
00584 
00585   if (severity == DBUS_SYSTEM_LOG_FATAL)
00586     exit (1);
00587 }
00588 
00594 void
00595 _dbus_set_signal_handler (int               sig,
00596                           DBusSignalHandler handler)
00597 {
00598   struct sigaction act;
00599   sigset_t empty_mask;
00600   
00601   sigemptyset (&empty_mask);
00602   act.sa_handler = handler;
00603   act.sa_mask    = empty_mask;
00604   act.sa_flags   = 0;
00605   sigaction (sig,  &act, NULL);
00606 }
00607 
00613 dbus_bool_t 
00614 _dbus_file_exists (const char *file)
00615 {
00616   return (access (file, F_OK) == 0);
00617 }
00618 
00625 dbus_bool_t 
00626 _dbus_user_at_console (const char *username,
00627                        DBusError  *error)
00628 {
00629 
00630   DBusString f;
00631   dbus_bool_t result;
00632 
00633   result = FALSE;
00634   if (!_dbus_string_init (&f))
00635     {
00636       _DBUS_SET_OOM (error);
00637       return FALSE;
00638     }
00639 
00640   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
00641     {
00642       _DBUS_SET_OOM (error);
00643       goto out;
00644     }
00645 
00646 
00647   if (!_dbus_string_append (&f, username))
00648     {
00649       _DBUS_SET_OOM (error);
00650       goto out;
00651     }
00652 
00653   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
00654 
00655  out:
00656   _dbus_string_free (&f);
00657 
00658   return result;
00659 }
00660 
00661 
00668 dbus_bool_t
00669 _dbus_path_is_absolute (const DBusString *filename)
00670 {
00671   if (_dbus_string_get_length (filename) > 0)
00672     return _dbus_string_get_byte (filename, 0) == '/';
00673   else
00674     return FALSE;
00675 }
00676 
00685 dbus_bool_t
00686 _dbus_stat (const DBusString *filename,
00687             DBusStat         *statbuf,
00688             DBusError        *error)
00689 {
00690   const char *filename_c;
00691   struct stat sb;
00692 
00693   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00694   
00695   filename_c = _dbus_string_get_const_data (filename);
00696 
00697   if (stat (filename_c, &sb) < 0)
00698     {
00699       dbus_set_error (error, _dbus_error_from_errno (errno),
00700                       "%s", _dbus_strerror (errno));
00701       return FALSE;
00702     }
00703 
00704   statbuf->mode = sb.st_mode;
00705   statbuf->nlink = sb.st_nlink;
00706   statbuf->uid = sb.st_uid;
00707   statbuf->gid = sb.st_gid;
00708   statbuf->size = sb.st_size;
00709   statbuf->atime = sb.st_atime;
00710   statbuf->mtime = sb.st_mtime;
00711   statbuf->ctime = sb.st_ctime;
00712 
00713   return TRUE;
00714 }
00715 
00716 
00720 struct DBusDirIter
00721 {
00722   DIR *d; 
00724 };
00725 
00733 DBusDirIter*
00734 _dbus_directory_open (const DBusString *filename,
00735                       DBusError        *error)
00736 {
00737   DIR *d;
00738   DBusDirIter *iter;
00739   const char *filename_c;
00740 
00741   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00742   
00743   filename_c = _dbus_string_get_const_data (filename);
00744 
00745   d = opendir (filename_c);
00746   if (d == NULL)
00747     {
00748       dbus_set_error (error, _dbus_error_from_errno (errno),
00749                       "Failed to read directory \"%s\": %s",
00750                       filename_c,
00751                       _dbus_strerror (errno));
00752       return NULL;
00753     }
00754   iter = dbus_new0 (DBusDirIter, 1);
00755   if (iter == NULL)
00756     {
00757       closedir (d);
00758       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
00759                       "Could not allocate memory for directory iterator");
00760       return NULL;
00761     }
00762 
00763   iter->d = d;
00764 
00765   return iter;
00766 }
00767 
00781 dbus_bool_t
00782 _dbus_directory_get_next_file (DBusDirIter      *iter,
00783                                DBusString       *filename,
00784                                DBusError        *error)
00785 {
00786   struct dirent *ent;
00787   int err;
00788 
00789   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
00790 
00791  again:
00792   errno = 0;
00793   ent = readdir (iter->d);
00794 
00795   if (!ent)
00796     {
00797       err = errno;
00798 
00799       if (err != 0)
00800         dbus_set_error (error,
00801                         _dbus_error_from_errno (err),
00802                         "%s", _dbus_strerror (err));
00803 
00804       return FALSE;
00805     }
00806   else if (ent->d_name[0] == '.' &&
00807            (ent->d_name[1] == '\0' ||
00808             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
00809     goto again;
00810   else
00811     {
00812       _dbus_string_set_length (filename, 0);
00813       if (!_dbus_string_append (filename, ent->d_name))
00814         {
00815           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
00816                           "No memory to read directory entry");
00817           return FALSE;
00818         }
00819       else
00820         {
00821           return TRUE;
00822         }
00823     }
00824 }
00825 
00829 void
00830 _dbus_directory_close (DBusDirIter *iter)
00831 {
00832   closedir (iter->d);
00833   dbus_free (iter);
00834 }
00835 
00836 static dbus_bool_t
00837 fill_user_info_from_group (struct group  *g,
00838                            DBusGroupInfo *info,
00839                            DBusError     *error)
00840 {
00841   _dbus_assert (g->gr_name != NULL);
00842   
00843   info->gid = g->gr_gid;
00844   info->groupname = _dbus_strdup (g->gr_name);
00845 
00846   /* info->members = dbus_strdupv (g->gr_mem) */
00847   
00848   if (info->groupname == NULL)
00849     {
00850       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00851       return FALSE;
00852     }
00853 
00854   return TRUE;
00855 }
00856 
00857 static dbus_bool_t
00858 fill_group_info (DBusGroupInfo    *info,
00859                  dbus_gid_t        gid,
00860                  const DBusString *groupname,
00861                  DBusError        *error)
00862 {
00863   const char *group_c_str;
00864 
00865   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
00866   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
00867 
00868   if (groupname)
00869     group_c_str = _dbus_string_get_const_data (groupname);
00870   else
00871     group_c_str = NULL;
00872   
00873   /* For now assuming that the getgrnam() and getgrgid() flavors
00874    * always correspond to the pwnam flavors, if not we have
00875    * to add more configure checks.
00876    */
00877   
00878 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
00879   {
00880     struct group *g;
00881     int result;
00882     size_t buflen;
00883     char *buf;
00884     struct group g_str;
00885     dbus_bool_t b;
00886 
00887     /* retrieve maximum needed size for buf */
00888     buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
00889 
00890     /* sysconf actually returns a long, but everything else expects size_t,
00891      * so just recast here.
00892      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
00893      */
00894     if ((long) buflen <= 0)
00895       buflen = 1024;
00896 
00897     result = -1;
00898     while (1)
00899       {
00900         buf = dbus_malloc (buflen);
00901         if (buf == NULL)
00902           {
00903             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
00904             return FALSE;
00905           }
00906 
00907         g = NULL;
00908 #ifdef HAVE_POSIX_GETPWNAM_R
00909         if (group_c_str)
00910           result = getgrnam_r (group_c_str, &g_str, buf, buflen,
00911                                &g);
00912         else
00913           result = getgrgid_r (gid, &g_str, buf, buflen,
00914                                &g);
00915 #else
00916         g = getgrnam_r (group_c_str, &g_str, buf, buflen);
00917         result = 0;
00918 #endif /* !HAVE_POSIX_GETPWNAM_R */
00919         /* Try a bigger buffer if ERANGE was returned:
00920            https://bugs.freedesktop.org/show_bug.cgi?id=16727
00921         */
00922         if (result == ERANGE && buflen < 512 * 1024)
00923           {
00924             dbus_free (buf);
00925             buflen *= 2;
00926           }
00927         else
00928           {
00929             break;
00930           }
00931       }
00932 
00933     if (result == 0 && g == &g_str)
00934       {
00935         b = fill_user_info_from_group (g, info, error);
00936         dbus_free (buf);
00937         return b;
00938       }
00939     else
00940       {
00941         dbus_set_error (error, _dbus_error_from_errno (errno),
00942                         "Group %s unknown or failed to look it up\n",
00943                         group_c_str ? group_c_str : "???");
00944         dbus_free (buf);
00945         return FALSE;
00946       }
00947   }
00948 #else /* ! HAVE_GETPWNAM_R */
00949   {
00950     /* I guess we're screwed on thread safety here */
00951     struct group *g;
00952 
00953     g = getgrnam (group_c_str);
00954 
00955     if (g != NULL)
00956       {
00957         return fill_user_info_from_group (g, info, error);
00958       }
00959     else
00960       {
00961         dbus_set_error (error, _dbus_error_from_errno (errno),
00962                         "Group %s unknown or failed to look it up\n",
00963                         group_c_str ? group_c_str : "???");
00964         return FALSE;
00965       }
00966   }
00967 #endif  /* ! HAVE_GETPWNAM_R */
00968 }
00969 
00979 dbus_bool_t
00980 _dbus_group_info_fill (DBusGroupInfo    *info,
00981                        const DBusString *groupname,
00982                        DBusError        *error)
00983 {
00984   return fill_group_info (info, DBUS_GID_UNSET,
00985                           groupname, error);
00986 
00987 }
00988 
00998 dbus_bool_t
00999 _dbus_group_info_fill_gid (DBusGroupInfo *info,
01000                            dbus_gid_t     gid,
01001                            DBusError     *error)
01002 {
01003   return fill_group_info (info, gid, NULL, error);
01004 }
01005 
01014 dbus_bool_t
01015 _dbus_parse_unix_user_from_config (const DBusString  *username,
01016                                    dbus_uid_t        *uid_p)
01017 {
01018   return _dbus_get_user_id (username, uid_p);
01019 
01020 }
01021 
01030 dbus_bool_t
01031 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
01032                                     dbus_gid_t        *gid_p)
01033 {
01034   return _dbus_get_group_id (groupname, gid_p);
01035 }
01036 
01047 dbus_bool_t
01048 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
01049                             dbus_gid_t          **group_ids,
01050                             int                  *n_group_ids)
01051 {
01052   return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
01053 }
01054 
01064 dbus_bool_t
01065 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
01066                                DBusError         *error)
01067 {
01068   return _dbus_is_console_user (uid, error);
01069 
01070 }
01071 
01079 dbus_bool_t
01080 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
01081 {
01082   return uid == _dbus_geteuid ();
01083 }
01084 
01092 dbus_bool_t
01093 _dbus_windows_user_is_process_owner (const char *windows_sid)
01094 {
01095   return FALSE;
01096 }
01097  /* End of DBusInternalsUtils functions */
01099 
01111 dbus_bool_t
01112 _dbus_string_get_dirname  (const DBusString *filename,
01113                            DBusString       *dirname)
01114 {
01115   int sep;
01116   
01117   _dbus_assert (filename != dirname);
01118   _dbus_assert (filename != NULL);
01119   _dbus_assert (dirname != NULL);
01120 
01121   /* Ignore any separators on the end */
01122   sep = _dbus_string_get_length (filename);
01123   if (sep == 0)
01124     return _dbus_string_append (dirname, "."); /* empty string passed in */
01125     
01126   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
01127     --sep;
01128 
01129   _dbus_assert (sep >= 0);
01130   
01131   if (sep == 0)
01132     return _dbus_string_append (dirname, "/");
01133   
01134   /* Now find the previous separator */
01135   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
01136   if (sep < 0)
01137     return _dbus_string_append (dirname, ".");
01138   
01139   /* skip multiple separators */
01140   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
01141     --sep;
01142 
01143   _dbus_assert (sep >= 0);
01144   
01145   if (sep == 0 &&
01146       _dbus_string_get_byte (filename, 0) == '/')
01147     return _dbus_string_append (dirname, "/");
01148   else
01149     return _dbus_string_copy_len (filename, 0, sep - 0,
01150                                   dirname, _dbus_string_get_length (dirname));
01151 } /* DBusString stuff */
01153 
01154 static void
01155 string_squash_nonprintable (DBusString *str)
01156 {
01157   unsigned char *buf;
01158   int i, len; 
01159   
01160   buf = _dbus_string_get_data (str);
01161   len = _dbus_string_get_length (str);
01162   
01163   for (i = 0; i < len; i++)
01164     {
01165       unsigned char c = (unsigned char) buf[i];
01166       if (c == '\0')
01167         buf[i] = ' ';
01168       else if (c < 0x20 || c > 127)
01169         buf[i] = '?';
01170     }
01171 }
01172 
01187 dbus_bool_t 
01188 _dbus_command_for_pid (unsigned long  pid,
01189                        DBusString    *str,
01190                        int            max_len,
01191                        DBusError     *error)
01192 {
01193   /* This is all Linux-specific for now */
01194   DBusString path;
01195   DBusString cmdline;
01196   int fd;
01197   
01198   if (!_dbus_string_init (&path)) 
01199     {
01200       _DBUS_SET_OOM (error);
01201       return FALSE;
01202     }
01203   
01204   if (!_dbus_string_init (&cmdline))
01205     {
01206       _DBUS_SET_OOM (error);
01207       _dbus_string_free (&path);
01208       return FALSE;
01209     }
01210   
01211   if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
01212     goto oom;
01213   
01214   fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
01215   if (fd < 0) 
01216     {
01217       dbus_set_error (error,
01218                       _dbus_error_from_errno (errno),
01219                       "Failed to open \"%s\": %s",
01220                       _dbus_string_get_const_data (&path),
01221                       _dbus_strerror (errno));
01222       goto fail;
01223     }
01224   
01225   if (!_dbus_read (fd, &cmdline, max_len))
01226     {
01227       dbus_set_error (error,
01228                       _dbus_error_from_errno (errno),
01229                       "Failed to read from \"%s\": %s",
01230                       _dbus_string_get_const_data (&path),
01231                       _dbus_strerror (errno));      
01232       goto fail;
01233     }
01234   
01235   if (!_dbus_close (fd, error))
01236     goto fail;
01237   
01238   string_squash_nonprintable (&cmdline);  
01239 
01240   if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
01241     goto oom;
01242 
01243   _dbus_string_free (&cmdline);  
01244   _dbus_string_free (&path);
01245   return TRUE;
01246 oom:
01247   _DBUS_SET_OOM (error);
01248 fail:
01249   _dbus_string_free (&cmdline);
01250   _dbus_string_free (&path);
01251   return FALSE;
01252 }