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