Bug 21646 - Fix a signed char comparison
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-util-unix.c
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
3  * 
4  * Copyright (C) 2002, 2003, 2004, 2005  Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.1
8  * 
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.
13  *
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.
18  * 
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
22  *
23  */
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"
32
33 #include <sys/types.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <unistd.h>
38 #include <stdio.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <sys/stat.h>
42 #include <grp.h>
43 #include <sys/socket.h>
44 #include <dirent.h>
45 #include <sys/un.h>
46 #include <syslog.h>
47 #ifdef HAVE_LIBAUDIT
48 #include <sys/prctl.h>
49 #include <sys/capability.h>
50 #include <libaudit.h>
51 #endif /* HAVE_LIBAUDIT */
52
53 #ifdef HAVE_SYS_SYSLIMITS_H
54 #include <sys/syslimits.h>
55 #endif
56
57 #ifndef O_BINARY
58 #define O_BINARY 0
59 #endif
60
61 /**
62  * @addtogroup DBusInternalsUtils
63  * @{
64  */
65
66
67 /**
68  * Does the chdir, fork, setsid, etc. to become a daemon process.
69  *
70  * @param pidfile #NULL, or pidfile to create
71  * @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
72  * @param error return location for errors
73  * @param keep_umask #TRUE to keep the original umask
74  * @returns #FALSE on failure
75  */
76 dbus_bool_t
77 _dbus_become_daemon (const DBusString *pidfile,
78                      DBusPipe         *print_pid_pipe,
79                      DBusError        *error,
80                      dbus_bool_t       keep_umask)
81 {
82   const char *s;
83   pid_t child_pid;
84   int dev_null_fd;
85
86   _dbus_verbose ("Becoming a daemon...\n");
87
88   _dbus_verbose ("chdir to /\n");
89   if (chdir ("/") < 0)
90     {
91       dbus_set_error (error, DBUS_ERROR_FAILED,
92                       "Could not chdir() to root directory");
93       return FALSE;
94     }
95
96   _dbus_verbose ("forking...\n");
97   switch ((child_pid = fork ()))
98     {
99     case -1:
100       _dbus_verbose ("fork failed\n");
101       dbus_set_error (error, _dbus_error_from_errno (errno),
102                       "Failed to fork daemon: %s", _dbus_strerror (errno));
103       return FALSE;
104       break;
105
106     case 0:
107       _dbus_verbose ("in child, closing std file descriptors\n");
108
109       /* silently ignore failures here, if someone
110        * doesn't have /dev/null we may as well try
111        * to continue anyhow
112        */
113       
114       dev_null_fd = open ("/dev/null", O_RDWR);
115       if (dev_null_fd >= 0)
116         {
117           dup2 (dev_null_fd, 0);
118           dup2 (dev_null_fd, 1);
119           
120           s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
121           if (s == NULL || *s == '\0')
122             dup2 (dev_null_fd, 2);
123           else
124             _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
125         }
126
127       if (!keep_umask)
128         {
129           /* Get a predictable umask */
130           _dbus_verbose ("setting umask\n");
131           umask (022);
132         }
133
134       _dbus_verbose ("calling setsid()\n");
135       if (setsid () == -1)
136         _dbus_assert_not_reached ("setsid() failed");
137       
138       break;
139
140     default:
141       if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
142                                              child_pid, error))
143         {
144           _dbus_verbose ("pid file or pipe write failed: %s\n",
145                          error->message);
146           kill (child_pid, SIGTERM);
147           return FALSE;
148         }
149
150       _dbus_verbose ("parent exiting\n");
151       _exit (0);
152       break;
153     }
154   
155   return TRUE;
156 }
157
158
159 /**
160  * Creates a file containing the process ID.
161  *
162  * @param filename the filename to write to
163  * @param pid our process ID
164  * @param error return location for errors
165  * @returns #FALSE on failure
166  */
167 static dbus_bool_t
168 _dbus_write_pid_file (const DBusString *filename,
169                       unsigned long     pid,
170                       DBusError        *error)
171 {
172   const char *cfilename;
173   int fd;
174   FILE *f;
175
176   cfilename = _dbus_string_get_const_data (filename);
177   
178   fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
179   
180   if (fd < 0)
181     {
182       dbus_set_error (error, _dbus_error_from_errno (errno),
183                       "Failed to open \"%s\": %s", cfilename,
184                       _dbus_strerror (errno));
185       return FALSE;
186     }
187
188   if ((f = fdopen (fd, "w")) == NULL)
189     {
190       dbus_set_error (error, _dbus_error_from_errno (errno),
191                       "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
192       _dbus_close (fd, NULL);
193       return FALSE;
194     }
195   
196   if (fprintf (f, "%lu\n", pid) < 0)
197     {
198       dbus_set_error (error, _dbus_error_from_errno (errno),
199                       "Failed to write to \"%s\": %s", cfilename,
200                       _dbus_strerror (errno));
201       
202       fclose (f);
203       return FALSE;
204     }
205
206   if (fclose (f) == EOF)
207     {
208       dbus_set_error (error, _dbus_error_from_errno (errno),
209                       "Failed to close \"%s\": %s", cfilename,
210                       _dbus_strerror (errno));
211       return FALSE;
212     }
213   
214   return TRUE;
215 }
216
217 /**
218  * Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
219  * pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
220  * NULL.
221  *
222  * @param pidfile the file to write to or #NULL
223  * @param print_pid_pipe the pipe to write to or #NULL
224  * @param pid_to_write the pid to write out
225  * @param error error on failure
226  * @returns FALSE if error is set
227  */
228 dbus_bool_t
229 _dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
230                                   DBusPipe         *print_pid_pipe,
231                                   dbus_pid_t        pid_to_write,
232                                   DBusError        *error)
233 {
234   if (pidfile)
235     {
236       _dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
237       if (!_dbus_write_pid_file (pidfile,
238                                  pid_to_write,
239                                  error))
240         {
241           _dbus_verbose ("pid file write failed\n");
242           _DBUS_ASSERT_ERROR_IS_SET(error);
243           return FALSE;
244         }
245     }
246   else
247     {
248       _dbus_verbose ("No pid file requested\n");
249     }
250
251   if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
252     {
253       DBusString pid;
254       int bytes;
255
256       _dbus_verbose ("writing our pid to pipe %d\n", print_pid_pipe->fd_or_handle);
257       
258       if (!_dbus_string_init (&pid))
259         {
260           _DBUS_SET_OOM (error);
261           return FALSE;
262         }
263           
264       if (!_dbus_string_append_int (&pid, pid_to_write) ||
265           !_dbus_string_append (&pid, "\n"))
266         {
267           _dbus_string_free (&pid);
268           _DBUS_SET_OOM (error);
269           return FALSE;
270         }
271           
272       bytes = _dbus_string_get_length (&pid);
273       if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
274         {
275           /* _dbus_pipe_write sets error only on failure, not short write */
276           if (error != NULL && !dbus_error_is_set(error))
277             {
278               dbus_set_error (error, DBUS_ERROR_FAILED,
279                               "Printing message bus PID: did not write enough bytes\n");
280             }
281           _dbus_string_free (&pid);
282           return FALSE;
283         }
284           
285       _dbus_string_free (&pid);
286     }
287   else
288     {
289       _dbus_verbose ("No pid pipe to write to\n");
290     }
291
292   return TRUE;
293 }
294
295 /**
296  * Verify that after the fork we can successfully change to this user.
297  *
298  * @param user the username given in the daemon configuration
299  * @returns #TRUE if username is valid
300  */
301 dbus_bool_t
302 _dbus_verify_daemon_user (const char *user)
303 {
304   DBusString u;
305
306   _dbus_string_init_const (&u, user);
307
308   return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
309 }
310
311 /**
312  * Changes the user and group the bus is running as.
313  *
314  * @param user the user to become
315  * @param error return location for errors
316  * @returns #FALSE on failure
317  */
318 dbus_bool_t
319 _dbus_change_to_daemon_user  (const char    *user,
320                               DBusError     *error)
321 {
322   dbus_uid_t uid;
323   dbus_gid_t gid;
324   DBusString u;
325 #ifdef HAVE_LIBAUDIT
326   dbus_bool_t we_were_root;
327   cap_t new_caps;
328 #endif
329   
330   _dbus_string_init_const (&u, user);
331   
332   if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
333     {
334       dbus_set_error (error, DBUS_ERROR_FAILED,
335                       "User '%s' does not appear to exist?",
336                       user);
337       return FALSE;
338     }
339   
340 #ifdef HAVE_LIBAUDIT
341   we_were_root = _dbus_geteuid () == 0;
342   new_caps = NULL;
343   /* have a tmp set of caps that we use to transition to the usr/grp dbus should
344    * run as ... doesn't really help. But keeps people happy.
345    */
346     
347   if (we_were_root)
348     {
349       cap_value_t new_cap_list[] = { CAP_AUDIT_WRITE };
350       cap_value_t tmp_cap_list[] = { CAP_AUDIT_WRITE, CAP_SETUID, CAP_SETGID };
351       cap_t tmp_caps = cap_init();
352         
353       if (!tmp_caps || !(new_caps = cap_init ()))
354         {
355           dbus_set_error (error, DBUS_ERROR_FAILED,
356                           "Failed to initialize drop of capabilities: %s\n",
357                           _dbus_strerror (errno));
358
359           if (tmp_caps)
360             cap_free (tmp_caps);
361
362           return FALSE;
363         }
364
365       /* assume these work... */
366       cap_set_flag (new_caps, CAP_PERMITTED, 1, new_cap_list, CAP_SET);
367       cap_set_flag (new_caps, CAP_EFFECTIVE, 1, new_cap_list, CAP_SET);
368       cap_set_flag (tmp_caps, CAP_PERMITTED, 3, tmp_cap_list, CAP_SET);
369       cap_set_flag (tmp_caps, CAP_EFFECTIVE, 3, tmp_cap_list, CAP_SET);
370       
371       if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1)
372         {
373           dbus_set_error (error, _dbus_error_from_errno (errno),
374                           "Failed to set keep-capabilities: %s\n",
375                           _dbus_strerror (errno));
376           cap_free (tmp_caps);
377           goto fail;
378         }
379         
380       if (cap_set_proc (tmp_caps) == -1)
381         {
382           dbus_set_error (error, DBUS_ERROR_FAILED,
383                           "Failed to drop capabilities: %s\n",
384                           _dbus_strerror (errno));
385           cap_free (tmp_caps);
386           goto fail;
387         }
388       cap_free (tmp_caps);
389     }
390 #endif /* HAVE_LIBAUDIT */
391   
392   /* setgroups() only works if we are a privileged process,
393    * so we don't return error on failure; the only possible
394    * failure is that we don't have perms to do it.
395    *
396    * not sure this is right, maybe if setuid()
397    * is going to work then setgroups() should also work.
398    */
399   if (setgroups (0, NULL) < 0)
400     _dbus_warn ("Failed to drop supplementary groups: %s\n",
401                 _dbus_strerror (errno));
402   
403   /* Set GID first, or the setuid may remove our permission
404    * to change the GID
405    */
406   if (setgid (gid) < 0)
407     {
408       dbus_set_error (error, _dbus_error_from_errno (errno),
409                       "Failed to set GID to %lu: %s", gid,
410                       _dbus_strerror (errno));
411       goto fail;
412     }
413   
414   if (setuid (uid) < 0)
415     {
416       dbus_set_error (error, _dbus_error_from_errno (errno),
417                       "Failed to set UID to %lu: %s", uid,
418                       _dbus_strerror (errno));
419       goto fail;
420     }
421   
422 #ifdef HAVE_LIBAUDIT
423   if (we_were_root)
424     {
425       if (cap_set_proc (new_caps))
426         {
427           dbus_set_error (error, DBUS_ERROR_FAILED,
428                           "Failed to drop capabilities: %s\n",
429                           _dbus_strerror (errno));
430           goto fail;
431         }
432       cap_free (new_caps);
433
434       /* should always work, if it did above */      
435       if (prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0) == -1)
436         {
437           dbus_set_error (error, _dbus_error_from_errno (errno),
438                           "Failed to unset keep-capabilities: %s\n",
439                           _dbus_strerror (errno));
440           return FALSE;
441         }
442     }
443 #endif
444
445  return TRUE;
446
447  fail:
448 #ifdef HAVE_LIBAUDIT
449  if (!we_were_root)
450    {
451      /* should always work, if it did above */
452      prctl (PR_SET_KEEPCAPS, 0, 0, 0, 0);
453      cap_free (new_caps);
454    }
455 #endif
456
457  return FALSE;
458 }
459
460 void 
461 _dbus_init_system_log (void)
462 {
463   openlog ("dbus", LOG_PID, LOG_DAEMON);
464 }
465
466 /**
467  * Log an informative message.  Intended for use primarily by
468  * the system bus.
469  *
470  * @param msg a printf-style format string
471  * @param args arguments for the format string
472  */
473 void 
474 _dbus_log_info (const char *msg, va_list args)
475 {
476   vsyslog (LOG_DAEMON|LOG_NOTICE, msg, args);
477 }
478
479 /**
480  * Log a security-related message.  Intended for use primarily by
481  * the system bus.
482  *
483  * @param msg a printf-style format string
484  * @param args arguments for the format string
485  */
486 void 
487 _dbus_log_security (const char *msg, va_list args)
488 {
489   vsyslog (LOG_AUTH|LOG_NOTICE, msg, args);
490 }
491
492 /** Installs a UNIX signal handler
493  *
494  * @param sig the signal to handle
495  * @param handler the handler
496  */
497 void
498 _dbus_set_signal_handler (int               sig,
499                           DBusSignalHandler handler)
500 {
501   struct sigaction act;
502   sigset_t empty_mask;
503   
504   sigemptyset (&empty_mask);
505   act.sa_handler = handler;
506   act.sa_mask    = empty_mask;
507   act.sa_flags   = 0;
508   sigaction (sig,  &act, NULL);
509 }
510
511
512 /**
513  * Removes a directory; Directory must be empty
514  * 
515  * @param filename directory filename
516  * @param error initialized error object
517  * @returns #TRUE on success
518  */
519 dbus_bool_t
520 _dbus_delete_directory (const DBusString *filename,
521                         DBusError        *error)
522 {
523   const char *filename_c;
524   
525   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
526
527   filename_c = _dbus_string_get_const_data (filename);
528
529   if (rmdir (filename_c) != 0)
530     {
531       dbus_set_error (error, DBUS_ERROR_FAILED,
532                       "Failed to remove directory %s: %s\n",
533                       filename_c, _dbus_strerror (errno));
534       return FALSE;
535     }
536   
537   return TRUE;
538 }
539
540 /** Checks if a file exists
541 *
542 * @param file full path to the file
543 * @returns #TRUE if file exists
544 */
545 dbus_bool_t 
546 _dbus_file_exists (const char *file)
547 {
548   return (access (file, F_OK) == 0);
549 }
550
551 /** Checks if user is at the console
552 *
553 * @param username user to check
554 * @param error return location for errors
555 * @returns #TRUE is the user is at the consolei and there are no errors
556 */
557 dbus_bool_t 
558 _dbus_user_at_console (const char *username,
559                        DBusError  *error)
560 {
561
562   DBusString f;
563   dbus_bool_t result;
564
565   result = FALSE;
566   if (!_dbus_string_init (&f))
567     {
568       _DBUS_SET_OOM (error);
569       return FALSE;
570     }
571
572   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
573     {
574       _DBUS_SET_OOM (error);
575       goto out;
576     }
577
578
579   if (!_dbus_string_append (&f, username))
580     {
581       _DBUS_SET_OOM (error);
582       goto out;
583     }
584
585   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
586
587  out:
588   _dbus_string_free (&f);
589
590   return result;
591 }
592
593
594 /**
595  * Checks whether the filename is an absolute path
596  *
597  * @param filename the filename
598  * @returns #TRUE if an absolute path
599  */
600 dbus_bool_t
601 _dbus_path_is_absolute (const DBusString *filename)
602 {
603   if (_dbus_string_get_length (filename) > 0)
604     return _dbus_string_get_byte (filename, 0) == '/';
605   else
606     return FALSE;
607 }
608
609 /**
610  * stat() wrapper.
611  *
612  * @param filename the filename to stat
613  * @param statbuf the stat info to fill in
614  * @param error return location for error
615  * @returns #FALSE if error was set
616  */
617 dbus_bool_t
618 _dbus_stat (const DBusString *filename,
619             DBusStat         *statbuf,
620             DBusError        *error)
621 {
622   const char *filename_c;
623   struct stat sb;
624
625   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
626   
627   filename_c = _dbus_string_get_const_data (filename);
628
629   if (stat (filename_c, &sb) < 0)
630     {
631       dbus_set_error (error, _dbus_error_from_errno (errno),
632                       "%s", _dbus_strerror (errno));
633       return FALSE;
634     }
635
636   statbuf->mode = sb.st_mode;
637   statbuf->nlink = sb.st_nlink;
638   statbuf->uid = sb.st_uid;
639   statbuf->gid = sb.st_gid;
640   statbuf->size = sb.st_size;
641   statbuf->atime = sb.st_atime;
642   statbuf->mtime = sb.st_mtime;
643   statbuf->ctime = sb.st_ctime;
644
645   return TRUE;
646 }
647
648
649 /**
650  * Internals of directory iterator
651  */
652 struct DBusDirIter
653 {
654   DIR *d; /**< The DIR* from opendir() */
655   
656 };
657
658 /**
659  * Open a directory to iterate over.
660  *
661  * @param filename the directory name
662  * @param error exception return object or #NULL
663  * @returns new iterator, or #NULL on error
664  */
665 DBusDirIter*
666 _dbus_directory_open (const DBusString *filename,
667                       DBusError        *error)
668 {
669   DIR *d;
670   DBusDirIter *iter;
671   const char *filename_c;
672
673   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
674   
675   filename_c = _dbus_string_get_const_data (filename);
676
677   d = opendir (filename_c);
678   if (d == NULL)
679     {
680       dbus_set_error (error, _dbus_error_from_errno (errno),
681                       "Failed to read directory \"%s\": %s",
682                       filename_c,
683                       _dbus_strerror (errno));
684       return NULL;
685     }
686   iter = dbus_new0 (DBusDirIter, 1);
687   if (iter == NULL)
688     {
689       closedir (d);
690       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
691                       "Could not allocate memory for directory iterator");
692       return NULL;
693     }
694
695   iter->d = d;
696
697   return iter;
698 }
699
700 /* Calculate the required buffer size (in bytes) for directory
701  * entries read from the given directory handle.  Return -1 if this
702  * this cannot be done. 
703  *
704  * If you use autoconf, include fpathconf and dirfd in your
705  * AC_CHECK_FUNCS list.  Otherwise use some other method to detect
706  * and use them where available.
707  */
708 static dbus_bool_t
709 dirent_buf_size(DIR * dirp, size_t *size)
710 {
711  long name_max;
712 #   if defined(HAVE_FPATHCONF) && defined(_PC_NAME_MAX)
713 #      if defined(HAVE_DIRFD)
714           name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
715 #      elif defined(HAVE_DDFD)
716           name_max = fpathconf(dirp->dd_fd, _PC_NAME_MAX);
717 #      else
718           name_max = fpathconf(dirp->__dd_fd, _PC_NAME_MAX);
719 #      endif /* HAVE_DIRFD */
720      if (name_max == -1)
721 #           if defined(NAME_MAX)
722              name_max = NAME_MAX;
723 #           else
724              return FALSE;
725 #           endif
726 #   elif defined(MAXNAMELEN)
727      name_max = MAXNAMELEN;
728 #   else
729 #       if defined(NAME_MAX)
730          name_max = NAME_MAX;
731 #       else
732 #           error "buffer size for readdir_r cannot be determined"
733 #       endif
734 #   endif
735   if (size)
736     *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
737   else
738     return FALSE;
739
740   return TRUE;
741 }
742
743 /**
744  * Get next file in the directory. Will not return "." or ".."  on
745  * UNIX. If an error occurs, the contents of "filename" are
746  * undefined. The error is never set if the function succeeds.
747  *
748  * @param iter the iterator
749  * @param filename string to be set to the next file in the dir
750  * @param error return location for error
751  * @returns #TRUE if filename was filled in with a new filename
752  */
753 dbus_bool_t
754 _dbus_directory_get_next_file (DBusDirIter      *iter,
755                                DBusString       *filename,
756                                DBusError        *error)
757 {
758   struct dirent *d, *ent;
759   size_t buf_size;
760   int err;
761
762   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
763  
764   if (!dirent_buf_size (iter->d, &buf_size))
765     {
766       dbus_set_error (error, DBUS_ERROR_FAILED,
767                       "Can't calculate buffer size when reading directory");
768       return FALSE;
769     }
770
771   d = (struct dirent *)dbus_malloc (buf_size);
772   if (!d)
773     {
774       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
775                       "No memory to read directory entry");
776       return FALSE;
777     }
778
779  again:
780   err = readdir_r (iter->d, d, &ent);
781   if (err || !ent)
782     {
783       if (err != 0)
784         dbus_set_error (error,
785                         _dbus_error_from_errno (err),
786                         "%s", _dbus_strerror (err));
787
788       dbus_free (d);
789       return FALSE;
790     }
791   else if (ent->d_name[0] == '.' &&
792            (ent->d_name[1] == '\0' ||
793             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
794     goto again;
795   else
796     {
797       _dbus_string_set_length (filename, 0);
798       if (!_dbus_string_append (filename, ent->d_name))
799         {
800           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
801                           "No memory to read directory entry");
802           dbus_free (d);
803           return FALSE;
804         }
805       else
806         {
807           dbus_free (d);
808           return TRUE;
809         }
810     }
811 }
812
813 /**
814  * Closes a directory iteration.
815  */
816 void
817 _dbus_directory_close (DBusDirIter *iter)
818 {
819   closedir (iter->d);
820   dbus_free (iter);
821 }
822
823 static dbus_bool_t
824 fill_user_info_from_group (struct group  *g,
825                            DBusGroupInfo *info,
826                            DBusError     *error)
827 {
828   _dbus_assert (g->gr_name != NULL);
829   
830   info->gid = g->gr_gid;
831   info->groupname = _dbus_strdup (g->gr_name);
832
833   /* info->members = dbus_strdupv (g->gr_mem) */
834   
835   if (info->groupname == NULL)
836     {
837       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
838       return FALSE;
839     }
840
841   return TRUE;
842 }
843
844 static dbus_bool_t
845 fill_group_info (DBusGroupInfo    *info,
846                  dbus_gid_t        gid,
847                  const DBusString *groupname,
848                  DBusError        *error)
849 {
850   const char *group_c_str;
851
852   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
853   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
854
855   if (groupname)
856     group_c_str = _dbus_string_get_const_data (groupname);
857   else
858     group_c_str = NULL;
859   
860   /* For now assuming that the getgrnam() and getgrgid() flavors
861    * always correspond to the pwnam flavors, if not we have
862    * to add more configure checks.
863    */
864   
865 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
866   {
867     struct group *g;
868     int result;
869     size_t buflen;
870     char *buf;
871     struct group g_str;
872     dbus_bool_t b;
873
874     /* retrieve maximum needed size for buf */
875     buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
876
877     /* sysconf actually returns a long, but everything else expects size_t,
878      * so just recast here.
879      * https://bugs.freedesktop.org/show_bug.cgi?id=17061
880      */
881     if ((long) buflen <= 0)
882       buflen = 1024;
883
884     result = -1;
885     while (1)
886       {
887         buf = dbus_malloc (buflen);
888         if (buf == NULL)
889           {
890             dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
891             return FALSE;
892           }
893
894         g = NULL;
895 #ifdef HAVE_POSIX_GETPWNAM_R
896         if (group_c_str)
897           result = getgrnam_r (group_c_str, &g_str, buf, buflen,
898                                &g);
899         else
900           result = getgrgid_r (gid, &g_str, buf, buflen,
901                                &g);
902 #else
903         g = getgrnam_r (group_c_str, &g_str, buf, buflen);
904         result = 0;
905 #endif /* !HAVE_POSIX_GETPWNAM_R */
906         /* Try a bigger buffer if ERANGE was returned:
907            https://bugs.freedesktop.org/show_bug.cgi?id=16727
908         */
909         if (result == ERANGE && buflen < 512 * 1024)
910           {
911             dbus_free (buf);
912             buflen *= 2;
913           }
914         else
915           {
916             break;
917           }
918       }
919
920     if (result == 0 && g == &g_str)
921       {
922         b = fill_user_info_from_group (g, info, error);
923         dbus_free (buf);
924         return b;
925       }
926     else
927       {
928         dbus_set_error (error, _dbus_error_from_errno (errno),
929                         "Group %s unknown or failed to look it up\n",
930                         group_c_str ? group_c_str : "???");
931         dbus_free (buf);
932         return FALSE;
933       }
934   }
935 #else /* ! HAVE_GETPWNAM_R */
936   {
937     /* I guess we're screwed on thread safety here */
938     struct group *g;
939
940     g = getgrnam (group_c_str);
941
942     if (g != NULL)
943       {
944         return fill_user_info_from_group (g, info, error);
945       }
946     else
947       {
948         dbus_set_error (error, _dbus_error_from_errno (errno),
949                         "Group %s unknown or failed to look it up\n",
950                         group_c_str ? group_c_str : "???");
951         return FALSE;
952       }
953   }
954 #endif  /* ! HAVE_GETPWNAM_R */
955 }
956
957 /**
958  * Initializes the given DBusGroupInfo struct
959  * with information about the given group name.
960  *
961  * @param info the group info struct
962  * @param groupname name of group
963  * @param error the error return
964  * @returns #FALSE if error is set
965  */
966 dbus_bool_t
967 _dbus_group_info_fill (DBusGroupInfo    *info,
968                        const DBusString *groupname,
969                        DBusError        *error)
970 {
971   return fill_group_info (info, DBUS_GID_UNSET,
972                           groupname, error);
973
974 }
975
976 /**
977  * Initializes the given DBusGroupInfo struct
978  * with information about the given group ID.
979  *
980  * @param info the group info struct
981  * @param gid group ID
982  * @param error the error return
983  * @returns #FALSE if error is set
984  */
985 dbus_bool_t
986 _dbus_group_info_fill_gid (DBusGroupInfo *info,
987                            dbus_gid_t     gid,
988                            DBusError     *error)
989 {
990   return fill_group_info (info, gid, NULL, error);
991 }
992
993 /**
994  * Parse a UNIX user from the bus config file. On Windows, this should
995  * simply always fail (just return #FALSE).
996  *
997  * @param username the username text
998  * @param uid_p place to return the uid
999  * @returns #TRUE on success
1000  */
1001 dbus_bool_t
1002 _dbus_parse_unix_user_from_config (const DBusString  *username,
1003                                    dbus_uid_t        *uid_p)
1004 {
1005   return _dbus_get_user_id (username, uid_p);
1006
1007 }
1008
1009 /**
1010  * Parse a UNIX group from the bus config file. On Windows, this should
1011  * simply always fail (just return #FALSE).
1012  *
1013  * @param groupname the groupname text
1014  * @param gid_p place to return the gid
1015  * @returns #TRUE on success
1016  */
1017 dbus_bool_t
1018 _dbus_parse_unix_group_from_config (const DBusString  *groupname,
1019                                     dbus_gid_t        *gid_p)
1020 {
1021   return _dbus_get_group_id (groupname, gid_p);
1022 }
1023
1024 /**
1025  * Gets all groups corresponding to the given UNIX user ID. On UNIX,
1026  * just calls _dbus_groups_from_uid(). On Windows, should always
1027  * fail since we don't know any UNIX groups.
1028  *
1029  * @param uid the UID
1030  * @param group_ids return location for array of group IDs
1031  * @param n_group_ids return location for length of returned array
1032  * @returns #TRUE if the UID existed and we got some credentials
1033  */
1034 dbus_bool_t
1035 _dbus_unix_groups_from_uid (dbus_uid_t            uid,
1036                             dbus_gid_t          **group_ids,
1037                             int                  *n_group_ids)
1038 {
1039   return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
1040 }
1041
1042 /**
1043  * Checks to see if the UNIX user ID is at the console.
1044  * Should always fail on Windows (set the error to
1045  * #DBUS_ERROR_NOT_SUPPORTED).
1046  *
1047  * @param uid UID of person to check 
1048  * @param error return location for errors
1049  * @returns #TRUE if the UID is the same as the console user and there are no errors
1050  */
1051 dbus_bool_t
1052 _dbus_unix_user_is_at_console (dbus_uid_t         uid,
1053                                DBusError         *error)
1054 {
1055   return _dbus_is_console_user (uid, error);
1056
1057 }
1058
1059 /**
1060  * Checks to see if the UNIX user ID matches the UID of
1061  * the process. Should always return #FALSE on Windows.
1062  *
1063  * @param uid the UNIX user ID
1064  * @returns #TRUE if this uid owns the process.
1065  */
1066 dbus_bool_t
1067 _dbus_unix_user_is_process_owner (dbus_uid_t uid)
1068 {
1069   return uid == _dbus_geteuid ();
1070 }
1071
1072 /**
1073  * Checks to see if the Windows user SID matches the owner of
1074  * the process. Should always return #FALSE on UNIX.
1075  *
1076  * @param windows_sid the Windows user SID
1077  * @returns #TRUE if this user owns the process.
1078  */
1079 dbus_bool_t
1080 _dbus_windows_user_is_process_owner (const char *windows_sid)
1081 {
1082   return FALSE;
1083 }
1084
1085 /** @} */ /* End of DBusInternalsUtils functions */
1086
1087 /**
1088  * @addtogroup DBusString
1089  *
1090  * @{
1091  */
1092 /**
1093  * Get the directory name from a complete filename
1094  * @param filename the filename
1095  * @param dirname string to append directory name to
1096  * @returns #FALSE if no memory
1097  */
1098 dbus_bool_t
1099 _dbus_string_get_dirname  (const DBusString *filename,
1100                            DBusString       *dirname)
1101 {
1102   int sep;
1103   
1104   _dbus_assert (filename != dirname);
1105   _dbus_assert (filename != NULL);
1106   _dbus_assert (dirname != NULL);
1107
1108   /* Ignore any separators on the end */
1109   sep = _dbus_string_get_length (filename);
1110   if (sep == 0)
1111     return _dbus_string_append (dirname, "."); /* empty string passed in */
1112     
1113   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1114     --sep;
1115
1116   _dbus_assert (sep >= 0);
1117   
1118   if (sep == 0)
1119     return _dbus_string_append (dirname, "/");
1120   
1121   /* Now find the previous separator */
1122   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
1123   if (sep < 0)
1124     return _dbus_string_append (dirname, ".");
1125   
1126   /* skip multiple separators */
1127   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
1128     --sep;
1129
1130   _dbus_assert (sep >= 0);
1131   
1132   if (sep == 0 &&
1133       _dbus_string_get_byte (filename, 0) == '/')
1134     return _dbus_string_append (dirname, "/");
1135   else
1136     return _dbus_string_copy_len (filename, 0, sep - 0,
1137                                   dirname, _dbus_string_get_length (dirname));
1138 }
1139 /** @} */ /* DBusString stuff */
1140
1141 static void
1142 string_squash_nonprintable (DBusString *str)
1143 {
1144   char *buf;
1145   int i, len; 
1146   
1147   buf = _dbus_string_get_data (str);
1148   len = _dbus_string_get_length (str);
1149   
1150   for (i = 0; i < len; i++)
1151     {
1152           unsigned char c = (unsigned char) buf[i];
1153       if (c == '\0')
1154         c = ' ';
1155       else if (c < 0x20 || c > 127)
1156         c = '?';
1157     }
1158 }
1159
1160 /**
1161  * Get a printable string describing the command used to execute
1162  * the process with pid.  This string should only be used for
1163  * informative purposes such as logging; it may not be trusted.
1164  * 
1165  * The command is guaranteed to be printable ASCII and no longer
1166  * than max_len.
1167  * 
1168  * @param pid Process id
1169  * @param str Append command to this string
1170  * @param max_len Maximum length of returned command
1171  * @param error return location for errors
1172  * @returns #FALSE on error
1173  */
1174 dbus_bool_t 
1175 _dbus_command_for_pid (unsigned long  pid,
1176                        DBusString    *str,
1177                        int            max_len,
1178                        DBusError     *error)
1179 {
1180   /* This is all Linux-specific for now */
1181   DBusString path;
1182   DBusString cmdline;
1183   int fd;
1184   
1185   if (!_dbus_string_init (&path)) 
1186     {
1187       _DBUS_SET_OOM (error);
1188       return FALSE;
1189     }
1190   
1191   if (!_dbus_string_init (&cmdline))
1192     {
1193       _DBUS_SET_OOM (error);
1194       _dbus_string_free (&path);
1195       return FALSE;
1196     }
1197   
1198   if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
1199     goto oom;
1200   
1201   fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
1202   if (fd < 0) 
1203     {
1204       dbus_set_error (error,
1205                       _dbus_error_from_errno (errno),
1206                       "Failed to open \"%s\": %s",
1207                       _dbus_string_get_const_data (&path),
1208                       _dbus_strerror (errno));
1209       goto fail;
1210     }
1211   
1212   if (!_dbus_read (fd, &cmdline, max_len))
1213     {
1214       dbus_set_error (error,
1215                       _dbus_error_from_errno (errno),
1216                       "Failed to read from \"%s\": %s",
1217                       _dbus_string_get_const_data (&path),
1218                       _dbus_strerror (errno));      
1219       goto fail;
1220     }
1221   
1222   if (!_dbus_close (fd, error))
1223     goto fail;
1224   
1225   string_squash_nonprintable (&cmdline);  
1226   
1227   if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
1228     goto oom;
1229   
1230   _dbus_string_free (&cmdline);  
1231   _dbus_string_free (&path);
1232   return TRUE;
1233 oom:
1234   _DBUS_SET_OOM (error);
1235 fail:
1236   _dbus_string_free (&cmdline);
1237   _dbus_string_free (&path);
1238   return FALSE;
1239 }
1240