2003-01-27 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / dbus / dbus-sysdeps.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
3  * 
4  * Copyright (C) 2002  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-sysdeps.h"
26 #include <sys/types.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <sys/socket.h>
35 #include <dirent.h>
36 #include <sys/un.h>
37 #include <pwd.h>
38 #include <time.h>
39 #include <sys/time.h>
40 #include <sys/stat.h>
41
42 #ifdef HAVE_WRITEV
43 #include <sys/uio.h>
44 #endif
45 #ifdef HAVE_POLL
46 #include <sys/poll.h>
47 #endif
48
49 #ifndef O_BINARY
50 #define O_BINARY 0
51 #endif
52
53 /**
54  * @addtogroup DBusInternalsUtils
55  * @{
56  */
57 /**
58  * Aborts the program with SIGABRT (dumping core).
59  */
60 void
61 _dbus_abort (void)
62 {
63   abort ();
64   _exit (1); /* in case someone manages to ignore SIGABRT */
65 }
66
67 /**
68  * Wrapper for getenv().
69  *
70  * @param varname name of environment variable
71  * @returns value of environment variable or #NULL if unset
72  */
73 const char*
74 _dbus_getenv (const char *varname)
75 {  
76   return getenv (varname);
77 }
78
79 /**
80  * Thin wrapper around the read() system call that appends
81  * the data it reads to the DBusString buffer. It appends
82  * up to the given count, and returns the same value
83  * and same errno as read(). The only exception is that
84  * _dbus_read() handles EINTR for you.
85  *
86  * @param fd the file descriptor to read from
87  * @param buffer the buffer to append data to
88  * @param count the amount of data to read
89  * @returns the number of bytes read or -1
90  */
91 int
92 _dbus_read (int               fd,
93             DBusString       *buffer,
94             int               count)
95 {
96   int bytes_read;
97   int start;
98   char *data;
99
100   _dbus_assert (count >= 0);
101   
102   start = _dbus_string_get_length (buffer);
103
104   if (!_dbus_string_lengthen (buffer, count))
105     {
106       errno = ENOMEM;
107       return -1;
108     }
109
110   _dbus_string_get_data_len (buffer, &data, start, count);
111
112  again:
113   
114   bytes_read = read (fd, data, count);
115
116   if (bytes_read < 0)
117     {
118       if (errno == EINTR)
119         goto again;
120       else
121         {
122           /* put length back (note that this doesn't actually realloc anything) */
123           _dbus_string_set_length (buffer, start);
124           return -1;
125         }
126     }
127   else
128     {
129       /* put length back (doesn't actually realloc) */
130       _dbus_string_set_length (buffer, start + bytes_read);
131
132 #if 0
133       if (bytes_read > 0)
134         _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
135 #endif
136       
137       return bytes_read;
138     }
139 }
140
141 /**
142  * Thin wrapper around the write() system call that writes a part of a
143  * DBusString and handles EINTR for you.
144  * 
145  * @param fd the file descriptor to write
146  * @param buffer the buffer to write data from
147  * @param start the first byte in the buffer to write
148  * @param len the number of bytes to try to write
149  * @returns the number of bytes written or -1 on error
150  */
151 int
152 _dbus_write (int               fd,
153              const DBusString *buffer,
154              int               start,
155              int               len)
156 {
157   const char *data;
158   int bytes_written;
159   
160   _dbus_string_get_const_data_len (buffer, &data, start, len);
161   
162  again:
163
164   bytes_written = write (fd, data, len);
165
166   if (bytes_written < 0 && errno == EINTR)
167     goto again;
168
169 #if 0
170   if (bytes_written > 0)
171     _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
172 #endif
173   
174   return bytes_written;
175 }
176
177 /**
178  * Like _dbus_write() but will use writev() if possible
179  * to write both buffers in sequence. The return value
180  * is the number of bytes written in the first buffer,
181  * plus the number written in the second. If the first
182  * buffer is written successfully and an error occurs
183  * writing the second, the number of bytes in the first
184  * is returned (i.e. the error is ignored), on systems that
185  * don't have writev. Handles EINTR for you.
186  * The second buffer may be #NULL.
187  *
188  * @param fd the file descriptor
189  * @param buffer1 first buffer
190  * @param start1 first byte to write in first buffer
191  * @param len1 number of bytes to write from first buffer
192  * @param buffer2 second buffer, or #NULL
193  * @param start2 first byte to write in second buffer
194  * @param len2 number of bytes to write in second buffer
195  * @returns total bytes written from both buffers, or -1 on error
196  */
197 int
198 _dbus_write_two (int               fd,
199                  const DBusString *buffer1,
200                  int               start1,
201                  int               len1,
202                  const DBusString *buffer2,
203                  int               start2,
204                  int               len2)
205 {
206   _dbus_assert (buffer1 != NULL);
207   _dbus_assert (start1 >= 0);
208   _dbus_assert (start2 >= 0);
209   _dbus_assert (len1 >= 0);
210   _dbus_assert (len2 >= 0);
211   
212 #ifdef HAVE_WRITEV
213   {
214     struct iovec vectors[2];
215     const char *data1;
216     const char *data2;
217     int bytes_written;
218
219     _dbus_string_get_const_data_len (buffer1, &data1, start1, len1);
220
221     if (buffer2 != NULL)
222       _dbus_string_get_const_data_len (buffer2, &data2, start2, len2);
223     else
224       {
225         data2 = NULL;
226         start2 = 0;
227         len2 = 0;
228       }
229    
230     vectors[0].iov_base = (char*) data1;
231     vectors[0].iov_len = len1;
232     vectors[1].iov_base = (char*) data2;
233     vectors[1].iov_len = len2;
234
235   again:
236    
237     bytes_written = writev (fd,
238                             vectors,
239                             data2 ? 2 : 1);
240
241     if (bytes_written < 0 && errno == EINTR)
242       goto again;
243    
244     return bytes_written;
245   }
246 #else /* HAVE_WRITEV */
247   {
248     int ret1;
249     
250     ret1 = _dbus_write (fd, buffer1, start1, len1);
251     if (ret1 == len1 && buffer2 != NULL)
252       {
253         ret2 = _dbus_write (fd, buffer2, start2, len2);
254         if (ret2 < 0)
255           ret2 = 0; /* we can't report an error as the first write was OK */
256        
257         return ret1 + ret2;
258       }
259     else
260       return ret1;
261   }
262 #endif /* !HAVE_WRITEV */   
263 }
264
265 /**
266  * Creates a socket and connects it to the UNIX domain socket at the
267  * given path.  The connection fd is returned, and is set up as
268  * nonblocking.
269  *
270  * @param path the path to UNIX domain socket
271  * @param result return location for error code
272  * @returns connection file descriptor or -1 on error
273  */
274 int
275 _dbus_connect_unix_socket (const char     *path,
276                            DBusResultCode *result)
277 {
278   int fd;
279   struct sockaddr_un addr;  
280   
281   fd = socket (AF_LOCAL, SOCK_STREAM, 0);
282
283   if (fd < 0)
284     {
285       dbus_set_result (result,
286                        _dbus_result_from_errno (errno));
287       
288       _dbus_verbose ("Failed to create socket: %s\n",
289                      _dbus_strerror (errno)); 
290       
291       return -1;
292     }
293
294   _DBUS_ZERO (addr);
295   addr.sun_family = AF_LOCAL;
296   strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
297   addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
298   
299   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
300     {      
301       dbus_set_result (result,
302                        _dbus_result_from_errno (errno));
303
304       _dbus_verbose ("Failed to connect to socket %s: %s\n",
305                      path, _dbus_strerror (errno));
306
307       close (fd);
308       fd = -1;
309       
310       return -1;
311     }
312
313   if (!_dbus_set_fd_nonblocking (fd, result))
314     {
315       close (fd);
316       fd = -1;
317
318       return -1;
319     }
320
321   return fd;
322 }
323
324 /**
325  * Creates a socket and binds it to the given path,
326  * then listens on the socket. The socket is
327  * set to be nonblocking. 
328  *
329  * @param path the socket name
330  * @param result return location for errors
331  * @returns the listening file descriptor or -1 on error
332  */
333 int
334 _dbus_listen_unix_socket (const char     *path,
335                           DBusResultCode *result)
336 {
337   int listen_fd;
338   struct sockaddr_un addr;
339
340   listen_fd = socket (AF_LOCAL, SOCK_STREAM, 0);
341
342   if (listen_fd < 0)
343     {
344       dbus_set_result (result, _dbus_result_from_errno (errno));
345       _dbus_verbose ("Failed to create socket \"%s\": %s\n",
346                      path, _dbus_strerror (errno));
347       return -1;
348     }
349
350   _DBUS_ZERO (addr);
351   addr.sun_family = AF_LOCAL;
352   strncpy (addr.sun_path, path, _DBUS_MAX_SUN_PATH_LENGTH);
353   addr.sun_path[_DBUS_MAX_SUN_PATH_LENGTH] = '\0';
354   
355   if (bind (listen_fd, (struct sockaddr*) &addr, SUN_LEN (&addr)) < 0)
356     {
357       dbus_set_result (result, _dbus_result_from_errno (errno));
358       _dbus_verbose ("Failed to bind socket \"%s\": %s\n",
359                      path, _dbus_strerror (errno));
360       close (listen_fd);
361       return -1;
362     }
363
364   if (listen (listen_fd, 30 /* backlog */) < 0)
365     {
366       dbus_set_result (result, _dbus_result_from_errno (errno));      
367       _dbus_verbose ("Failed to listen on socket \"%s\": %s\n",
368                      path, _dbus_strerror (errno));
369       close (listen_fd);
370       return -1;
371     }
372
373   if (!_dbus_set_fd_nonblocking (listen_fd, result))
374     {
375       close (listen_fd);
376       return -1;
377     }
378   
379   return listen_fd;
380 }
381
382 /* try to read a single byte and return #TRUE if we read it
383  * and it's equal to nul.
384  */
385 static dbus_bool_t
386 read_credentials_byte (int             client_fd,
387                        DBusResultCode *result)
388 {
389   char buf[1];
390   int bytes_read;
391
392  again:
393   bytes_read = read (client_fd, buf, 1);
394   if (bytes_read < 0)
395     {
396       if (errno == EINTR)
397         goto again;
398       else
399         {
400           dbus_set_result (result, _dbus_result_from_errno (errno));      
401           _dbus_verbose ("Failed to read credentials byte: %s\n",
402                          _dbus_strerror (errno));
403           return FALSE;
404         }
405     }
406   else if (bytes_read == 0)
407     {
408       dbus_set_result (result, DBUS_RESULT_IO_ERROR);
409       _dbus_verbose ("EOF reading credentials byte\n");
410       return FALSE;
411     }
412   else
413     {
414       _dbus_assert (bytes_read == 1);
415
416       if (buf[0] != '\0')
417         {
418           dbus_set_result (result, DBUS_RESULT_FAILED);
419           _dbus_verbose ("Credentials byte was not nul\n");
420           return FALSE;
421         }
422
423       _dbus_verbose ("read credentials byte\n");
424       
425       return TRUE;
426     }
427 }
428
429 static dbus_bool_t
430 write_credentials_byte (int             server_fd,
431                         DBusResultCode *result)
432 {
433   int bytes_written;
434   char buf[1] = { '\0' };
435   
436  again:
437
438   bytes_written = write (server_fd, buf, 1);
439
440   if (bytes_written < 0 && errno == EINTR)
441     goto again;
442
443   if (bytes_written < 0)
444     {
445       dbus_set_result (result, _dbus_result_from_errno (errno));      
446       _dbus_verbose ("Failed to write credentials byte: %s\n",
447                      _dbus_strerror (errno));
448       return FALSE;
449     }
450   else if (bytes_written == 0)
451     {
452       dbus_set_result (result, DBUS_RESULT_IO_ERROR);
453       _dbus_verbose ("wrote zero bytes writing credentials byte\n");
454       return FALSE;
455     }
456   else
457     {
458       _dbus_assert (bytes_written == 1);
459       _dbus_verbose ("wrote credentials byte\n");
460       return TRUE;
461     }
462 }
463
464 /**
465  * Reads a single byte which must be nul (an error occurs otherwise),
466  * and reads unix credentials if available. Fills in pid/uid/gid with
467  * -1 if no credentials are available. Return value indicates whether
468  * a byte was read, not whether we got valid credentials. On some
469  * systems, such as Linux, reading/writing the byte isn't actually
470  * required, but we do it anyway just to avoid multiple codepaths.
471  * 
472  * Fails if no byte is available, so you must select() first.
473  *
474  * The point of the byte is that on some systems we have to
475  * use sendmsg()/recvmsg() to transmit credentials.
476  *
477  * @param client_fd the client file descriptor
478  * @param credentials struct to fill with credentials of client
479  * @param result location to store result code
480  * @returns #TRUE on success
481  */
482 dbus_bool_t
483 _dbus_read_credentials_unix_socket  (int              client_fd,
484                                      DBusCredentials *credentials,
485                                      DBusResultCode  *result)
486 {
487   credentials->pid = -1;
488   credentials->uid = -1;
489   credentials->gid = -1;
490   
491 #ifdef SO_PEERCRED
492   if (read_credentials_byte (client_fd, result))
493     {
494       struct ucred cr;   
495       int cr_len = sizeof (cr);
496    
497       if (getsockopt (client_fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) == 0 &&
498           cr_len == sizeof (cr))
499         {
500           credentials->pid = cr.pid;
501           credentials->uid = cr.uid;
502           credentials->gid = cr.gid;
503           _dbus_verbose ("Got credentials pid %d uid %d gid %d\n",
504                          credentials->pid,
505                          credentials->uid,
506                          credentials->gid);
507         }
508       else
509         {
510           _dbus_verbose ("Failed to getsockopt() credentials, returned len %d/%d: %s\n",
511                          cr_len, (int) sizeof (cr), _dbus_strerror (errno));
512         }
513
514       return TRUE;
515     }
516   else
517     return FALSE;
518 #else /* !SO_PEERCRED */
519   _dbus_verbose ("Socket credentials not supported on this OS\n");
520   return TRUE;
521 #endif
522 }
523
524 /**
525  * Sends a single nul byte with our UNIX credentials as ancillary
526  * data.  Returns #TRUE if the data was successfully written.  On
527  * systems that don't support sending credentials, just writes a byte,
528  * doesn't send any credentials.  On some systems, such as Linux,
529  * reading/writing the byte isn't actually required, but we do it
530  * anyway just to avoid multiple codepaths.
531  *
532  * Fails if no byte can be written, so you must select() first.
533  *
534  * The point of the byte is that on some systems we have to
535  * use sendmsg()/recvmsg() to transmit credentials.
536  *
537  * @param server_fd file descriptor for connection to server
538  * @param result return location for error code
539  * @returns #TRUE if the byte was sent
540  */
541 dbus_bool_t
542 _dbus_send_credentials_unix_socket  (int              server_fd,
543                                      DBusResultCode  *result)
544 {
545   if (write_credentials_byte (server_fd, result))
546     return TRUE;
547   else
548     return FALSE;
549 }
550
551 /**
552  * Accepts a connection on a listening socket.
553  * Handles EINTR for you.
554  *
555  * @param listen_fd the listen file descriptor
556  * @returns the connection fd of the client, or -1 on error
557  */
558 int
559 _dbus_accept  (int listen_fd)
560 {
561   int client_fd;
562   
563  retry:
564   client_fd = accept (listen_fd, NULL, NULL);
565   
566   if (client_fd < 0)
567     {
568       if (errno == EINTR)
569         goto retry;
570     }
571   
572   return client_fd;
573 }
574
575 /** @} */
576
577 /**
578  * @addtogroup DBusString
579  *
580  * @{
581  */
582 /**
583  * Appends an integer to a DBusString.
584  * 
585  * @param str the string
586  * @param value the integer value
587  * @returns #FALSE if not enough memory or other failure.
588  */
589 dbus_bool_t
590 _dbus_string_append_int (DBusString *str,
591                          long        value)
592 {
593   /* this calculation is from comp.lang.c faq */
594 #define MAX_LONG_LEN ((sizeof (long) * 8 + 2) / 3 + 1)  /* +1 for '-' */
595   int orig_len;
596   int i;
597   char *buf;
598   
599   orig_len = _dbus_string_get_length (str);
600
601   if (!_dbus_string_lengthen (str, MAX_LONG_LEN))
602     return FALSE;
603
604   _dbus_string_get_data_len (str, &buf, orig_len, MAX_LONG_LEN);
605
606   snprintf (buf, MAX_LONG_LEN, "%ld", value);
607
608   i = 0;
609   while (*buf)
610     {
611       ++buf;
612       ++i;
613     }
614   
615   _dbus_string_shorten (str, MAX_LONG_LEN - i);
616   
617   return TRUE;
618 }
619
620 /**
621  * Appends a double to a DBusString.
622  * 
623  * @param str the string
624  * @param value the floating point value
625  * @returns #FALSE if not enough memory or other failure.
626  */
627 dbus_bool_t
628 _dbus_string_append_double (DBusString *str,
629                             double      value)
630 {
631 #define MAX_DOUBLE_LEN 64 /* this is completely made up :-/ */
632   int orig_len;
633   char *buf;
634   int i;
635   
636   orig_len = _dbus_string_get_length (str);
637
638   if (!_dbus_string_lengthen (str, MAX_DOUBLE_LEN))
639     return FALSE;
640
641   _dbus_string_get_data_len (str, &buf, orig_len, MAX_DOUBLE_LEN);
642
643   snprintf (buf, MAX_LONG_LEN, "%g", value);
644
645   i = 0;
646   while (*buf)
647     {
648       ++buf;
649       ++i;
650     }
651   
652   _dbus_string_shorten (str, MAX_DOUBLE_LEN - i);
653   
654   return TRUE;
655 }
656
657 /**
658  * Parses an integer contained in a DBusString. Either return parameter
659  * may be #NULL if you aren't interested in it. The integer is parsed
660  * and stored in value_return. Return parameters are not initialized
661  * if the function returns #FALSE.
662  *
663  * @param str the string
664  * @param start the byte index of the start of the integer
665  * @param value_return return location of the integer value or #NULL
666  * @param end_return return location of the end of the integer, or #NULL
667  * @returns #TRUE on success
668  */
669 dbus_bool_t
670 _dbus_string_parse_int (const DBusString *str,
671                         int               start,
672                         long             *value_return,
673                         int              *end_return)
674 {
675   long v;
676   const char *p;
677   char *end;
678
679   _dbus_string_get_const_data_len (str, &p, start,
680                                    _dbus_string_get_length (str) - start);
681
682   end = NULL;
683   errno = 0;
684   v = strtol (p, &end, 0);
685   if (end == NULL || end == p || errno != 0)
686     return FALSE;
687
688   if (value_return)
689     *value_return = v;
690   if (end_return)
691     *end_return = (end - p);
692
693   return TRUE;
694 }
695
696 /**
697  * Parses a floating point number contained in a DBusString. Either
698  * return parameter may be #NULL if you aren't interested in it. The
699  * integer is parsed and stored in value_return. Return parameters are
700  * not initialized if the function returns #FALSE.
701  *
702  * @todo this function is currently locale-dependent. Should
703  * ask alexl to relicense g_ascii_strtod() code and put that in
704  * here instead, so it's locale-independent.
705  *
706  * @param str the string
707  * @param start the byte index of the start of the float
708  * @param value_return return location of the float value or #NULL
709  * @param end_return return location of the end of the float, or #NULL
710  * @returns #TRUE on success
711  */
712 dbus_bool_t
713 _dbus_string_parse_double (const DBusString *str,
714                            int               start,
715                            double           *value_return,
716                            int              *end_return)
717 {
718   double v;
719   const char *p;
720   char *end;
721
722   _dbus_warn ("_dbus_string_parse_double() needs to be made locale-independent\n");
723   
724   _dbus_string_get_const_data_len (str, &p, start,
725                                    _dbus_string_get_length (str) - start);
726
727   end = NULL;
728   errno = 0;
729   v = strtod (p, &end);
730   if (end == NULL || end == p || errno != 0)
731     return FALSE;
732
733   if (value_return)
734     *value_return = v;
735   if (end_return)
736     *end_return = (end - p);
737
738   return TRUE;
739 }
740
741 /**
742  * Gets the credentials corresponding to the given username.
743  *
744  * @param username the username
745  * @param credentials credentials to fill in
746  * @returns #TRUE if the username existed and we got some credentials
747  */
748 dbus_bool_t
749 _dbus_credentials_from_username (const DBusString *username,
750                                  DBusCredentials  *credentials)
751 {
752   const char *username_c_str;
753   
754   credentials->pid = -1;
755   credentials->uid = -1;
756   credentials->gid = -1;
757
758   _dbus_string_get_const_data (username, &username_c_str);
759   
760 #ifdef HAVE_GETPWNAM_R
761   {
762     struct passwd *p;
763     int result;
764     char buf[1024];
765     struct passwd p_str;
766
767     p = NULL;
768     result = getpwnam_r (username_c_str, &p_str, buf, sizeof (buf),
769                          &p);
770
771     if (result == 0 && p == &p_str)
772       {
773         credentials->uid = p->pw_uid;
774         credentials->gid = p->pw_gid;
775
776         _dbus_verbose ("Username %s has uid %d gid %d\n",
777                        username_c_str, credentials->uid, credentials->gid);
778         return TRUE;
779       }
780     else
781       {
782         _dbus_verbose ("User %s unknown\n", username_c_str);
783         return FALSE;
784       }
785   }
786 #else /* ! HAVE_GETPWNAM_R */
787   {
788     /* I guess we're screwed on thread safety here */
789     struct passwd *p;
790
791     p = getpwnam (username_c_str);
792
793     if (p != NULL)
794       {
795         credentials->uid = p->pw_uid;
796         credentials->gid = p->pw_gid;
797
798         _dbus_verbose ("Username %s has uid %d gid %d\n",
799                        username_c_str, credentials->uid, credentials->gid);
800         return TRUE;
801       }
802     else
803       {
804         _dbus_verbose ("User %s unknown\n", username_c_str);
805         return FALSE;
806       }
807   }
808 #endif  
809 }
810
811 /**
812  * Gets credentials from a UID string. (Parses a string to a UID
813  * and converts to a DBusCredentials.)
814  *
815  * @param uid_str the UID in string form
816  * @param credentials credentials to fill in
817  * @returns #TRUE if successfully filled in some credentials
818  */
819 dbus_bool_t
820 _dbus_credentials_from_uid_string (const DBusString      *uid_str,
821                                    DBusCredentials       *credentials)
822 {
823   int end;
824   long uid;
825
826   credentials->pid = -1;
827   credentials->uid = -1;
828   credentials->gid = -1;
829   
830   if (_dbus_string_get_length (uid_str) == 0)
831     {
832       _dbus_verbose ("UID string was zero length\n");
833       return FALSE;
834     }
835
836   uid = -1;
837   end = 0;
838   if (!_dbus_string_parse_int (uid_str, 0, &uid,
839                                &end))
840     {
841       _dbus_verbose ("could not parse string as a UID\n");
842       return FALSE;
843     }
844   
845   if (end != _dbus_string_get_length (uid_str))
846     {
847       _dbus_verbose ("string contained trailing stuff after UID\n");
848       return FALSE;
849     }
850
851   credentials->uid = uid;
852
853   return TRUE;
854 }
855
856 /**
857  * Gets the credentials of the current process.
858  *
859  * @param credentials credentials to fill in.
860  */
861 void
862 _dbus_credentials_from_current_process (DBusCredentials *credentials)
863 {
864   credentials->pid = getpid ();
865   credentials->uid = getuid ();
866   credentials->gid = getgid ();
867 }
868
869 /**
870  * Checks whether the provided_credentials are allowed to log in
871  * as the expected_credentials.
872  *
873  * @param expected_credentials credentials we're trying to log in as
874  * @param provided_credentials credentials we have
875  * @returns #TRUE if we can log in
876  */
877 dbus_bool_t
878 _dbus_credentials_match (const DBusCredentials *expected_credentials,
879                          const DBusCredentials *provided_credentials)
880 {
881   if (provided_credentials->uid < 0)
882     return FALSE;
883   else if (expected_credentials->uid < 0)
884     return FALSE;
885   else if (provided_credentials->uid == 0)
886     return TRUE;
887   else if (provided_credentials->uid == expected_credentials->uid)
888     return TRUE;
889   else
890     return FALSE;
891 }
892
893 /**
894  * Appends the uid of the current process to the given string.
895  *
896  * @param str the string to append to
897  * @returns #TRUE on success
898  */
899 dbus_bool_t
900 _dbus_string_append_our_uid (DBusString *str)
901 {
902   return _dbus_string_append_int (str, getuid ());
903 }
904
905
906 /**
907  * Wrapper for poll().
908  *
909  * @todo need a fallback implementation using select()
910  *
911  * @param fds the file descriptors to poll
912  * @param n_fds number of descriptors in the array
913  * @param timeout_milliseconds timeout or -1 for infinite
914  * @returns numbers of fds with revents, or <0 on error
915  */
916 int
917 _dbus_poll (DBusPollFD *fds,
918             int         n_fds,
919             int         timeout_milliseconds)
920 {
921 #ifdef HAVE_POLL
922   /* This big thing is a constant expression and should get optimized
923    * out of existence. So it's more robust than a configure check at
924    * no cost.
925    */
926   if (_DBUS_POLLIN == POLLIN &&
927       _DBUS_POLLPRI == POLLPRI &&
928       _DBUS_POLLOUT == POLLOUT &&
929       _DBUS_POLLERR == POLLERR &&
930       _DBUS_POLLHUP == POLLHUP &&
931       _DBUS_POLLNVAL == POLLNVAL &&
932       sizeof (DBusPollFD) == sizeof (struct pollfd) &&
933       _DBUS_STRUCT_OFFSET (DBusPollFD, fd) ==
934       _DBUS_STRUCT_OFFSET (struct pollfd, fd) &&
935       _DBUS_STRUCT_OFFSET (DBusPollFD, events) ==
936       _DBUS_STRUCT_OFFSET (struct pollfd, events) &&
937       _DBUS_STRUCT_OFFSET (DBusPollFD, revents) ==
938       _DBUS_STRUCT_OFFSET (struct pollfd, revents))
939     {
940       return poll ((struct pollfd*) fds,
941                    n_fds, 
942                    timeout_milliseconds);
943     }
944   else
945     {
946       /* We have to convert the DBusPollFD to an array of
947        * struct pollfd, poll, and convert back.
948        */
949       _dbus_warn ("didn't implement poll() properly for this system yet\n");
950       return -1;
951     }
952 #else /* ! HAVE_POLL */
953   _dbus_warn ("need to implement select() fallback for systems with no poll()\n");
954   return -1;
955 #endif
956 }
957
958 /** nanoseconds in a second */
959 #define NANOSECONDS_PER_SECOND       1000000000
960 /** microseconds in a second */
961 #define MICROSECONDS_PER_SECOND      1000000
962 /** milliseconds in a second */
963 #define MILLISECONDS_PER_SECOND      1000
964 /** nanoseconds in a millisecond */
965 #define NANOSECONDS_PER_MILLISECOND  1000000
966 /** microseconds in a millisecond */
967 #define MICROSECONDS_PER_MILLISECOND 1000
968
969 /**
970  * Sleeps the given number of milliseconds.
971  * @param milliseconds number of milliseconds
972  */
973 void
974 _dbus_sleep_milliseconds (int milliseconds)
975 {
976 #ifdef HAVE_NANOSLEEP
977   struct timespec req;
978   struct timespec rem;
979
980   req.tv_sec = milliseconds / MILLISECONDS_PER_SECOND;
981   req.tv_nsec = (milliseconds % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
982   rem.tv_sec = 0;
983   rem.tv_nsec = 0;
984
985   while (nanosleep (&req, &rem) < 0 && errno == EINTR)
986     req = rem;
987 #elif defined (HAVE_USLEEP)
988   usleep (milliseconds * MICROSECONDS_PER_MILLISECOND);
989 #else /* ! HAVE_USLEEP */
990   sleep (MAX (milliseconds / 1000, 1));
991 #endif
992 }
993
994 /**
995  * Get current time, as in gettimeofday().
996  *
997  * @param tv_sec return location for number of seconds
998  * @param tv_usec return location for number of microseconds (thousandths)
999  */
1000 void
1001 _dbus_get_current_time (long *tv_sec,
1002                         long *tv_usec)
1003 {
1004   struct timeval t;
1005
1006   gettimeofday (&t, NULL);
1007
1008   if (tv_sec)
1009     *tv_sec = t.tv_sec;
1010   if (tv_usec)
1011     *tv_usec = t.tv_usec;
1012 }
1013
1014 /**
1015  * Appends the contents of the given file to the string,
1016  * returning result code. At the moment, won't open a file
1017  * more than a megabyte in size.
1018  *
1019  * @param str the string to append to
1020  * @param filename filename to load
1021  * @returns result
1022  */
1023 DBusResultCode
1024 _dbus_file_get_contents (DBusString       *str,
1025                          const DBusString *filename)
1026 {
1027   int fd;
1028   struct stat sb;
1029   int orig_len;
1030   int total;
1031   const char *filename_c;
1032
1033   _dbus_string_get_const_data (filename, &filename_c);
1034   
1035   /* O_BINARY useful on Cygwin */
1036   fd = open (filename_c, O_RDONLY | O_BINARY);
1037   if (fd < 0)
1038     return _dbus_result_from_errno (errno);
1039
1040   if (fstat (fd, &sb) < 0)
1041     {
1042       DBusResultCode result;      
1043
1044       result = _dbus_result_from_errno (errno); /* prior to close() */
1045
1046       _dbus_verbose ("fstat() failed: %s",
1047                      _dbus_strerror (errno));
1048       
1049       close (fd);
1050       
1051       return result;
1052     }
1053
1054   if (sb.st_size > _DBUS_ONE_MEGABYTE)
1055     {
1056       _dbus_verbose ("File size %lu is too large.\n",
1057                      (unsigned long) sb.st_size);
1058       close (fd);
1059       return DBUS_RESULT_FAILED;
1060     }
1061   
1062   total = 0;
1063   orig_len = _dbus_string_get_length (str);
1064   if (sb.st_size > 0 && S_ISREG (sb.st_mode))
1065     {
1066       int bytes_read;
1067
1068       while (total < (int) sb.st_size)
1069         {
1070           bytes_read = _dbus_read (fd, str,
1071                                    sb.st_size - total);
1072           if (bytes_read <= 0)
1073             {
1074               DBusResultCode result;
1075               
1076               result = _dbus_result_from_errno (errno); /* prior to close() */
1077
1078               _dbus_verbose ("read() failed: %s",
1079                              _dbus_strerror (errno));
1080               
1081               close (fd);
1082               _dbus_string_set_length (str, orig_len);
1083               return result;
1084             }
1085           else
1086             total += bytes_read;
1087         }
1088
1089       close (fd);
1090       return DBUS_RESULT_SUCCESS;
1091     }
1092   else if (sb.st_size != 0)
1093     {
1094       _dbus_verbose ("Can only open regular files at the moment.\n");
1095       close (fd);
1096       return DBUS_RESULT_FAILED;
1097     }
1098   else
1099     {
1100       close (fd);
1101       return DBUS_RESULT_SUCCESS;
1102     }
1103 }
1104
1105 /**
1106  * Appends the given filename to the given directory.
1107  *
1108  * @param dir the directory name
1109  * @param next_component the filename
1110  * @returns #TRUE on success
1111  */
1112 dbus_bool_t
1113 _dbus_concat_dir_and_file (DBusString       *dir,
1114                            const DBusString *next_component)
1115 {
1116   dbus_bool_t dir_ends_in_slash;
1117   dbus_bool_t file_starts_with_slash;
1118
1119   if (_dbus_string_get_length (dir) == 0 ||
1120       _dbus_string_get_length (next_component) == 0)
1121     return TRUE;
1122   
1123   dir_ends_in_slash = '/' == _dbus_string_get_byte (dir,
1124                                                     _dbus_string_get_length (dir) - 1);
1125
1126   file_starts_with_slash = '/' == _dbus_string_get_byte (next_component, 0);
1127
1128   if (dir_ends_in_slash && file_starts_with_slash)
1129     {
1130       _dbus_string_shorten (dir, 1);
1131     }
1132   else if (!(dir_ends_in_slash || file_starts_with_slash))
1133     {
1134       if (!_dbus_string_append_byte (dir, '/'))
1135         return FALSE;
1136     }
1137
1138   return _dbus_string_copy (next_component, 0, dir,
1139                             _dbus_string_get_length (dir));
1140 }
1141
1142 struct DBusDirIter
1143 {
1144   DIR *d;
1145   
1146 };
1147
1148 /**
1149  * Open a directory to iterate over.
1150  *
1151  * @param filename the directory name
1152  * @param result return location for error code if #NULL returned
1153  * @returns new iterator, or #NULL on error
1154  */
1155 DBusDirIter*
1156 _dbus_directory_open (const DBusString *filename,
1157                       DBusResultCode   *result)
1158 {
1159   DIR *d;
1160   DBusDirIter *iter;
1161   const char *filename_c;
1162
1163   _dbus_string_get_const_data (filename, &filename_c);
1164
1165   d = opendir (filename_c);
1166   if (d == NULL)
1167     {
1168       dbus_set_result (result, _dbus_result_from_errno (errno));
1169       return NULL;
1170     }
1171   
1172   iter = dbus_new0 (DBusDirIter, 1);
1173   if (iter == NULL)
1174     {
1175       closedir (d);
1176       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1177       return NULL;
1178     }
1179
1180   iter->d = d;
1181
1182   return iter;
1183 }
1184
1185 /**
1186  * Get next file in the directory. Will not return "." or ".."
1187  * on UNIX. If an error occurs, the contents of "filename"
1188  * are undefined. #DBUS_RESULT_SUCCESS is always returned
1189  * in result if no error occurs.
1190  *
1191  * @todo for thread safety, I think we have to use
1192  * readdir_r(). (GLib has the same issue, should file a bug.)
1193  *
1194  * @param iter the iterator
1195  * @param filename string to be set to the next file in the dir
1196  * @param result return location for error, or #DBUS_RESULT_SUCCESS
1197  * @returns #TRUE if filename was filled in with a new filename
1198  */
1199 dbus_bool_t
1200 _dbus_directory_get_next_file (DBusDirIter      *iter,
1201                                DBusString       *filename,
1202                                DBusResultCode   *result)
1203 {
1204   /* we always have to put something in result, since return
1205    * value means whether there's a filename and doesn't
1206    * reliably indicate whether an error was set.
1207    */
1208   struct dirent *ent;
1209   
1210   dbus_set_result (result, DBUS_RESULT_SUCCESS);
1211
1212  again:
1213   errno = 0;
1214   ent = readdir (iter->d);
1215   if (ent == NULL)
1216     {
1217       dbus_set_result (result,
1218                        _dbus_result_from_errno (errno));
1219       return FALSE;
1220     }
1221   else if (ent->d_name[0] == '.' &&
1222            (ent->d_name[1] == '\0' ||
1223             (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
1224     goto again;
1225   else
1226     {
1227       _dbus_string_set_length (filename, 0);
1228       if (!_dbus_string_append (filename, ent->d_name))
1229         {
1230           dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1231           return FALSE;
1232         }
1233       else
1234         return TRUE;
1235     }
1236 }
1237
1238 /**
1239  * Closes a directory iteration.
1240  */
1241 void
1242 _dbus_directory_close (DBusDirIter *iter)
1243 {
1244   closedir (iter->d);
1245   dbus_free (iter);
1246 }
1247
1248
1249 /** @} end of sysdeps */