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