2006-09-16 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-sysdeps-util-unix.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps-util-unix.c Would be in dbus-sysdeps-unix.c, but not used in libdbus
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
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
50
51 /**
52  * @addtogroup DBusInternalsUtils
53  * @{
54  */
55
56 /**
57  * Does the chdir, fork, setsid, etc. to become a daemon process.
58  *
59  * @param pidfile #NULL, or pidfile to create
60  * @param print_pid_fd file descriptor to print daemon's pid to, or -1 for none
61  * @param error return location for errors
62  * @returns #FALSE on failure
63  */
64 dbus_bool_t
65 _dbus_become_daemon (const DBusString *pidfile,
66                      int               print_pid_fd,
67                      DBusError        *error)
68 {
69   const char *s;
70   pid_t child_pid;
71   int dev_null_fd;
72
73   _dbus_verbose ("Becoming a daemon...\n");
74
75   _dbus_verbose ("chdir to /\n");
76   if (chdir ("/") < 0)
77     {
78       dbus_set_error (error, DBUS_ERROR_FAILED,
79                       "Could not chdir() to root directory");
80       return FALSE;
81     }
82
83   _dbus_verbose ("forking...\n");
84   switch ((child_pid = fork ()))
85     {
86     case -1:
87       _dbus_verbose ("fork failed\n");
88       dbus_set_error (error, _dbus_error_from_errno (errno),
89                       "Failed to fork daemon: %s", _dbus_strerror (errno));
90       return FALSE;
91       break;
92
93     case 0:
94       _dbus_verbose ("in child, closing std file descriptors\n");
95
96       /* silently ignore failures here, if someone
97        * doesn't have /dev/null we may as well try
98        * to continue anyhow
99        */
100       
101       dev_null_fd = open ("/dev/null", O_RDWR);
102       if (dev_null_fd >= 0)
103         {
104           dup2 (dev_null_fd, 0);
105           dup2 (dev_null_fd, 1);
106           
107           s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
108           if (s == NULL || *s == '\0')
109             dup2 (dev_null_fd, 2);
110           else
111             _dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
112         }
113
114       /* Get a predictable umask */
115       _dbus_verbose ("setting umask\n");
116       umask (022);
117       break;
118
119     default:
120       if (pidfile)
121         {
122           _dbus_verbose ("parent writing pid file\n");
123           if (!_dbus_write_pid_file (pidfile,
124                                      child_pid,
125                                      error))
126             {
127               _dbus_verbose ("pid file write failed, killing child\n");
128               kill (child_pid, SIGTERM);
129               return FALSE;
130             }
131         }
132
133       /* Write PID if requested */
134       if (print_pid_fd >= 0)
135         {
136           DBusString pid;
137           int bytes;
138           
139           if (!_dbus_string_init (&pid))
140             {
141               _DBUS_SET_OOM (error);
142               kill (child_pid, SIGTERM);
143               return FALSE;
144             }
145           
146           if (!_dbus_string_append_int (&pid, child_pid) ||
147               !_dbus_string_append (&pid, "\n"))
148             {
149               _dbus_string_free (&pid);
150               _DBUS_SET_OOM (error);
151               kill (child_pid, SIGTERM);
152               return FALSE;
153             }
154           
155           bytes = _dbus_string_get_length (&pid);
156           if (_dbus_write_socket (print_pid_fd, &pid, 0, bytes) != bytes)
157             {
158               dbus_set_error (error, DBUS_ERROR_FAILED,
159                               "Printing message bus PID: %s\n",
160                               _dbus_strerror (errno));
161               _dbus_string_free (&pid);
162               kill (child_pid, SIGTERM);
163               return FALSE;
164             }
165           
166           _dbus_string_free (&pid);
167         }
168       _dbus_verbose ("parent exiting\n");
169       _exit (0);
170       break;
171     }
172
173   _dbus_verbose ("calling setsid()\n");
174   if (setsid () == -1)
175     _dbus_assert_not_reached ("setsid() failed");
176   
177   return TRUE;
178 }
179
180
181 /**
182  * Creates a file containing the process ID.
183  *
184  * @param filename the filename to write to
185  * @param pid our process ID
186  * @param error return location for errors
187  * @returns #FALSE on failure
188  */
189 dbus_bool_t
190 _dbus_write_pid_file (const DBusString *filename,
191                       unsigned long     pid,
192                       DBusError        *error)
193 {
194   const char *cfilename;
195   int fd;
196   FILE *f;
197
198   cfilename = _dbus_string_get_const_data (filename);
199   
200   fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
201   
202   if (fd < 0)
203     {
204       dbus_set_error (error, _dbus_error_from_errno (errno),
205                       "Failed to open \"%s\": %s", cfilename,
206                       _dbus_strerror (errno));
207       return FALSE;
208     }
209
210   if ((f = fdopen (fd, "w")) == NULL)
211     {
212       dbus_set_error (error, _dbus_error_from_errno (errno),
213                       "Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
214       _dbus_close (fd, NULL);
215       return FALSE;
216     }
217   
218   if (fprintf (f, "%lu\n", pid) < 0)
219     {
220       dbus_set_error (error, _dbus_error_from_errno (errno),
221                       "Failed to write to \"%s\": %s", cfilename,
222                       _dbus_strerror (errno));
223       
224       fclose (f);
225       return FALSE;
226     }
227
228   if (fclose (f) == EOF)
229     {
230       dbus_set_error (error, _dbus_error_from_errno (errno),
231                       "Failed to close \"%s\": %s", cfilename,
232                       _dbus_strerror (errno));
233       return FALSE;
234     }
235   
236   return TRUE;
237 }
238
239
240 /**
241  * Changes the user and group the bus is running as.
242  *
243  * @param uid the new user ID
244  * @param gid the new group ID
245  * @param error return location for errors
246  * @returns #FALSE on failure
247  */
248 dbus_bool_t
249 _dbus_change_identity  (dbus_uid_t     uid,
250                         dbus_gid_t     gid,
251                         DBusError     *error)
252 {
253   /* setgroups() only works if we are a privileged process,
254    * so we don't return error on failure; the only possible
255    * failure is that we don't have perms to do it.
256    *
257    * not sure this is right, maybe if setuid()
258    * is going to work then setgroups() should also work.
259    */
260   if (setgroups (0, NULL) < 0)
261     _dbus_warn ("Failed to drop supplementary groups: %s\n",
262                 _dbus_strerror (errno));
263   
264   /* Set GID first, or the setuid may remove our permission
265    * to change the GID
266    */
267   if (setgid (gid) < 0)
268     {
269       dbus_set_error (error, _dbus_error_from_errno (errno),
270                       "Failed to set GID to %lu: %s", gid,
271                       _dbus_strerror (errno));
272       return FALSE;
273     }
274   
275   if (setuid (uid) < 0)
276     {
277       dbus_set_error (error, _dbus_error_from_errno (errno),
278                       "Failed to set UID to %lu: %s", uid,
279                       _dbus_strerror (errno));
280       return FALSE;
281     }
282   
283   return TRUE;
284 }
285
286 /** Installs a UNIX signal handler
287  *
288  * @param sig the signal to handle
289  * @param handler the handler
290  */
291 void
292 _dbus_set_signal_handler (int               sig,
293                           DBusSignalHandler handler)
294 {
295   struct sigaction act;
296   sigset_t empty_mask;
297   
298   sigemptyset (&empty_mask);
299   act.sa_handler = handler;
300   act.sa_mask    = empty_mask;
301   act.sa_flags   = 0;
302   sigaction (sig,  &act, NULL);
303 }
304
305
306 /**
307  * Removes a directory; Directory must be empty
308  * 
309  * @param filename directory filename
310  * @param error initialized error object
311  * @returns #TRUE on success
312  */
313 dbus_bool_t
314 _dbus_delete_directory (const DBusString *filename,
315                         DBusError        *error)
316 {
317   const char *filename_c;
318   
319   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
320
321   filename_c = _dbus_string_get_const_data (filename);
322
323   if (rmdir (filename_c) != 0)
324     {
325       dbus_set_error (error, DBUS_ERROR_FAILED,
326                       "Failed to remove directory %s: %s\n",
327                       filename_c, _dbus_strerror (errno));
328       return FALSE;
329     }
330   
331   return TRUE;
332 }
333
334 /** Checks if a file exists
335 *
336 * @param file full path to the file
337 * @returns #TRUE if file exists
338 */
339 dbus_bool_t 
340 _dbus_file_exists (const char *file)
341 {
342   return (access (file, F_OK) == 0);
343 }
344
345 /** Checks if user is at the console
346 *
347 * @param username user to check
348 * @param error return location for errors
349 * @returns #TRUE is the user is at the consolei and there are no errors
350 */
351 dbus_bool_t 
352 _dbus_user_at_console (const char *username,
353                        DBusError  *error)
354 {
355
356   DBusString f;
357   dbus_bool_t result;
358
359   result = FALSE;
360   if (!_dbus_string_init (&f))
361     {
362       _DBUS_SET_OOM (error);
363       return FALSE;
364     }
365
366   if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
367     {
368       _DBUS_SET_OOM (error);
369       goto out;
370     }
371
372
373   if (!_dbus_string_append (&f, username))
374     {
375       _DBUS_SET_OOM (error);
376       goto out;
377     }
378
379   result = _dbus_file_exists (_dbus_string_get_const_data (&f));
380
381  out:
382   _dbus_string_free (&f);
383
384   return result;
385 }
386
387
388 /**
389  * Checks whether the filename is an absolute path
390  *
391  * @param filename the filename
392  * @returns #TRUE if an absolute path
393  */
394 dbus_bool_t
395 _dbus_path_is_absolute (const DBusString *filename)
396 {
397   if (_dbus_string_get_length (filename) > 0)
398     return _dbus_string_get_byte (filename, 0) == '/';
399   else
400     return FALSE;
401 }
402
403 /**
404  * stat() wrapper.
405  *
406  * @param filename the filename to stat
407  * @param statbuf the stat info to fill in
408  * @param error return location for error
409  * @returns #FALSE if error was set
410  */
411 dbus_bool_t
412 _dbus_stat (const DBusString *filename,
413             DBusStat         *statbuf,
414             DBusError        *error)
415 {
416   const char *filename_c;
417   struct stat sb;
418
419   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
420   
421   filename_c = _dbus_string_get_const_data (filename);
422
423   if (stat (filename_c, &sb) < 0)
424     {
425       dbus_set_error (error, _dbus_error_from_errno (errno),
426                       "%s", _dbus_strerror (errno));
427       return FALSE;
428     }
429
430   statbuf->mode = sb.st_mode;
431   statbuf->nlink = sb.st_nlink;
432   statbuf->uid = sb.st_uid;
433   statbuf->gid = sb.st_gid;
434   statbuf->size = sb.st_size;
435   statbuf->atime = sb.st_atime;
436   statbuf->mtime = sb.st_mtime;
437   statbuf->ctime = sb.st_ctime;
438
439   return TRUE;
440 }
441
442
443 /**
444  * Internals of directory iterator
445  */
446 struct DBusDirIter
447 {
448   DIR *d; /**< The DIR* from opendir() */
449   
450 };
451
452 /**
453  * Open a directory to iterate over.
454  *
455  * @param filename the directory name
456  * @param error exception return object or #NULL
457  * @returns new iterator, or #NULL on error
458  */
459 DBusDirIter*
460 _dbus_directory_open (const DBusString *filename,
461                       DBusError        *error)
462 {
463   DIR *d;
464   DBusDirIter *iter;
465   const char *filename_c;
466
467   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
468   
469   filename_c = _dbus_string_get_const_data (filename);
470
471   d = opendir (filename_c);
472   if (d == NULL)
473     {
474       dbus_set_error (error, _dbus_error_from_errno (errno),
475                       "Failed to read directory \"%s\": %s",
476                       filename_c,
477                       _dbus_strerror (errno));
478       return NULL;
479     }
480   iter = dbus_new0 (DBusDirIter, 1);
481   if (iter == NULL)
482     {
483       closedir (d);
484       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
485                       "Could not allocate memory for directory iterator");
486       return NULL;
487     }
488
489   iter->d = d;
490
491   return iter;
492 }
493
494 /* Calculate the required buffer size (in bytes) for directory
495  * entries read from the given directory handle.  Return -1 if this
496  * this cannot be done. 
497  *
498  * If you use autoconf, include fpathconf and dirfd in your
499  * AC_CHECK_FUNCS list.  Otherwise use some other method to detect
500  * and use them where available.
501  */
502 static dbus_bool_t
503 dirent_buf_size(DIR * dirp, size_t *size)
504 {
505  long name_max;
506 #   if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \
507     && defined(_PC_NAME_MAX)
508      name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
509      if (name_max == -1)
510 #           if defined(NAME_MAX)
511              name_max = NAME_MAX;
512 #           else
513              return FALSE;
514 #           endif
515 #   else
516 #       if defined(NAME_MAX)
517          name_max = NAME_MAX;
518 #       else
519 #           error "buffer size for readdir_r cannot be determined"
520 #       endif
521 #   endif
522   if (size)
523     *size = (size_t)offsetof(struct dirent, d_name) + name_max + 1;
524   else
525     return FALSE;
526
527   return TRUE;
528 }
529
530 /**
531  * Get next file in the directory. Will not return "." or ".."  on
532  * UNIX. If an error occurs, the contents of "filename" are
533  * undefined. The error is never set if the function succeeds.
534  *
535  * @param iter the iterator
536  * @param filename string to be set to the next file in the dir
537  * @param error return location for error
538  * @returns #TRUE if filename was filled in with a new filename
539  */
540 dbus_bool_t
541 _dbus_directory_get_next_file (DBusDirIter      *iter,
542                                DBusString       *filename,
543                                DBusError        *error)
544 {
545   struct dirent *d, *ent;
546   size_t buf_size;
547   int err;
548
549   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
550  
551   if (!dirent_buf_size (iter->d, &buf_size))
552     {
553       dbus_set_error (error, DBUS_ERROR_FAILED,
554                       "Can't calculate buffer size when reading directory");
555       return FALSE;
556     }
557
558   d = (struct dirent *)dbus_malloc (buf_size);
559   if (!d)
560     {
561       dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
562                       "No memory to read directory entry");
563       return FALSE;
564     }
565
566  again:
567   err = readdir_r (iter->d, d, &ent);
568   if (err || !ent)
569     {
570       if (err != 0)
571         dbus_set_error (error,
572                         _dbus_error_from_errno (err),
573                         "%s", _dbus_strerror (err));
574
575       dbus_free (d);
576       return FALSE;
577     }
578   else if (ent->d_name[0] == '.' &&
579            (ent->d_name[1] == '\0' ||
580             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
581     goto again;
582   else
583     {
584       _dbus_string_set_length (filename, 0);
585       if (!_dbus_string_append (filename, ent->d_name))
586         {
587           dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
588                           "No memory to read directory entry");
589           dbus_free (d);
590           return FALSE;
591         }
592       else
593         {
594           dbus_free (d);
595           return TRUE;
596         }
597     }
598 }
599
600 /**
601  * Closes a directory iteration.
602  */
603 void
604 _dbus_directory_close (DBusDirIter *iter)
605 {
606   closedir (iter->d);
607   dbus_free (iter);
608 }
609
610 static dbus_bool_t
611 fill_user_info_from_group (struct group  *g,
612                            DBusGroupInfo *info,
613                            DBusError     *error)
614 {
615   _dbus_assert (g->gr_name != NULL);
616   
617   info->gid = g->gr_gid;
618   info->groupname = _dbus_strdup (g->gr_name);
619
620   /* info->members = dbus_strdupv (g->gr_mem) */
621   
622   if (info->groupname == NULL)
623     {
624       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
625       return FALSE;
626     }
627
628   return TRUE;
629 }
630
631 static dbus_bool_t
632 fill_group_info (DBusGroupInfo    *info,
633                  dbus_gid_t        gid,
634                  const DBusString *groupname,
635                  DBusError        *error)
636 {
637   const char *group_c_str;
638
639   _dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
640   _dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
641
642   if (groupname)
643     group_c_str = _dbus_string_get_const_data (groupname);
644   else
645     group_c_str = NULL;
646   
647   /* For now assuming that the getgrnam() and getgrgid() flavors
648    * always correspond to the pwnam flavors, if not we have
649    * to add more configure checks.
650    */
651   
652 #if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
653   {
654     struct group *g;
655     int result;
656     char buf[1024];
657     struct group g_str;
658
659     g = NULL;
660 #ifdef HAVE_POSIX_GETPWNAM_R
661
662     if (group_c_str)
663       result = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf),
664                            &g);
665     else
666       result = getgrgid_r (gid, &g_str, buf, sizeof (buf),
667                            &g);
668 #else
669     g = getgrnam_r (group_c_str, &g_str, buf, sizeof (buf));
670     result = 0;
671 #endif /* !HAVE_POSIX_GETPWNAM_R */
672     if (result == 0 && g == &g_str)
673       {
674         return fill_user_info_from_group (g, info, error);
675       }
676     else
677       {
678         dbus_set_error (error, _dbus_error_from_errno (errno),
679                         "Group %s unknown or failed to look it up\n",
680                         group_c_str ? group_c_str : "???");
681         return FALSE;
682       }
683   }
684 #else /* ! HAVE_GETPWNAM_R */
685   {
686     /* I guess we're screwed on thread safety here */
687     struct group *g;
688
689     g = getgrnam (group_c_str);
690
691     if (g != NULL)
692       {
693         return fill_user_info_from_group (g, info, error);
694       }
695     else
696       {
697         dbus_set_error (error, _dbus_error_from_errno (errno),
698                         "Group %s unknown or failed to look it up\n",
699                         group_c_str ? group_c_str : "???");
700         return FALSE;
701       }
702   }
703 #endif  /* ! HAVE_GETPWNAM_R */
704 }
705
706 /**
707  * Initializes the given DBusGroupInfo struct
708  * with information about the given group name.
709  *
710  * @param info the group info struct
711  * @param groupname name of group
712  * @param error the error return
713  * @returns #FALSE if error is set
714  */
715 dbus_bool_t
716 _dbus_group_info_fill (DBusGroupInfo    *info,
717                        const DBusString *groupname,
718                        DBusError        *error)
719 {
720   return fill_group_info (info, DBUS_GID_UNSET,
721                           groupname, error);
722
723 }
724
725 /**
726  * Initializes the given DBusGroupInfo struct
727  * with information about the given group ID.
728  *
729  * @param info the group info struct
730  * @param gid group ID
731  * @param error the error return
732  * @returns #FALSE if error is set
733  */
734 dbus_bool_t
735 _dbus_group_info_fill_gid (DBusGroupInfo *info,
736                            dbus_gid_t     gid,
737                            DBusError     *error)
738 {
739   return fill_group_info (info, gid, NULL, error);
740 }
741
742 /** @} */ /* End of DBusInternalsUtils functions */
743
744 /**
745  * @addtogroup DBusString
746  *
747  * @{
748  */
749 /**
750  * Get the directory name from a complete filename
751  * @param filename the filename
752  * @param dirname string to append directory name to
753  * @returns #FALSE if no memory
754  */
755 dbus_bool_t
756 _dbus_string_get_dirname  (const DBusString *filename,
757                            DBusString       *dirname)
758 {
759   int sep;
760   
761   _dbus_assert (filename != dirname);
762   _dbus_assert (filename != NULL);
763   _dbus_assert (dirname != NULL);
764
765   /* Ignore any separators on the end */
766   sep = _dbus_string_get_length (filename);
767   if (sep == 0)
768     return _dbus_string_append (dirname, "."); /* empty string passed in */
769     
770   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
771     --sep;
772
773   _dbus_assert (sep >= 0);
774   
775   if (sep == 0)
776     return _dbus_string_append (dirname, "/");
777   
778   /* Now find the previous separator */
779   _dbus_string_find_byte_backward (filename, sep, '/', &sep);
780   if (sep < 0)
781     return _dbus_string_append (dirname, ".");
782   
783   /* skip multiple separators */
784   while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
785     --sep;
786
787   _dbus_assert (sep >= 0);
788   
789   if (sep == 0 &&
790       _dbus_string_get_byte (filename, 0) == '/')
791     return _dbus_string_append (dirname, "/");
792   else
793     return _dbus_string_copy_len (filename, 0, sep - 0,
794                                   dirname, _dbus_string_get_length (dirname));
795 }
796 /** @} */ /* DBusString stuff */
797