1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
6 * Copyright (C) 2005 Novell, Inc.
7 * Copyright (C) 2006 Ralf Habacker <ralf.habacker@freenet.de>
8 * Copyright (C) 2006 Peter Kümmel <syntheticpp@gmx.net>
9 * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
11 * Licensed under the Academic Free License version 2.1
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 /* #define ENABLE_DBUSUSERINFO */
33 #define STRSAFE_NO_DEPRECATE
36 #define _WIN32_WINNT 0x0500
39 #include "dbus-internals.h"
40 #include "dbus-sysdeps.h"
41 #include "dbus-threads.h"
42 #include "dbus-protocol.h"
43 #include "dbus-string.h"
44 #include "dbus-sysdeps-win.h"
45 #include "dbus-protocol.h"
46 #include "dbus-hash.h"
47 #include "dbus-sockets-win.h"
48 #include "dbus-list.h"
49 #include "dbus-credentials.h"
56 #include <sys/types.h>
62 #ifndef HAVE_SOCKLEN_T
66 #ifdef ENABLE_DBUSSOCKET
67 _DBUS_DEFINE_GLOBAL_LOCK (win_fds);
70 #ifdef ENABLE_UID_TO_SID
71 _DBUS_DEFINE_GLOBAL_LOCK (sid_atom_cache);
74 #ifdef ENABLE_DBUSUSERINFO
79 dbus_gid_t *group_ids;
85 #ifdef ENABLE_DBUSSOCKET
90 _dbus_assert (win_fds!=0);
96 _dbus_unlock_sockets()
98 _dbus_assert (win_fds!=0);
99 _DBUS_UNLOCK (win_fds);
103 #ifdef _DBUS_WIN_USE_RANDOMIZER
104 static int win_encap_randomizer;
107 #ifdef ENABLE_UID_TO_SID
108 static DBusHashTable *sid_atom_cache = NULL;
111 static DBusString dbusdir;
112 static int working_dir_init = 0;
114 int _dbus_init_working_dir(char *s)
116 /* change working directory to one level above
117 of dbus-daemon executable path.
118 This allows the usage of relative path in
119 config files or command line parameters */
120 DBusString daemon_path,bin_path;
122 if (!_dbus_string_init (&daemon_path))
125 if (!_dbus_string_init (&bin_path))
128 if (!_dbus_string_init (&dbusdir))
131 _dbus_string_append(&daemon_path,s);
132 _dbus_string_get_dirname(&daemon_path,&bin_path);
133 _dbus_string_get_dirname(&bin_path,&dbusdir);
134 chdir(_dbus_string_get_const_data(&dbusdir));
135 _dbus_verbose ("Change working path to %s\n",_dbus_string_get_const_data (&dbusdir));
136 working_dir_init = 1;
140 DBusString *_dbus_get_working_dir(void)
142 if (!working_dir_init)
145 _dbus_verbose ("retrieving working path %s\n",_dbus_string_get_const_data (&dbusdir));
154 _dbus_file_open (DBusFile *file,
155 const char *filename,
160 file->FDATA = _open (filename, oflag, pmode);
162 file->FDATA = _open (filename, oflag);
163 if (file->FDATA >= 0)
173 _dbus_file_close (DBusFile *file,
176 const int fd = file->FDATA;
178 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
180 _dbus_assert (fd >= 0);
182 if (_close (fd) == -1)
184 dbus_set_error (error, _dbus_error_from_errno (errno),
185 "Could not close fd %d: %s", fd,
186 _dbus_strerror (errno));
191 _dbus_verbose ("closed C file descriptor %d:\n",fd);
197 _dbus_file_read(DBusFile *file,
201 const int fd = file->FDATA;
205 _dbus_assert (count >= 0);
207 start = _dbus_string_get_length (buffer);
209 if (!_dbus_string_lengthen (buffer, count))
215 data = _dbus_string_get_data_len (buffer, start, count);
217 _dbus_assert (fd >= 0);
219 _dbus_verbose ("read: count=%d fd=%d\n", count, fd);
220 bytes_read = read (fd, data, count);
222 if (bytes_read == -1)
223 _dbus_verbose ("read: failed: %s\n", _dbus_strerror (errno));
225 _dbus_verbose ("read: = %d\n", bytes_read);
229 /* put length back (note that this doesn't actually realloc anything) */
230 _dbus_string_set_length (buffer, start);
235 /* put length back (doesn't actually realloc) */
236 _dbus_string_set_length (buffer, start + bytes_read);
241 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
249 _dbus_file_write (DBusFile *file,
250 const DBusString *buffer,
254 const int fd = file->FDATA;
258 data = _dbus_string_get_const_data_len (buffer, start, len);
260 _dbus_assert (fd >= 0);
262 _dbus_verbose ("write: len=%d fd=%d\n", len, fd);
263 bytes_written = write (fd, data, len);
265 if (bytes_written == -1)
266 _dbus_verbose ("write: failed: %s\n", _dbus_strerror (errno));
268 _dbus_verbose ("write: = %d\n", bytes_written);
272 if (bytes_written > 0)
273 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
276 return bytes_written;
280 _dbus_is_valid_file (DBusFile* file)
282 return file->FDATA >= 0;
285 dbus_bool_t _dbus_fstat (DBusFile *file,
288 return fstat(file->FDATA, sb) >= 0;
292 * write data to a pipe.
294 * @param pipe the pipe instance
295 * @param buffer the buffer to write data from
296 * @param start the first byte in the buffer to write
297 * @param len the number of bytes to try to write
298 * @param error error return
299 * @returns the number of bytes written or -1 on error
302 _dbus_pipe_write (DBusPipe *pipe,
303 const DBusString *buffer,
310 file.FDATA = pipe->fd_or_handle;
311 written = _dbus_file_write (&file, buffer, start, len);
314 dbus_set_error (error, DBUS_ERROR_FAILED,
315 "Writing to pipe: %s\n",
316 _dbus_strerror (errno));
324 * @param pipe the pipe instance
325 * @param error return location for an error
326 * @returns #FALSE if error is set
329 _dbus_pipe_close (DBusPipe *pipe,
333 file.FDATA = pipe->fd_or_handle;
334 if (_dbus_file_close (&file, error) < 0)
340 _dbus_pipe_invalidate (pipe);
352 #ifdef ENABLE_DBUSSOCKET
353 static DBusSocket *win_fds = NULL;
354 static int win_n_fds = 0; // is this the size? rename to win_fds_size? #
358 #define TO_HANDLE(n) ((n)^win32_encap_randomizer)
359 #define FROM_HANDLE(n) ((n)^win32_encap_randomizer)
361 #define TO_HANDLE(n) ((n)+0x10000000)
362 #define FROM_HANDLE(n) ((n)-0x10000000)
363 #define IS_HANDLE(n) ((n)&0x10000000)
369 _dbus_win_deallocate_fd (int fd)
371 _DBUS_LOCK (win_fds);
372 win_fds[FROM_HANDLE (fd)].is_used = 0;
373 _DBUS_UNLOCK (win_fds);
378 _dbus_win_allocate_fd (void)
382 _DBUS_LOCK (win_fds);
386 #ifdef _DBUS_WIN_USE_RANDOMIZER
391 /* Use malloc to avoid memory leak failure in dbus-test */
392 win_fds = malloc (win_n_fds * sizeof (*win_fds));
394 _dbus_assert (win_fds != NULL);
396 for (i = 0; i < win_n_fds; i++)
397 win_fds[i].is_used = 0;
399 #ifdef _DBUS_WIN_USE_RANDOMIZER
401 _dbus_string_init (&random);
402 _dbus_generate_random_bytes (&random, sizeof (int));
403 memmove (&win_encap_randomizer, _dbus_string_get_const_data (&random), sizeof (int));
404 win_encap_randomizer &= 0xFF;
405 _dbus_string_free (&random);
410 for (i = 0; i < win_n_fds && win_fds[i].is_used != 0; i++)
415 int oldn = win_n_fds;
419 win_fds = realloc (win_fds, win_n_fds * sizeof (*win_fds));
421 _dbus_assert (win_fds != NULL);
423 for (j = oldn; j < win_n_fds; j++)
424 win_fds[i].is_used = 0;
427 memset(&win_fds[i], 0, sizeof(win_fds[i]));
429 win_fds[i].is_used = 1;
431 win_fds[i].port_file_fd = -1;
432 win_fds[i].close_on_exec = FALSE;
433 win_fds[i].non_blocking = FALSE;
435 _DBUS_UNLOCK (win_fds);
442 _dbus_create_handle_from_socket (int s)
447 // check: parameter must be a valid value
448 _dbus_assert(s != -1);
449 _dbus_assert(!IS_HANDLE(s));
451 // get index of a new position in the map
452 i = _dbus_win_allocate_fd ();
454 // fill new posiiton in the map: value->index
456 win_fds[i].is_used = 1;
458 // create handle from the index: index->handle
459 handle = TO_HANDLE (i);
461 _dbus_verbose ("_dbus_create_handle_from_value, value: %d, handle: %d\n", s, handle);
467 _dbus_socket_to_handle (DBusSocket *s)
472 // check: parameter must be a valid socket
473 _dbus_assert(s != NULL);
474 _dbus_assert(s->fd != -1);
475 _dbus_assert(!IS_HANDLE(s->fd));
477 _DBUS_LOCK (win_fds);
479 // at the first call there is no win_fds
480 // will be constructed _dbus_create_handle_from_socket
481 // because handle = -1
484 // search for the value in the map
485 // find the index of the value: value->index
486 for (i = 0; i < win_n_fds; i++)
487 if (win_fds[i].is_used == 1 && win_fds[i].fd == s->fd)
489 // create handle from the index: index->handle
490 handle = TO_HANDLE (i);
494 _DBUS_UNLOCK (win_fds);
499 handle = _dbus_create_handle_from_socket(s->fd);
502 _dbus_assert(handle != -1);
509 _dbus_handle_to_socket_unlocked (int handle,
514 // check: parameter must be a valid handle
515 _dbus_assert(handle != -1);
516 _dbus_assert(IS_HANDLE(handle));
517 _dbus_assert(ptr != NULL);
519 // map from handle to index: handle->index
520 i = FROM_HANDLE (handle);
522 _dbus_assert (win_fds != NULL);
523 _dbus_assert (i >= 0 && i < win_n_fds);
525 // check for if fd is valid
526 _dbus_assert (win_fds[i].is_used == 1);
528 // get socket from index: index->socket
531 _dbus_verbose ("_dbus_socket_to_handle_unlocked: socket=%d, handle=%d, index=%d\n", (*ptr)->fd, handle, i);
535 _dbus_handle_to_socket (int handle,
538 _dbus_lock_sockets();
539 _dbus_handle_to_socket_unlocked (handle, ptr);
540 _dbus_unlock_sockets();
547 #define FROM_HANDLE(n) 1==DBUS_WIN_DONT_USE__FROM_HANDLE__DIRECTLY
548 #define win_fds 1==DBUS_WIN_DONT_USE_win_fds_DIRECTLY
554 * Thin wrapper around the read() system call that appends
555 * the data it reads to the DBusString buffer. It appends
556 * up to the given count, and returns the same value
557 * and same errno as read(). The only exception is that
558 * _dbus_read() handles EINTR for you. _dbus_read() can
559 * return ENOMEM, even though regular UNIX read doesn't.
561 * @param fd the file descriptor to read from
562 * @param buffer the buffer to append data to
563 * @param count the amount of data to read
564 * @returns the number of bytes read or -1
567 _dbus_read_socket (int handle,
571 #ifdef ENABLE_DBUSSOCKET
578 _dbus_assert (count >= 0);
580 start = _dbus_string_get_length (buffer);
582 if (!_dbus_string_lengthen (buffer, count))
588 data = _dbus_string_get_data_len (buffer, start, count);
590 #ifdef ENABLE_DBUSSOCKET
591 _dbus_handle_to_socket(handle, &s);
595 _dbus_verbose ("recv: count=%d socket=%d\n", count, s->fd);
596 bytes_read = recv (s->fd, data, count, 0);
600 _dbus_verbose ("recv: count=%d socket=%d\n", count, handle);
601 bytes_read = recv (handle, data, count, 0);
603 if (bytes_read == SOCKET_ERROR)
605 DBUS_SOCKET_SET_ERRNO();
606 _dbus_verbose ("recv: failed: %s\n", _dbus_strerror (errno));
610 _dbus_verbose ("recv: = %d\n", bytes_read);
614 _dbus_assert_not_reached ("no valid socket");
619 /* put length back (note that this doesn't actually realloc anything) */
620 _dbus_string_set_length (buffer, start);
625 /* put length back (doesn't actually realloc) */
626 _dbus_string_set_length (buffer, start + bytes_read);
631 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
639 * Thin wrapper around the write() system call that writes a part of a
640 * DBusString and handles EINTR for you.
642 * @param fd the file descriptor to write
643 * @param buffer the buffer to write data from
644 * @param start the first byte in the buffer to write
645 * @param len the number of bytes to try to write
646 * @returns the number of bytes written or -1 on error
649 _dbus_write_socket (int handle,
650 const DBusString *buffer,
654 #ifdef ENABLE_DBUSSOCKET
661 data = _dbus_string_get_const_data_len (buffer, start, len);
663 #ifdef ENABLE_DBUSSOCKET
664 _dbus_handle_to_socket(handle, &s);
668 _dbus_verbose ("send: len=%d socket=%d\n", len, s->fd);
669 bytes_written = send (s->fd, data, len, 0);
673 _dbus_verbose ("send: len=%d socket=%d\n", len, handle);
674 bytes_written = send (handle, data, len, 0);
676 if (bytes_written == SOCKET_ERROR)
678 DBUS_SOCKET_SET_ERRNO();
679 _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
683 _dbus_verbose ("send: = %d\n", bytes_written);
687 _dbus_assert_not_reached ("unhandled fd type");
691 if (bytes_written > 0)
692 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
695 return bytes_written;
700 * Closes a file descriptor.
702 * @param fd the file descriptor
703 * @param error error object
704 * @returns #FALSE if error set
707 _dbus_close_socket (int handle,
710 #ifdef ENABLE_DBUSSOCKET
713 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
715 _dbus_lock_sockets();
717 _dbus_handle_to_socket_unlocked (handle, &s);
722 if (s->port_file_fd >= 0)
724 _chsize (s->port_file_fd, 0);
725 close (s->port_file_fd);
726 s->port_file_fd = -1;
727 unlink (_dbus_string_get_const_data (&s->port_file));
728 free ((char *) _dbus_string_get_const_data (&s->port_file));
731 if (closesocket (s->fd) == SOCKET_ERROR)
733 DBUS_SOCKET_SET_ERRNO ();
734 dbus_set_error (error, _dbus_error_from_errno (errno),
735 "Could not close socket: socket=%d, handle=%d, %s",
736 s->fd, handle, _dbus_strerror (errno));
737 _dbus_unlock_sockets();
740 _dbus_verbose ("_dbus_close_socket: socket=%d, handle=%d\n",
745 _dbus_assert_not_reached ("unhandled fd type");
748 _dbus_unlock_sockets();
750 _dbus_win_deallocate_fd (handle);
756 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
761 if (closesocket (handle) == SOCKET_ERROR)
763 DBUS_SOCKET_SET_ERRNO ();
764 dbus_set_error (error, _dbus_error_from_errno (errno),
765 "Could not close socket: socket=%d, , %s",
766 handle, _dbus_strerror (errno));
769 _dbus_verbose ("_dbus_close_socket: socket=%d, \n",
774 _dbus_assert_not_reached ("unhandled fd type");
783 * Sets the file descriptor to be close
784 * on exec. Should be called for all file
785 * descriptors in D-Bus code.
787 * @param fd the file descriptor
790 _dbus_fd_set_close_on_exec (int handle)
792 #ifdef ENABLE_DBUSSOCKET
797 _dbus_lock_sockets();
799 _dbus_handle_to_socket_unlocked (handle, &s);
800 s->close_on_exec = TRUE;
802 _dbus_unlock_sockets();
807 val = fcntl (fd, F_GETFD, 0);
814 fcntl (fd, F_SETFD, val);
820 * Sets a file descriptor to be nonblocking.
822 * @param fd the file descriptor.
823 * @param error address of error location.
824 * @returns #TRUE on success.
827 _dbus_set_fd_nonblocking (int handle,
830 #ifdef ENABLE_DBUSSOCKET
834 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
836 _dbus_lock_sockets();
838 _dbus_handle_to_socket_unlocked(handle, &s);
842 if (ioctlsocket (s->fd, FIONBIO, &one) == SOCKET_ERROR)
844 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
845 "Failed to set socket %d:%d to nonblocking: %s", s->fd,
846 _dbus_strerror (WSAGetLastError ()));
847 _dbus_unlock_sockets();
853 _dbus_assert_not_reached ("unhandled fd type");
856 _dbus_unlock_sockets();
862 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
866 if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
868 dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
869 "Failed to set socket %d:%d to nonblocking: %s", handle,
870 _dbus_strerror (WSAGetLastError ()));
876 _dbus_assert_not_reached ("unhandled fd type");
884 * Like _dbus_write() but will use writev() if possible
885 * to write both buffers in sequence. The return value
886 * is the number of bytes written in the first buffer,
887 * plus the number written in the second. If the first
888 * buffer is written successfully and an error occurs
889 * writing the second, the number of bytes in the first
890 * is returned (i.e. the error is ignored), on systems that
891 * don't have writev. Handles EINTR for you.
892 * The second buffer may be #NULL.
894 * @param fd the file descriptor
895 * @param buffer1 first buffer
896 * @param start1 first byte to write in first buffer
897 * @param len1 number of bytes to write from first buffer
898 * @param buffer2 second buffer, or #NULL
899 * @param start2 first byte to write in second buffer
900 * @param len2 number of bytes to write in second buffer
901 * @returns total bytes written from both buffers, or -1 on error
904 _dbus_write_socket_two (int handle,
905 const DBusString *buffer1,
908 const DBusString *buffer2,
912 #ifdef ENABLE_DBUSSOCKET
921 _dbus_assert (buffer1 != NULL);
922 _dbus_assert (start1 >= 0);
923 _dbus_assert (start2 >= 0);
924 _dbus_assert (len1 >= 0);
925 _dbus_assert (len2 >= 0);
927 _dbus_handle_to_socket(handle, &s);
929 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
932 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
942 vectors[0].buf = (char*) data1;
943 vectors[0].len = len1;
944 vectors[1].buf = (char*) data2;
945 vectors[1].len = len2;
947 _dbus_verbose ("WSASend: len1+2=%d+%d socket=%d\n", len1, len2, s->fd);
948 rc = WSASend (s->fd, vectors, data2 ? 2 : 1, &bytes_written,
952 DBUS_SOCKET_SET_ERRNO ();
953 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
957 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
958 return bytes_written;
962 _dbus_assert_not_reached ("unhandled fd type");
973 _dbus_assert (buffer1 != NULL);
974 _dbus_assert (start1 >= 0);
975 _dbus_assert (start2 >= 0);
976 _dbus_assert (len1 >= 0);
977 _dbus_assert (len2 >= 0);
980 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
983 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
993 vectors[0].buf = (char*) data1;
994 vectors[0].len = len1;
995 vectors[1].buf = (char*) data2;
996 vectors[1].len = len2;
998 _dbus_verbose ("WSASend: len1+2=%d+%d socket=%d\n", len1, len2, handle);
999 rc = WSASend (handle, vectors, data2 ? 2 : 1, &bytes_written,
1003 DBUS_SOCKET_SET_ERRNO ();
1004 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
1008 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
1009 return bytes_written;
1013 _dbus_assert_not_reached ("unhandled fd type");
1022 * Opens the client side of a Windows named pipe. The connection D-BUS
1023 * file descriptor index is returned. It is set up as nonblocking.
1025 * @param path the path to named pipe socket
1026 * @param error return location for error code
1027 * @returns connection D-BUS file descriptor or -1 on error
1030 _dbus_connect_named_pipe (const char *path,
1033 _dbus_assert_not_reached ("not implemented");
1039 #ifdef ENABLE_DBUSUSERINFO
1041 _dbus_account_to_win_sid (const wchar_t *waccount,
1045 dbus_bool_t retval = FALSE;
1046 DWORD sid_length, wdomain_length;
1054 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
1055 NULL, &wdomain_length, &use)
1056 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1058 _dbus_win_set_error_from_win_error (error, GetLastError ());
1062 *ppsid = dbus_malloc (sid_length);
1065 _DBUS_SET_OOM (error);
1069 wdomain = dbus_new (wchar_t, wdomain_length);
1072 _DBUS_SET_OOM (error);
1076 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
1077 wdomain, &wdomain_length, &use))
1079 _dbus_win_set_error_from_win_error (error, GetLastError ());
1083 if (!IsValidSid ((PSID) *ppsid))
1085 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
1092 dbus_free (wdomain);
1104 fill_win_user_info_name_and_groups (wchar_t *wname,
1112 dbus_bool_t retval = FALSE;
1113 char *name, *domain;
1114 LPLOCALGROUP_USERS_INFO_0 local_groups = NULL;
1115 LPGROUP_USERS_INFO_0 global_groups = NULL;
1116 DWORD nread, ntotal;
1118 name = _dbus_win_utf16_to_utf8 (wname, error);
1122 domain = _dbus_win_utf16_to_utf8 (wdomain, error);
1126 info->username = dbus_malloc (strlen (domain) + 1 + strlen (name) + 1);
1127 if (!info->username)
1129 _DBUS_SET_OOM (error);
1133 strcpy (info->username, domain);
1134 strcat (info->username, "\\");
1135 strcat (info->username, name);
1137 info->n_group_ids = 0;
1138 if (NetUserGetLocalGroups (NULL, wname, 0, LG_INCLUDE_INDIRECT,
1139 (LPBYTE *) &local_groups, MAX_PREFERRED_LENGTH,
1140 &nread, &ntotal) == NERR_Success)
1145 info->group_ids = dbus_new (dbus_gid_t, nread);
1146 if (!info->group_ids)
1148 _DBUS_SET_OOM (error);
1152 for (i = n = 0; i < nread; i++)
1155 if (_dbus_account_to_win_sid (local_groups[i].lgrui0_name,
1158 info->group_ids[n++] = _dbus_win_sid_to_uid_t (group_sid);
1159 dbus_free (group_sid);
1162 info->n_group_ids = n;
1165 if (NetUserGetGroups (NULL, wname, 0,
1166 (LPBYTE *) &global_groups, MAX_PREFERRED_LENGTH,
1167 &nread, &ntotal) == NERR_Success)
1170 int n = info->n_group_ids;
1172 info->group_ids = dbus_realloc (info->group_ids, (n + nread) * sizeof (dbus_gid_t));
1173 if (!info->group_ids)
1175 _DBUS_SET_OOM (error);
1179 for (i = 0; i < nread; i++)
1182 if (_dbus_account_to_win_sid (global_groups[i].grui0_name,
1185 info->group_ids[n++] = _dbus_win_sid_to_uid_t (group_sid);
1186 dbus_free (group_sid);
1189 info->n_group_ids = n;
1192 if (info->n_group_ids > 0)
1194 /* FIXME: find out actual primary group */
1195 info->primary_gid = info->group_ids[0];
1199 info->group_ids = dbus_new (dbus_gid_t, 1);
1200 info->n_group_ids = 1;
1201 info->group_ids[0] = DBUS_GID_UNSET;
1202 info->primary_gid = DBUS_GID_UNSET;
1208 if (global_groups != NULL)
1209 NetApiBufferFree (global_groups);
1211 if (local_groups != NULL)
1212 NetApiBufferFree (local_groups);
1223 fill_win_user_info_homedir (wchar_t *wname,
1232 dbus_bool_t retval = FALSE;
1233 USER_INFO_1 *user_info = NULL;
1234 wchar_t wcomputername[MAX_COMPUTERNAME_LENGTH + 1];
1235 DWORD wcomputername_length = MAX_COMPUTERNAME_LENGTH + 1;
1236 dbus_bool_t local_computer;
1238 NET_API_STATUS ret = 0;
1240 /* If the domain is this computer's name, assume it's a local user.
1241 * Otherwise look up a DC for the domain, and ask it.
1244 GetComputerNameW (wcomputername, &wcomputername_length);
1245 local_computer = (wcsicmp (wcomputername, wdomain) == 0);
1247 if (!local_computer)
1249 ret = NetGetAnyDCName (NULL, wdomain, (LPBYTE *) &dc);
1250 if (ret != NERR_Success)
1252 info->homedir = _dbus_strdup ("\\");
1253 _dbus_verbose("NetGetAnyDCName() failed with errorcode %d '%s'\n",ret,_dbus_lm_strerror(ret));
1258 /* No way to find out the profile of another user, let's try the
1259 * "home directory" from NetUserGetInfo's USER_INFO_1.
1261 ret = NetUserGetInfo (dc, wname, 1, (LPBYTE *) &user_info);
1262 if (ret == NERR_Success )
1263 if(user_info->usri1_home_dir != NULL &&
1264 user_info->usri1_home_dir != (LPWSTR)0xfeeefeee && /* freed memory http://www.gamedev.net/community/forums/topic.asp?topic_id=158402 */
1265 user_info->usri1_home_dir[0] != '\0')
1267 info->homedir = _dbus_win_utf16_to_utf8 (user_info->usri1_home_dir, error);
1273 _dbus_verbose("NetUserGetInfo() returned no home dir entry\n");
1274 /* Not set, so use something random. */
1275 info->homedir = _dbus_strdup ("\\");
1279 char *dc_string = _dbus_win_utf16_to_utf8(dc,error);
1280 char *user_name = _dbus_win_utf16_to_utf8(wname,error);
1281 _dbus_verbose("NetUserGetInfo() for user '%s' failed with errorcode %d '%s', %s\n",user_name, ret,_dbus_lm_strerror(ret),dc_string);
1282 dbus_free(user_name);
1283 dbus_free(dc_string);
1284 /* Not set, so use something random. */
1285 info->homedir = _dbus_strdup ("\\");
1292 NetApiBufferFree (dc);
1293 if (user_info != NULL)
1294 NetApiBufferFree (user_info);
1301 fill_win_user_info_from_name (wchar_t *wname,
1309 dbus_bool_t retval = FALSE;
1312 DWORD sid_length, wdomain_length;
1317 if (!LookupAccountNameW (NULL, wname, NULL, &sid_length,
1318 NULL, &wdomain_length, &use) &&
1319 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1321 _dbus_win_set_error_from_win_error (error, GetLastError ());
1325 sid = dbus_malloc (sid_length);
1328 _DBUS_SET_OOM (error);
1332 wdomain = dbus_new (wchar_t, wdomain_length);
1335 _DBUS_SET_OOM (error);
1339 if (!LookupAccountNameW (NULL, wname, sid, &sid_length,
1340 wdomain, &wdomain_length, &use))
1342 _dbus_win_set_error_from_win_error (error, GetLastError ());
1346 if (!IsValidSid (sid))
1348 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
1352 info->uid = _dbus_win_sid_to_uid_t (sid);
1354 if (!fill_win_user_info_name_and_groups (wname, wdomain, info, error))
1357 if (!fill_win_user_info_homedir (wname, wdomain, info, error))
1363 dbus_free (wdomain);
1372 _dbus_win_sid_to_name_and_domain (dbus_uid_t uid,
1382 DWORD wname_length, wdomain_length;
1385 if (!_dbus_uid_t_to_win_sid (uid, &sid))
1387 _dbus_win_set_error_from_win_error (error, GetLastError ());
1393 if (!LookupAccountSidW (NULL, sid, NULL, &wname_length,
1394 NULL, &wdomain_length, &use) &&
1395 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1397 _dbus_win_set_error_from_win_error (error, GetLastError ());
1401 *wname = dbus_new (wchar_t, wname_length);
1404 _DBUS_SET_OOM (error);
1408 *wdomain = dbus_new (wchar_t, wdomain_length);
1411 _DBUS_SET_OOM (error);
1415 if (!LookupAccountSidW (NULL, sid, *wname, &wname_length,
1416 *wdomain, &wdomain_length, &use))
1418 _dbus_win_set_error_from_win_error (error, GetLastError ());
1425 dbus_free (*wdomain);
1438 fill_win_user_info_from_uid (dbus_uid_t uid,
1447 dbus_bool_t retval = FALSE;
1448 wchar_t *wname, *wdomain;
1452 if (!_dbus_win_sid_to_name_and_domain (uid, &wname, &wdomain, error))
1454 _dbus_verbose("%s after _dbus_win_sid_to_name_and_domain\n",__FUNCTION__);
1458 if (!fill_win_user_info_name_and_groups (wname, wdomain, info, error))
1460 _dbus_verbose("%s after fill_win_user_info_name_and_groups\n",__FUNCTION__);
1465 if (!fill_win_user_info_homedir (wname, wdomain, info, error))
1467 _dbus_verbose("%s after fill_win_user_info_homedir\n",__FUNCTION__);
1474 dbus_free (wdomain);
1485 _dbus_win_startup_winsock (void)
1487 /* Straight from MSDN, deuglified */
1489 static dbus_bool_t beenhere = FALSE;
1491 WORD wVersionRequested;
1498 wVersionRequested = MAKEWORD (2, 0);
1500 err = WSAStartup (wVersionRequested, &wsaData);
1503 _dbus_assert_not_reached ("Could not initialize WinSock");
1507 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
1508 * supports versions greater than 2.0 in addition to 2.0, it will
1509 * still return 2.0 in wVersion since that is the version we
1512 if (LOBYTE (wsaData.wVersion) != 2 ||
1513 HIBYTE (wsaData.wVersion) != 0)
1515 _dbus_assert_not_reached ("No usable WinSock found");
1530 /************************************************************************
1534 ************************************************************************/
1537 * Measure the message length without terminating nul
1539 int _dbus_printf_string_upper_bound (const char *format,
1542 /* MSVCRT's vsnprintf semantics are a bit different */
1543 /* The C library source in the Platform SDK indicates that this
1544 * would work, but alas, it doesn't. At least not on Windows
1545 * 2000. Presumably those sources correspond to the C library on
1546 * some newer or even future Windows version.
1548 len = _vsnprintf (NULL, _DBUS_INT_MAX, format, args);
1552 len = _vsnprintf (p, sizeof(p)-1, format, args);
1553 if (len == -1) // try again
1556 p = malloc (strlen(format)*3);
1557 len = _vsnprintf (p, sizeof(p)-1, format, args);
1565 * Returns the UTF-16 form of a UTF-8 string. The result should be
1566 * freed with dbus_free() when no longer needed.
1568 * @param str the UTF-8 string
1569 * @param error return location for error code
1572 _dbus_win_utf8_to_utf16 (const char *str,
1579 _dbus_string_init_const (&s, str);
1581 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
1583 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
1587 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
1591 _dbus_win_set_error_from_win_error (error, GetLastError ());
1595 retval = dbus_new (wchar_t, n);
1599 _DBUS_SET_OOM (error);
1603 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
1606 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
1614 * Returns the UTF-8 form of a UTF-16 string. The result should be
1615 * freed with dbus_free() when no longer needed.
1617 * @param str the UTF-16 string
1618 * @param error return location for error code
1621 _dbus_win_utf16_to_utf8 (const wchar_t *str,
1627 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
1631 _dbus_win_set_error_from_win_error (error, GetLastError ());
1635 retval = dbus_malloc (n);
1639 _DBUS_SET_OOM (error);
1643 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
1646 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
1658 /************************************************************************
1660 uid ... <-> win sid functions
1662 ************************************************************************/
1665 _dbus_win_account_to_sid (const wchar_t *waccount,
1669 dbus_bool_t retval = FALSE;
1670 DWORD sid_length, wdomain_length;
1678 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
1679 NULL, &wdomain_length, &use) &&
1680 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1682 _dbus_win_set_error_from_win_error (error, GetLastError ());
1686 *ppsid = dbus_malloc (sid_length);
1689 _DBUS_SET_OOM (error);
1693 wdomain = dbus_new (wchar_t, wdomain_length);
1696 _DBUS_SET_OOM (error);
1700 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
1701 wdomain, &wdomain_length, &use))
1703 _dbus_win_set_error_from_win_error (error, GetLastError ());
1707 if (!IsValidSid ((PSID) *ppsid))
1709 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
1716 dbus_free (wdomain);
1727 #ifdef ENABLE_UID_TO_SID
1729 _sid_atom_cache_shutdown (void *unused)
1732 _DBUS_LOCK (sid_atom_cache);
1733 _dbus_hash_iter_init (sid_atom_cache, &iter);
1734 while (_dbus_hash_iter_next (&iter))
1737 atom = (ATOM) _dbus_hash_iter_get_value (&iter);
1738 GlobalDeleteAtom(atom);
1739 _dbus_hash_iter_remove_entry(&iter);
1741 _DBUS_UNLOCK (sid_atom_cache);
1742 _dbus_hash_table_unref (sid_atom_cache);
1743 sid_atom_cache = NULL;
1747 * Returns the 2-way associated dbus_uid_t form a SID.
1749 * @param psid pointer to the SID
1752 _dbus_win_sid_to_uid_t (PSID psid)
1759 if (!IsValidSid (psid))
1761 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
1762 return DBUS_UID_UNSET;
1764 if (!ConvertSidToStringSidA (psid, &string))
1766 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
1767 return DBUS_UID_UNSET;
1770 atom = GlobalAddAtom(string);
1774 _dbus_verbose("%s GlobalAddAtom failed\n",__FUNCTION__);
1776 return DBUS_UID_UNSET;
1779 _DBUS_LOCK (sid_atom_cache);
1781 if (sid_atom_cache == NULL)
1783 sid_atom_cache = _dbus_hash_table_new (DBUS_HASH_ULONG, NULL, NULL);
1784 _dbus_register_shutdown_func (_sid_atom_cache_shutdown, NULL);
1788 olduid = (dbus_uid_t) _dbus_hash_table_lookup_ulong (sid_atom_cache, uid);
1792 _dbus_verbose("%s sid with id %i found in cache\n",__FUNCTION__, olduid);
1797 _dbus_hash_table_insert_ulong (sid_atom_cache, uid, (void*) uid);
1798 _dbus_verbose("%s sid %s added with uid %i to cache\n",__FUNCTION__, string, uid);
1801 _DBUS_UNLOCK (sid_atom_cache);
1806 dbus_bool_t _dbus_uid_t_to_win_sid (dbus_uid_t uid, PSID *ppsid)
1811 atom = _dbus_hash_table_lookup_ulong (sid_atom_cache, uid);
1814 _dbus_verbose("%s uid %i not found in cache\n",__FUNCTION__,uid);
1817 memset( string, '.', sizeof(string) );
1818 if (!GlobalGetAtomNameA( (ATOM) atom, string, 255 ))
1820 _dbus_verbose("%s uid %i not found in cache\n",__FUNCTION__, uid);
1823 if (!ConvertStringSidToSidA(string, ppsid))
1825 _dbus_verbose("%s could not convert %s into sid \n",__FUNCTION__, string);
1828 _dbus_verbose("%s converted %s into sid \n",__FUNCTION__, string);
1833 /** @} end of sysdeps-win */
1837 * @returns process UID
1842 #ifndef ENABLE_UID_TO_SID
1843 return DBUS_UID_UNSET;
1845 dbus_uid_t retval = DBUS_UID_UNSET;
1846 HANDLE process_token = NULL;
1847 TOKEN_USER *token_user = NULL;
1850 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
1851 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
1852 else if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
1853 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1854 || (token_user = alloca (n)) == NULL
1855 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
1856 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
1858 retval = _dbus_win_sid_to_uid_t (token_user->User.Sid);
1860 if (process_token != NULL)
1861 CloseHandle (process_token);
1863 _dbus_verbose("_dbus_getuid() returns %d\n",retval);
1869 * The only reason this is separate from _dbus_getpid() is to allow it
1870 * on Windows for logging but not for other purposes.
1872 * @returns process ID to put in log messages
1875 _dbus_pid_for_log (void)
1877 return _dbus_getpid ();
1881 * @param points to sid buffer, need to be freed with LocalFree()
1882 * @returns process sid
1885 _dbus_getsid(char **sid)
1887 HANDLE process_token = NULL;
1888 TOKEN_USER *token_user = NULL;
1893 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
1895 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
1898 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
1899 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1900 || (token_user = alloca (n)) == NULL
1901 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
1903 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
1906 psid = token_user->User.Sid;
1907 if (!IsValidSid (psid))
1909 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
1912 if (!ConvertSidToStringSidA (psid, sid))
1914 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
1920 if (process_token != NULL)
1921 CloseHandle (process_token);
1923 _dbus_verbose("_dbus_getsid() returns %d\n",retval);
1928 #ifdef DBUS_BUILD_TESTS
1930 * @returns process GID
1935 #ifndef ENABLE_UID_TO_SID
1936 return DBUS_GID_UNSET;
1938 dbus_gid_t retval = DBUS_GID_UNSET;
1939 HANDLE process_token = NULL;
1940 TOKEN_PRIMARY_GROUP *token_primary_group = NULL;
1943 if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token))
1944 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
1945 else if ((!GetTokenInformation (process_token, TokenPrimaryGroup,
1947 GetLastError () != ERROR_INSUFFICIENT_BUFFER) ||
1948 (token_primary_group = alloca (n)) == NULL ||
1949 !GetTokenInformation (process_token, TokenPrimaryGroup,
1950 token_primary_group, n, &n))
1951 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
1953 retval = _dbus_win_sid_to_uid_t (token_primary_group->PrimaryGroup);
1955 if (process_token != NULL)
1956 CloseHandle (process_token);
1964 _dbus_domain_test (const char *test_data_dir)
1966 if (!_dbus_test_oom_handling ("spawn_nonexistent",
1967 check_spawn_nonexistent,
1974 #endif //DBUS_BUILD_TESTS
1976 /************************************************************************
1980 ************************************************************************/
1983 * Creates a full-duplex pipe (as in socketpair()).
1984 * Sets both ends of the pipe nonblocking.
1986 * @todo libdbus only uses this for the debug-pipe server, so in
1987 * principle it could be in dbus-sysdeps-util.c, except that
1988 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
1989 * debug-pipe server is used.
1991 * @param fd1 return location for one end
1992 * @param fd2 return location for the other end
1993 * @param blocking #TRUE if pipe should be blocking
1994 * @param error error return
1995 * @returns #FALSE on failure (if error is set)
1998 _dbus_full_duplex_pipe (int *fd1,
2000 dbus_bool_t blocking,
2003 SOCKET temp, socket1 = -1, socket2 = -1;
2004 struct sockaddr_in saddr;
2007 fd_set read_set, write_set;
2009 #ifdef ENABLE_DBUSSOCKET
2014 _dbus_win_startup_winsock ();
2016 temp = socket (AF_INET, SOCK_STREAM, 0);
2017 if (temp == INVALID_SOCKET)
2019 DBUS_SOCKET_SET_ERRNO ();
2024 if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
2026 DBUS_SOCKET_SET_ERRNO ();
2031 saddr.sin_family = AF_INET;
2033 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
2035 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
2037 DBUS_SOCKET_SET_ERRNO ();
2041 if (listen (temp, 1) == SOCKET_ERROR)
2043 DBUS_SOCKET_SET_ERRNO ();
2047 len = sizeof (saddr);
2048 if (getsockname (temp, (struct sockaddr *)&saddr, &len))
2050 DBUS_SOCKET_SET_ERRNO ();
2054 socket1 = socket (AF_INET, SOCK_STREAM, 0);
2055 if (socket1 == INVALID_SOCKET)
2057 DBUS_SOCKET_SET_ERRNO ();
2062 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
2064 DBUS_SOCKET_SET_ERRNO ();
2068 if (connect (socket1, (struct sockaddr *)&saddr, len) != SOCKET_ERROR ||
2069 WSAGetLastError () != WSAEWOULDBLOCK)
2071 DBUS_SOCKET_SET_ERRNO ();
2075 FD_ZERO (&read_set);
2076 FD_SET (temp, &read_set);
2081 if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
2083 DBUS_SOCKET_SET_ERRNO ();
2087 _dbus_assert (FD_ISSET (temp, &read_set));
2089 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
2090 if (socket2 == INVALID_SOCKET)
2092 DBUS_SOCKET_SET_ERRNO ();
2096 FD_ZERO (&write_set);
2097 FD_SET (socket1, &write_set);
2102 if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
2104 DBUS_SOCKET_SET_ERRNO ();
2108 _dbus_assert (FD_ISSET (socket1, &write_set));
2113 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
2115 DBUS_SOCKET_SET_ERRNO ();
2120 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
2122 DBUS_SOCKET_SET_ERRNO ();
2129 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
2131 DBUS_SOCKET_SET_ERRNO ();
2136 #ifdef ENABLE_DBUSSOCKET
2138 *fd1 = _dbus_socket_to_handle (&sock);
2140 *fd2 = _dbus_socket_to_handle (&sock);
2146 _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
2147 *fd1, socket1, *fd2, socket2);
2154 closesocket (socket2);
2156 closesocket (socket1);
2160 dbus_set_error (error, _dbus_error_from_errno (errno),
2161 "Could not setup socket pair: %s",
2162 _dbus_strerror (errno));
2168 * Wrapper for poll().
2170 * @param fds the file descriptors to poll
2171 * @param n_fds number of descriptors in the array
2172 * @param timeout_milliseconds timeout or -1 for infinite
2173 * @returns numbers of fds with revents, or <0 on error
2175 #define USE_CHRIS_IMPL 0
2178 _dbus_poll (DBusPollFD *fds,
2180 int timeout_milliseconds)
2182 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
2183 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
2191 #define DBUS_STACK_WSAEVENTS 256
2192 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
2193 WSAEVENT *pEvents = NULL;
2194 if (n_fds > DBUS_STACK_WSAEVENTS)
2195 pEvents = calloc(sizeof(WSAEVENT), n_fds);
2197 pEvents = eventsOnStack;
2199 _dbus_lock_sockets();
2201 #ifdef DBUS_ENABLE_VERBOSE_MODE
2203 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
2204 for (i = 0; i < n_fds; i++)
2206 static dbus_bool_t warned = FALSE;
2208 DBusPollFD *fdp = &fds[i];
2210 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2212 if (s->is_used == 0)
2214 _dbus_warn ("no valid socket");
2218 if (fdp->events & _DBUS_POLLIN)
2219 msgp += sprintf (msgp, "R:%d ", s->fd);
2221 if (fdp->events & _DBUS_POLLOUT)
2222 msgp += sprintf (msgp, "W:%d ", s->fd);
2224 msgp += sprintf (msgp, "E:%d\n\t", s->fd);
2226 // FIXME: more robust code for long msg
2227 // create on heap when msg[] becomes too small
2228 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
2230 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
2234 msgp += sprintf (msgp, "\n");
2235 _dbus_verbose ("%s",msg);
2237 for (i = 0; i < n_fds; i++)
2240 DBusPollFD *fdp = &fds[i];
2242 long lNetworkEvents = FD_OOB;
2244 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2246 if (s->is_used == 0)
2249 ev = WSACreateEvent();
2251 if (fdp->events & _DBUS_POLLIN)
2252 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
2254 if (fdp->events & _DBUS_POLLOUT)
2255 lNetworkEvents |= FD_WRITE | FD_CONNECT;
2257 WSAEventSelect(s->fd, ev, lNetworkEvents);
2262 _dbus_unlock_sockets();
2264 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
2266 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
2268 DBUS_SOCKET_SET_ERRNO ();
2269 if (errno != EWOULDBLOCK)
2270 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror (errno));
2273 else if (ready == WSA_WAIT_TIMEOUT)
2275 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
2278 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
2281 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
2283 _dbus_lock_sockets();
2284 for (i = 0; i < n_fds; i++)
2287 DBusPollFD *fdp = &fds[i];
2288 WSANETWORKEVENTS ne;
2290 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2294 WSAEnumNetworkEvents(s->fd, pEvents[i], &ne);
2296 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
2297 fdp->revents |= _DBUS_POLLIN;
2299 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
2300 fdp->revents |= _DBUS_POLLOUT;
2302 if (ne.lNetworkEvents & (FD_OOB))
2303 fdp->revents |= _DBUS_POLLERR;
2305 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
2306 msgp += sprintf (msgp, "R:%d ", s->fd);
2308 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
2309 msgp += sprintf (msgp, "W:%d ", s->fd);
2311 if (ne.lNetworkEvents & (FD_OOB))
2312 msgp += sprintf (msgp, "E:%d ", s->fd);
2314 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
2316 if(ne.lNetworkEvents)
2319 WSAEventSelect(s->fd, pEvents[i], 0);
2321 _dbus_unlock_sockets();
2323 msgp += sprintf (msgp, "\n");
2324 _dbus_verbose ("%s",msg);
2328 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
2332 for(i = 0; i < n_fds; i++)
2334 WSACloseEvent(pEvents[i]);
2337 if (n_fds > DBUS_STACK_WSAEVENTS)
2343 #else // USE_CHRIS_IMPL
2345 #ifdef ENABLE_DBUSSOCKET
2348 _dbus_poll (DBusPollFD *fds,
2350 int timeout_milliseconds)
2352 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
2353 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
2356 fd_set read_set, write_set, err_set;
2362 FD_ZERO (&read_set);
2363 FD_ZERO (&write_set);
2366 _dbus_lock_sockets();
2368 #ifdef DBUS_ENABLE_VERBOSE_MODE
2370 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
2371 for (i = 0; i < n_fds; i++)
2373 static dbus_bool_t warned = FALSE;
2375 DBusPollFD *fdp = &fds[i];
2377 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2379 if (s->is_used == 0)
2381 _dbus_warn ("no valid socket");
2385 if (fdp->events & _DBUS_POLLIN)
2386 msgp += sprintf (msgp, "R:%d ", s->fd);
2388 if (fdp->events & _DBUS_POLLOUT)
2389 msgp += sprintf (msgp, "W:%d ", s->fd);
2391 msgp += sprintf (msgp, "E:%d\n\t", s->fd);
2393 // FIXME: more robust code for long msg
2394 // create on heap when msg[] becomes too small
2395 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
2397 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
2401 msgp += sprintf (msgp, "\n");
2402 _dbus_verbose ("%s",msg);
2404 for (i = 0; i < n_fds; i++)
2407 DBusPollFD *fdp = &fds[i];
2409 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2411 if (s->is_used != 1)
2414 if (fdp->events & _DBUS_POLLIN)
2415 FD_SET (s->fd, &read_set);
2417 if (fdp->events & _DBUS_POLLOUT)
2418 FD_SET (s->fd, &write_set);
2420 FD_SET (s->fd, &err_set);
2422 max_fd = MAX (max_fd, s->fd);
2425 _dbus_unlock_sockets();
2427 tv.tv_sec = timeout_milliseconds / 1000;
2428 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2430 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2431 timeout_milliseconds < 0 ? NULL : &tv);
2433 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
2435 DBUS_SOCKET_SET_ERRNO ();
2436 if (errno != EWOULDBLOCK)
2437 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
2439 else if (ready == 0)
2440 _dbus_verbose ("select: = 0\n");
2444 #ifdef DBUS_ENABLE_VERBOSE_MODE
2446 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
2447 _dbus_lock_sockets();
2448 for (i = 0; i < n_fds; i++)
2451 DBusPollFD *fdp = &fds[i];
2453 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2455 if (FD_ISSET (s->fd, &read_set))
2456 msgp += sprintf (msgp, "R:%d ", s->fd);
2458 if (FD_ISSET (s->fd, &write_set))
2459 msgp += sprintf (msgp, "W:%d ", s->fd);
2461 if (FD_ISSET (s->fd, &err_set))
2462 msgp += sprintf (msgp, "E:%d\n\t", s->fd);
2464 msgp += sprintf (msgp, "\n");
2465 _dbus_verbose ("%s",msg);
2468 for (i = 0; i < n_fds; i++)
2471 DBusPollFD *fdp = &fds[i];
2473 _dbus_handle_to_socket_unlocked(fdp->fd, &s);
2477 if (FD_ISSET (s->fd, &read_set))
2478 fdp->revents |= _DBUS_POLLIN;
2480 if (FD_ISSET (s->fd, &write_set))
2481 fdp->revents |= _DBUS_POLLOUT;
2483 if (FD_ISSET (s->fd, &err_set))
2484 fdp->revents |= _DBUS_POLLERR;
2486 _dbus_unlock_sockets();
2490 #else // ENABLE_DBUSSOCKET
2493 _dbus_poll (DBusPollFD *fds,
2495 int timeout_milliseconds)
2497 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
2498 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
2501 fd_set read_set, write_set, err_set;
2507 FD_ZERO (&read_set);
2508 FD_ZERO (&write_set);
2512 #ifdef DBUS_ENABLE_VERBOSE_MODE
2514 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
2515 for (i = 0; i < n_fds; i++)
2517 static dbus_bool_t warned = FALSE;
2519 DBusPollFD *fdp = &fds[i];
2523 if (fdp->events & _DBUS_POLLIN)
2524 msgp += sprintf (msgp, "R:%d ", fd);
2526 if (fdp->events & _DBUS_POLLOUT)
2527 msgp += sprintf (msgp, "W:%d ", fd);
2529 msgp += sprintf (msgp, "E:%d\n\t", fd);
2531 // FIXME: more robust code for long msg
2532 // create on heap when msg[] becomes too small
2533 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
2535 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
2539 msgp += sprintf (msgp, "\n");
2540 _dbus_verbose ("%s",msg);
2542 for (i = 0; i < n_fds; i++)
2545 DBusPollFD *fdp = &fds[i];
2548 if (fdp->events & _DBUS_POLLIN)
2549 FD_SET (fd, &read_set);
2551 if (fdp->events & _DBUS_POLLOUT)
2552 FD_SET (fd, &write_set);
2554 FD_SET (fd, &err_set);
2556 max_fd = MAX (max_fd, fd);
2560 tv.tv_sec = timeout_milliseconds / 1000;
2561 tv.tv_usec = (timeout_milliseconds % 1000) * 1000;
2563 ready = select (max_fd + 1, &read_set, &write_set, &err_set,
2564 timeout_milliseconds < 0 ? NULL : &tv);
2566 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
2568 DBUS_SOCKET_SET_ERRNO ();
2569 if (errno != EWOULDBLOCK)
2570 _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
2572 else if (ready == 0)
2573 _dbus_verbose ("select: = 0\n");
2577 #ifdef DBUS_ENABLE_VERBOSE_MODE
2579 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
2581 for (i = 0; i < n_fds; i++)
2584 DBusPollFD *fdp = &fds[i];
2587 if (FD_ISSET (fd, &read_set))
2588 msgp += sprintf (msgp, "R:%d ", fd);
2590 if (FD_ISSET (fd, &write_set))
2591 msgp += sprintf (msgp, "W:%d ", fd);
2593 if (FD_ISSET (fd, &err_set))
2594 msgp += sprintf (msgp, "E:%d\n\t", fd);
2596 msgp += sprintf (msgp, "\n");
2597 _dbus_verbose ("%s",msg);
2600 for (i = 0; i < n_fds; i++)
2603 DBusPollFD *fdp = &fds[i];
2608 if (FD_ISSET (fd, &read_set))
2609 fdp->revents |= _DBUS_POLLIN;
2611 if (FD_ISSET (fd, &write_set))
2612 fdp->revents |= _DBUS_POLLOUT;
2614 if (FD_ISSET (fd, &err_set))
2615 fdp->revents |= _DBUS_POLLERR;
2621 #endif //ENABLE_DBUSSOCKET
2623 #endif // USE_CHRIS_IMPL
2626 /************************************************************************
2630 ************************************************************************/
2634 * Assigns an error name and message corresponding to a Win32 error
2635 * code to a DBusError. Does nothing if error is #NULL.
2637 * @param error the error.
2638 * @param code the Win32 error code
2641 _dbus_win_set_error_from_win_error (DBusError *error,
2646 /* As we want the English message, use the A API */
2647 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
2648 FORMAT_MESSAGE_IGNORE_INSERTS |
2649 FORMAT_MESSAGE_FROM_SYSTEM,
2650 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
2651 (LPTSTR) &msg, 0, NULL);
2656 msg_copy = dbus_malloc (strlen (msg));
2657 strcpy (msg_copy, msg);
2660 dbus_set_error (error, "win32.error", "%s", msg_copy);
2663 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
2667 _dbus_win_warn_win_error (const char *message,
2672 dbus_error_init (&error);
2673 _dbus_win_set_error_from_win_error (&error, code);
2674 _dbus_warn ("%s: %s\n", message, error.message);
2675 dbus_error_free (&error);
2679 * A wrapper around strerror() because some platforms
2680 * may be lame and not have strerror().
2682 * @param error_number errno.
2683 * @returns error description.
2686 _dbus_strerror (int error_number)
2694 switch (error_number)
2697 return "Interrupted function call";
2699 return "Permission denied";
2701 return "Bad address";
2703 return "Invalid argument";
2705 return "Too many open files";
2706 case WSAEWOULDBLOCK:
2707 return "Resource temporarily unavailable";
2708 case WSAEINPROGRESS:
2709 return "Operation now in progress";
2711 return "Operation already in progress";
2713 return "Socket operation on nonsocket";
2714 case WSAEDESTADDRREQ:
2715 return "Destination address required";
2717 return "Message too long";
2719 return "Protocol wrong type for socket";
2720 case WSAENOPROTOOPT:
2721 return "Bad protocol option";
2722 case WSAEPROTONOSUPPORT:
2723 return "Protocol not supported";
2724 case WSAESOCKTNOSUPPORT:
2725 return "Socket type not supported";
2727 return "Operation not supported";
2728 case WSAEPFNOSUPPORT:
2729 return "Protocol family not supported";
2730 case WSAEAFNOSUPPORT:
2731 return "Address family not supported by protocol family";
2733 return "Address already in use";
2734 case WSAEADDRNOTAVAIL:
2735 return "Cannot assign requested address";
2737 return "Network is down";
2738 case WSAENETUNREACH:
2739 return "Network is unreachable";
2741 return "Network dropped connection on reset";
2742 case WSAECONNABORTED:
2743 return "Software caused connection abort";
2745 return "Connection reset by peer";
2747 return "No buffer space available";
2749 return "Socket is already connected";
2751 return "Socket is not connected";
2753 return "Cannot send after socket shutdown";
2755 return "Connection timed out";
2756 case WSAECONNREFUSED:
2757 return "Connection refused";
2759 return "Host is down";
2760 case WSAEHOSTUNREACH:
2761 return "No route to host";
2763 return "Too many processes";
2765 return "Graceful shutdown in progress";
2766 case WSATYPE_NOT_FOUND:
2767 return "Class type not found";
2768 case WSAHOST_NOT_FOUND:
2769 return "Host not found";
2771 return "Nonauthoritative host not found";
2772 case WSANO_RECOVERY:
2773 return "This is a nonrecoverable error";
2775 return "Valid name, no data record of requested type";
2776 case WSA_INVALID_HANDLE:
2777 return "Specified event object handle is invalid";
2778 case WSA_INVALID_PARAMETER:
2779 return "One or more parameters are invalid";
2780 case WSA_IO_INCOMPLETE:
2781 return "Overlapped I/O event object not in signaled state";
2782 case WSA_IO_PENDING:
2783 return "Overlapped operations will complete later";
2784 case WSA_NOT_ENOUGH_MEMORY:
2785 return "Insufficient memory available";
2786 case WSA_OPERATION_ABORTED:
2787 return "Overlapped operation aborted";
2788 #ifdef WSAINVALIDPROCTABLE
2790 case WSAINVALIDPROCTABLE:
2791 return "Invalid procedure table from service provider";
2793 #ifdef WSAINVALIDPROVIDER
2795 case WSAINVALIDPROVIDER:
2796 return "Invalid service provider version number";
2798 #ifdef WSAPROVIDERFAILEDINIT
2800 case WSAPROVIDERFAILEDINIT:
2801 return "Unable to initialize a service provider";
2804 case WSASYSCALLFAILURE:
2805 return "System call failure";
2807 msg = strerror (error_number);
2817 /* lan manager error codes */
2819 _dbus_lm_strerror(int error_number)
2826 switch (error_number)
2828 case NERR_NetNotStarted:
2829 return "The workstation driver is not installed.";
2830 case NERR_UnknownServer:
2831 return "The server could not be located.";
2833 return "An internal error occurred. The network cannot access a shared memory segment.";
2834 case NERR_NoNetworkResource:
2835 return "A network resource shortage occurred.";
2836 case NERR_RemoteOnly:
2837 return "This operation is not supported on workstations.";
2838 case NERR_DevNotRedirected:
2839 return "The device is not connected.";
2840 case NERR_ServerNotStarted:
2841 return "The Server service is not started.";
2842 case NERR_ItemNotFound:
2843 return "The queue is empty.";
2844 case NERR_UnknownDevDir:
2845 return "The device or directory does not exist.";
2846 case NERR_RedirectedPath:
2847 return "The operation is invalid on a redirected resource.";
2848 case NERR_DuplicateShare:
2849 return "The name has already been shared.";
2851 return "The server is currently out of the requested resource.";
2852 case NERR_TooManyItems:
2853 return "Requested addition of items exceeds the maximum allowed.";
2854 case NERR_InvalidMaxUsers:
2855 return "The Peer service supports only two simultaneous users.";
2856 case NERR_BufTooSmall:
2857 return "The API return buffer is too small.";
2858 case NERR_RemoteErr:
2859 return "A remote API error occurred.";
2860 case NERR_LanmanIniError:
2861 return "An error occurred when opening or reading the configuration file.";
2862 case NERR_NetworkError:
2863 return "A general network error occurred.";
2864 case NERR_WkstaInconsistentState:
2865 return "The Workstation service is in an inconsistent state. Restart the computer before restarting the Workstation service.";
2866 case NERR_WkstaNotStarted:
2867 return "The Workstation service has not been started.";
2868 case NERR_BrowserNotStarted:
2869 return "The requested information is not available.";
2870 case NERR_InternalError:
2871 return "An internal error occurred.";
2872 case NERR_BadTransactConfig:
2873 return "The server is not configured for transactions.";
2874 case NERR_InvalidAPI:
2875 return "The requested API is not supported on the remote server.";
2876 case NERR_BadEventName:
2877 return "The event name is invalid.";
2878 case NERR_DupNameReboot:
2879 return "The computer name already exists on the network. Change it and restart the computer.";
2880 case NERR_CfgCompNotFound:
2881 return "The specified component could not be found in the configuration information.";
2882 case NERR_CfgParamNotFound:
2883 return "The specified parameter could not be found in the configuration information.";
2884 case NERR_LineTooLong:
2885 return "A line in the configuration file is too long.";
2886 case NERR_QNotFound:
2887 return "The printer does not exist.";
2888 case NERR_JobNotFound:
2889 return "The print job does not exist.";
2890 case NERR_DestNotFound:
2891 return "The printer destination cannot be found.";
2892 case NERR_DestExists:
2893 return "The printer destination already exists.";
2895 return "The printer queue already exists.";
2897 return "No more printers can be added.";
2898 case NERR_JobNoRoom:
2899 return "No more print jobs can be added.";
2900 case NERR_DestNoRoom:
2901 return "No more printer destinations can be added.";
2903 return "This printer destination is idle and cannot accept control operations.";
2904 case NERR_DestInvalidOp:
2905 return "This printer destination request contains an invalid control function.";
2906 case NERR_ProcNoRespond:
2907 return "The print processor is not responding.";
2908 case NERR_SpoolerNotLoaded:
2909 return "The spooler is not running.";
2910 case NERR_DestInvalidState:
2911 return "This operation cannot be performed on the print destination in its current state.";
2912 case NERR_QInvalidState:
2913 return "This operation cannot be performed on the printer queue in its current state.";
2914 case NERR_JobInvalidState:
2915 return "This operation cannot be performed on the print job in its current state.";
2916 case NERR_SpoolNoMemory:
2917 return "A spooler memory allocation failure occurred.";
2918 case NERR_DriverNotFound:
2919 return "The device driver does not exist.";
2920 case NERR_DataTypeInvalid:
2921 return "The data type is not supported by the print processor.";
2922 case NERR_ProcNotFound:
2923 return "The print processor is not installed.";
2924 case NERR_ServiceTableLocked:
2925 return "The service database is locked.";
2926 case NERR_ServiceTableFull:
2927 return "The service table is full.";
2928 case NERR_ServiceInstalled:
2929 return "The requested service has already been started.";
2930 case NERR_ServiceEntryLocked:
2931 return "The service does not respond to control actions.";
2932 case NERR_ServiceNotInstalled:
2933 return "The service has not been started.";
2934 case NERR_BadServiceName:
2935 return "The service name is invalid.";
2936 case NERR_ServiceCtlTimeout:
2937 return "The service is not responding to the control function.";
2938 case NERR_ServiceCtlBusy:
2939 return "The service control is busy.";
2940 case NERR_BadServiceProgName:
2941 return "The configuration file contains an invalid service program name.";
2942 case NERR_ServiceNotCtrl:
2943 return "The service could not be controlled in its present state.";
2944 case NERR_ServiceKillProc:
2945 return "The service ended abnormally.";
2946 case NERR_ServiceCtlNotValid:
2947 return "The requested pause or stop is not valid for this service.";
2948 case NERR_NotInDispatchTbl:
2949 return "The service control dispatcher could not find the service name in the dispatch table.";
2950 case NERR_BadControlRecv:
2951 return "The service control dispatcher pipe read failed.";
2952 case NERR_ServiceNotStarting:
2953 return "A thread for the new service could not be created.";
2954 case NERR_AlreadyLoggedOn:
2955 return "This workstation is already logged on to the local-area network.";
2956 case NERR_NotLoggedOn:
2957 return "The workstation is not logged on to the local-area network.";
2958 case NERR_BadUsername:
2959 return "The user name or group name parameter is invalid.";
2960 case NERR_BadPassword:
2961 return "The password parameter is invalid.";
2962 case NERR_UnableToAddName_W:
2963 return "@W The logon processor did not add the message alias.";
2964 case NERR_UnableToAddName_F:
2965 return "The logon processor did not add the message alias.";
2966 case NERR_UnableToDelName_W:
2967 return "@W The logoff processor did not delete the message alias.";
2968 case NERR_UnableToDelName_F:
2969 return "The logoff processor did not delete the message alias.";
2970 case NERR_LogonsPaused:
2971 return "Network logons are paused.";
2972 case NERR_LogonServerConflict:
2973 return "A centralized logon-server conflict occurred.";
2974 case NERR_LogonNoUserPath:
2975 return "The server is configured without a valid user path.";
2976 case NERR_LogonScriptError:
2977 return "An error occurred while loading or running the logon script.";
2978 case NERR_StandaloneLogon:
2979 return "The logon server was not specified. Your computer will be logged on as STANDALONE.";
2980 case NERR_LogonServerNotFound:
2981 return "The logon server could not be found.";
2982 case NERR_LogonDomainExists:
2983 return "There is already a logon domain for this computer.";
2984 case NERR_NonValidatedLogon:
2985 return "The logon server could not validate the logon.";
2986 case NERR_ACFNotFound:
2987 return "The security database could not be found.";
2988 case NERR_GroupNotFound:
2989 return "The group name could not be found.";
2990 case NERR_UserNotFound:
2991 return "The user name could not be found.";
2992 case NERR_ResourceNotFound:
2993 return "The resource name could not be found.";
2994 case NERR_GroupExists:
2995 return "The group already exists.";
2996 case NERR_UserExists:
2997 return "The user account already exists.";
2998 case NERR_ResourceExists:
2999 return "The resource permission list already exists.";
3000 case NERR_NotPrimary:
3001 return "This operation is only allowed on the primary domain controller of the domain.";
3002 case NERR_ACFNotLoaded:
3003 return "The security database has not been started.";
3004 case NERR_ACFNoRoom:
3005 return "There are too many names in the user accounts database.";
3006 case NERR_ACFFileIOFail:
3007 return "A disk I/O failure occurred.";
3008 case NERR_ACFTooManyLists:
3009 return "The limit of 64 entries per resource was exceeded.";
3010 case NERR_UserLogon:
3011 return "Deleting a user with a session is not allowed.";
3012 case NERR_ACFNoParent:
3013 return "The parent directory could not be located.";
3014 case NERR_CanNotGrowSegment:
3015 return "Unable to add to the security database session cache segment.";
3016 case NERR_SpeGroupOp:
3017 return "This operation is not allowed on this special group.";
3018 case NERR_NotInCache:
3019 return "This user is not cached in user accounts database session cache.";
3020 case NERR_UserInGroup:
3021 return "The user already belongs to this group.";
3022 case NERR_UserNotInGroup:
3023 return "The user does not belong to this group.";
3024 case NERR_AccountUndefined:
3025 return "This user account is undefined.";
3026 case NERR_AccountExpired:
3027 return "This user account has expired.";
3028 case NERR_InvalidWorkstation:
3029 return "The user is not allowed to log on from this workstation.";
3030 case NERR_InvalidLogonHours:
3031 return "The user is not allowed to log on at this time.";
3032 case NERR_PasswordExpired:
3033 return "The password of this user has expired.";
3034 case NERR_PasswordCantChange:
3035 return "The password of this user cannot change.";
3036 case NERR_PasswordHistConflict:
3037 return "This password cannot be used now.";
3038 case NERR_PasswordTooShort:
3039 return "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements.";
3040 case NERR_PasswordTooRecent:
3041 return "The password of this user is too recent to change.";
3042 case NERR_InvalidDatabase:
3043 return "The security database is corrupted.";
3044 case NERR_DatabaseUpToDate:
3045 return "No updates are necessary to this replicant network/local security database.";
3046 case NERR_SyncRequired:
3047 return "This replicant database is outdated; synchronization is required.";
3048 case NERR_UseNotFound:
3049 return "The network connection could not be found.";
3050 case NERR_BadAsgType:
3051 return "This asg_type is invalid.";
3052 case NERR_DeviceIsShared:
3053 return "This device is currently being shared.";
3054 case NERR_NoComputerName:
3055 return "The computer name could not be added as a message alias. The name may already exist on the network.";
3056 case NERR_MsgAlreadyStarted:
3057 return "The Messenger service is already started.";
3058 case NERR_MsgInitFailed:
3059 return "The Messenger service failed to start.";
3060 case NERR_NameNotFound:
3061 return "The message alias could not be found on the network.";
3062 case NERR_AlreadyForwarded:
3063 return "This message alias has already been forwarded.";
3064 case NERR_AddForwarded:
3065 return "This message alias has been added but is still forwarded.";
3066 case NERR_AlreadyExists:
3067 return "This message alias already exists locally.";
3068 case NERR_TooManyNames:
3069 return "The maximum number of added message aliases has been exceeded.";
3070 case NERR_DelComputerName:
3071 return "The computer name could not be deleted.";
3072 case NERR_LocalForward:
3073 return "Messages cannot be forwarded back to the same workstation.";
3074 case NERR_GrpMsgProcessor:
3075 return "An error occurred in the domain message processor.";
3076 case NERR_PausedRemote:
3077 return "The message was sent, but the recipient has paused the Messenger service.";
3078 case NERR_BadReceive:
3079 return "The message was sent but not received.";
3080 case NERR_NameInUse:
3081 return "The message alias is currently in use. Try again later.";
3082 case NERR_MsgNotStarted:
3083 return "The Messenger service has not been started.";
3084 case NERR_NotLocalName:
3085 return "The name is not on the local computer.";
3086 case NERR_NoForwardName:
3087 return "The forwarded message alias could not be found on the network.";
3088 case NERR_RemoteFull:
3089 return "The message alias table on the remote station is full.";
3090 case NERR_NameNotForwarded:
3091 return "Messages for this alias are not currently being forwarded.";
3092 case NERR_TruncatedBroadcast:
3093 return "The broadcast message was truncated.";
3094 case NERR_InvalidDevice:
3095 return "This is an invalid device name.";
3096 case NERR_WriteFault:
3097 return "A write fault occurred.";
3098 case NERR_DuplicateName:
3099 return "A duplicate message alias exists on the network.";
3100 case NERR_DeleteLater:
3101 return "@W This message alias will be deleted later.";
3102 case NERR_IncompleteDel:
3103 return "The message alias was not successfully deleted from all networks.";
3104 case NERR_MultipleNets:
3105 return "This operation is not supported on computers with multiple networks.";
3106 case NERR_NetNameNotFound:
3107 return "This shared resource does not exist.";
3108 case NERR_DeviceNotShared:
3109 return "This device is not shared.";
3110 case NERR_ClientNameNotFound:
3111 return "A session does not exist with that computer name.";
3112 case NERR_FileIdNotFound:
3113 return "There is not an open file with that identification number.";
3114 case NERR_ExecFailure:
3115 return "A failure occurred when executing a remote administration command.";
3117 return "A failure occurred when opening a remote temporary file.";
3118 case NERR_TooMuchData:
3119 return "The data returned from a remote administration command has been truncated to 64K.";
3120 case NERR_DeviceShareConflict:
3121 return "This device cannot be shared as both a spooled and a non-spooled resource.";
3122 case NERR_BrowserTableIncomplete:
3123 return "The information in the list of servers may be incorrect.";
3124 case NERR_NotLocalDomain:
3125 return "The computer is not active in this domain.";
3126 #ifdef NERR_IsDfsShare
3128 case NERR_IsDfsShare:
3129 return "The share must be removed from the Distributed File System before it can be deleted.";
3132 case NERR_DevInvalidOpCode:
3133 return "The operation is invalid for this device.";
3134 case NERR_DevNotFound:
3135 return "This device cannot be shared.";
3136 case NERR_DevNotOpen:
3137 return "This device was not open.";
3138 case NERR_BadQueueDevString:
3139 return "This device name list is invalid.";
3140 case NERR_BadQueuePriority:
3141 return "The queue priority is invalid.";
3142 case NERR_NoCommDevs:
3143 return "There are no shared communication devices.";
3144 case NERR_QueueNotFound:
3145 return "The queue you specified does not exist.";
3146 case NERR_BadDevString:
3147 return "This list of devices is invalid.";
3149 return "The requested device is invalid.";
3150 case NERR_InUseBySpooler:
3151 return "This device is already in use by the spooler.";
3152 case NERR_CommDevInUse:
3153 return "This device is already in use as a communication device.";
3154 case NERR_InvalidComputer:
3155 return "This computer name is invalid.";
3156 case NERR_MaxLenExceeded:
3157 return "The string and prefix specified are too long.";
3158 case NERR_BadComponent:
3159 return "This path component is invalid.";
3161 return "Could not determine the type of input.";
3162 case NERR_TooManyEntries:
3163 return "The buffer for types is not big enough.";
3164 case NERR_ProfileFileTooBig:
3165 return "Profile files cannot exceed 64K.";
3166 case NERR_ProfileOffset:
3167 return "The start offset is out of range.";
3168 case NERR_ProfileCleanup:
3169 return "The system cannot delete current connections to network resources.";
3170 case NERR_ProfileUnknownCmd:
3171 return "The system was unable to parse the command line in this file.";
3172 case NERR_ProfileLoadErr:
3173 return "An error occurred while loading the profile file.";
3174 case NERR_ProfileSaveErr:
3175 return "@W Errors occurred while saving the profile file. The profile was partially saved.";
3176 case NERR_LogOverflow:
3177 return "Log file %1 is full.";
3178 case NERR_LogFileChanged:
3179 return "This log file has changed between reads.";
3180 case NERR_LogFileCorrupt:
3181 return "Log file %1 is corrupt.";
3182 case NERR_SourceIsDir:
3183 return "The source path cannot be a directory.";
3184 case NERR_BadSource:
3185 return "The source path is illegal.";
3187 return "The destination path is illegal.";
3188 case NERR_DifferentServers:
3189 return "The source and destination paths are on different servers.";
3190 case NERR_RunSrvPaused:
3191 return "The Run server you requested is paused.";
3192 case NERR_ErrCommRunSrv:
3193 return "An error occurred when communicating with a Run server.";
3194 case NERR_ErrorExecingGhost:
3195 return "An error occurred when starting a background process.";
3196 case NERR_ShareNotFound:
3197 return "The shared resource you are connected to could not be found.";
3198 case NERR_InvalidLana:
3199 return "The LAN adapter number is invalid.";
3200 case NERR_OpenFiles:
3201 return "There are open files on the connection.";
3202 case NERR_ActiveConns:
3203 return "Active connections still exist.";
3204 case NERR_BadPasswordCore:
3205 return "This share name or password is invalid.";
3207 return "The device is being accessed by an active process.";
3208 case NERR_LocalDrive:
3209 return "The drive letter is in use locally.";
3210 case NERR_AlertExists:
3211 return "The specified client is already registered for the specified event.";
3212 case NERR_TooManyAlerts:
3213 return "The alert table is full.";
3214 case NERR_NoSuchAlert:
3215 return "An invalid or nonexistent alert name was raised.";
3216 case NERR_BadRecipient:
3217 return "The alert recipient is invalid.";
3218 case NERR_AcctLimitExceeded:
3219 return "A user's session with this server has been deleted.";
3220 case NERR_InvalidLogSeek:
3221 return "The log file does not contain the requested record number.";
3222 case NERR_BadUasConfig:
3223 return "The user accounts database is not configured correctly.";
3224 case NERR_InvalidUASOp:
3225 return "This operation is not permitted when the Netlogon service is running.";
3226 case NERR_LastAdmin:
3227 return "This operation is not allowed on the last administrative account.";
3228 case NERR_DCNotFound:
3229 return "Could not find domain controller for this domain.";
3230 case NERR_LogonTrackingError:
3231 return "Could not set logon information for this user.";
3232 case NERR_NetlogonNotStarted:
3233 return "The Netlogon service has not been started.";
3234 case NERR_CanNotGrowUASFile:
3235 return "Unable to add to the user accounts database.";
3236 case NERR_TimeDiffAtDC:
3237 return "This server's clock is not synchronized with the primary domain controller's clock.";
3238 case NERR_PasswordMismatch:
3239 return "A password mismatch has been detected.";
3240 case NERR_NoSuchServer:
3241 return "The server identification does not specify a valid server.";
3242 case NERR_NoSuchSession:
3243 return "The session identification does not specify a valid session.";
3244 case NERR_NoSuchConnection:
3245 return "The connection identification does not specify a valid connection.";
3246 case NERR_TooManyServers:
3247 return "There is no space for another entry in the table of available servers.";
3248 case NERR_TooManySessions:
3249 return "The server has reached the maximum number of sessions it supports.";
3250 case NERR_TooManyConnections:
3251 return "The server has reached the maximum number of connections it supports.";
3252 case NERR_TooManyFiles:
3253 return "The server cannot open more files because it has reached its maximum number.";
3254 case NERR_NoAlternateServers:
3255 return "There are no alternate servers registered on this server.";
3256 case NERR_TryDownLevel:
3257 return "Try down-level (remote admin protocol) version of API instead.";
3258 case NERR_UPSDriverNotStarted:
3259 return "The UPS driver could not be accessed by the UPS service.";
3260 case NERR_UPSInvalidConfig:
3261 return "The UPS service is not configured correctly.";
3262 case NERR_UPSInvalidCommPort:
3263 return "The UPS service could not access the specified Comm Port.";
3264 case NERR_UPSSignalAsserted:
3265 return "The UPS indicated a line fail or low battery situation. Service not started.";
3266 case NERR_UPSShutdownFailed:
3267 return "The UPS service failed to perform a system shut down.";
3268 case NERR_BadDosRetCode:
3269 return "The program below returned an MS-DOS error code:";
3270 case NERR_ProgNeedsExtraMem:
3271 return "The program below needs more memory:";
3272 case NERR_BadDosFunction:
3273 return "The program below called an unsupported MS-DOS function:";
3274 case NERR_RemoteBootFailed:
3275 return "The workstation failed to boot.";
3276 case NERR_BadFileCheckSum:
3277 return "The file below is corrupt.";
3278 case NERR_NoRplBootSystem:
3279 return "No loader is specified in the boot-block definition file.";
3280 case NERR_RplLoadrNetBiosErr:
3281 return "NetBIOS returned an error: The NCB and SMB are dumped above.";
3282 case NERR_RplLoadrDiskErr:
3283 return "A disk I/O error occurred.";
3284 case NERR_ImageParamErr:
3285 return "Image parameter substitution failed.";
3286 case NERR_TooManyImageParams:
3287 return "Too many image parameters cross disk sector boundaries.";
3288 case NERR_NonDosFloppyUsed:
3289 return "The image was not generated from an MS-DOS diskette formatted with /S.";
3290 case NERR_RplBootRestart:
3291 return "Remote boot will be restarted later.";
3292 case NERR_RplSrvrCallFailed:
3293 return "The call to the Remoteboot server failed.";
3294 case NERR_CantConnectRplSrvr:
3295 return "Cannot connect to the Remoteboot server.";
3296 case NERR_CantOpenImageFile:
3297 return "Cannot open image file on the Remoteboot server.";
3298 case NERR_CallingRplSrvr:
3299 return "Connecting to the Remoteboot server...";
3300 case NERR_StartingRplBoot:
3301 return "Connecting to the Remoteboot server...";
3302 case NERR_RplBootServiceTerm:
3303 return "Remote boot service was stopped; check the error log for the cause of the problem.";
3304 case NERR_RplBootStartFailed:
3305 return "Remote boot startup failed; check the error log for the cause of the problem.";
3306 case NERR_RPL_CONNECTED:
3307 return "A second connection to a Remoteboot resource is not allowed.";
3308 case NERR_BrowserConfiguredToNotRun:
3309 return "The browser service was configured with MaintainServerList=No.";
3310 case NERR_RplNoAdaptersStarted:
3311 return "Service failed to start since none of the network adapters started with this service.";
3312 case NERR_RplBadRegistry:
3313 return "Service failed to start due to bad startup information in the registry.";
3314 case NERR_RplBadDatabase:
3315 return "Service failed to start because its database is absent or corrupt.";
3316 case NERR_RplRplfilesShare:
3317 return "Service failed to start because RPLFILES share is absent.";
3318 case NERR_RplNotRplServer:
3319 return "Service failed to start because RPLUSER group is absent.";
3320 case NERR_RplCannotEnum:
3321 return "Cannot enumerate service records.";
3322 case NERR_RplWkstaInfoCorrupted:
3323 return "Workstation record information has been corrupted.";
3324 case NERR_RplWkstaNotFound:
3325 return "Workstation record was not found.";
3326 case NERR_RplWkstaNameUnavailable:
3327 return "Workstation name is in use by some other workstation.";
3328 case NERR_RplProfileInfoCorrupted:
3329 return "Profile record information has been corrupted.";
3330 case NERR_RplProfileNotFound:
3331 return "Profile record was not found.";
3332 case NERR_RplProfileNameUnavailable:
3333 return "Profile name is in use by some other profile.";
3334 case NERR_RplProfileNotEmpty:
3335 return "There are workstations using this profile.";
3336 case NERR_RplConfigInfoCorrupted:
3337 return "Configuration record information has been corrupted.";
3338 case NERR_RplConfigNotFound:
3339 return "Configuration record was not found.";
3340 case NERR_RplAdapterInfoCorrupted:
3341 return "Adapter ID record information has been corrupted.";
3342 case NERR_RplInternal:
3343 return "An internal service error has occurred.";
3344 case NERR_RplVendorInfoCorrupted:
3345 return "Vendor ID record information has been corrupted.";
3346 case NERR_RplBootInfoCorrupted:
3347 return "Boot block record information has been corrupted.";
3348 case NERR_RplWkstaNeedsUserAcct:
3349 return "The user account for this workstation record is missing.";
3350 case NERR_RplNeedsRPLUSERAcct:
3351 return "The RPLUSER local group could not be found.";
3352 case NERR_RplBootNotFound:
3353 return "Boot block record was not found.";
3354 case NERR_RplIncompatibleProfile:
3355 return "Chosen profile is incompatible with this workstation.";
3356 case NERR_RplAdapterNameUnavailable:
3357 return "Chosen network adapter ID is in use by some other workstation.";
3358 case NERR_RplConfigNotEmpty:
3359 return "There are profiles using this configuration.";
3360 case NERR_RplBootInUse:
3361 return "There are workstations, profiles, or configurations using this boot block.";
3362 case NERR_RplBackupDatabase:
3363 return "Service failed to backup Remoteboot database.";
3364 case NERR_RplAdapterNotFound:
3365 return "Adapter record was not found.";
3366 case NERR_RplVendorNotFound:
3367 return "Vendor record was not found.";
3368 case NERR_RplVendorNameUnavailable:
3369 return "Vendor name is in use by some other vendor record.";
3370 case NERR_RplBootNameUnavailable:
3371 return "(boot name, vendor ID) is in use by some other boot block record.";
3372 case NERR_RplConfigNameUnavailable:
3373 return "Configuration name is in use by some other configuration.";
3374 case NERR_DfsInternalCorruption:
3375 return "The internal database maintained by the Dfs service is corrupt.";
3376 case NERR_DfsVolumeDataCorrupt:
3377 return "One of the records in the internal Dfs database is corrupt.";
3378 case NERR_DfsNoSuchVolume:
3379 return "There is no DFS name whose entry path matches the input Entry Path.";
3380 case NERR_DfsVolumeAlreadyExists:
3381 return "A root or link with the given name already exists.";
3382 case NERR_DfsAlreadyShared:
3383 return "The server share specified is already shared in the Dfs.";
3384 case NERR_DfsNoSuchShare:
3385 return "The indicated server share does not support the indicated DFS namespace.";
3386 case NERR_DfsNotALeafVolume:
3387 return "The operation is not valid on this portion of the namespace.";
3388 case NERR_DfsLeafVolume:
3389 return "The operation is not valid on this portion of the namespace.";
3390 case NERR_DfsVolumeHasMultipleServers:
3391 return "The operation is ambiguous because the link has multiple servers.";
3392 case NERR_DfsCantCreateJunctionPoint:
3393 return "Unable to create a link.";
3394 case NERR_DfsServerNotDfsAware:
3395 return "The server is not Dfs Aware.";
3396 case NERR_DfsBadRenamePath:
3397 return "The specified rename target path is invalid.";
3398 case NERR_DfsVolumeIsOffline:
3399 return "The specified DFS link is offline.";
3400 case NERR_DfsNoSuchServer:
3401 return "The specified server is not a server for this link.";
3402 case NERR_DfsCyclicalName:
3403 return "A cycle in the Dfs name was detected.";
3404 case NERR_DfsNotSupportedInServerDfs:
3405 return "The operation is not supported on a server-based Dfs.";
3406 case NERR_DfsDuplicateService:
3407 return "This link is already supported by the specified server-share.";
3408 case NERR_DfsCantRemoveLastServerShare:
3409 return "Can't remove the last server-share supporting this root or link.";
3410 case NERR_DfsVolumeIsInterDfs:
3411 return "The operation is not supported for an Inter-DFS link.";
3412 case NERR_DfsInconsistent:
3413 return "The internal state of the Dfs Service has become inconsistent.";
3414 case NERR_DfsServerUpgraded:
3415 return "The Dfs Service has been installed on the specified server.";
3416 case NERR_DfsDataIsIdentical:
3417 return "The Dfs data being reconciled is identical.";
3418 case NERR_DfsCantRemoveDfsRoot:
3419 return "The DFS root cannot be deleted. Uninstall DFS if required.";
3420 case NERR_DfsChildOrParentInDfs:
3421 return "A child or parent directory of the share is already in a Dfs.";
3422 case NERR_DfsInternalError:
3423 return "Dfs internal error.";
3424 /* the following are not defined in mingw */
3427 case NERR_SetupAlreadyJoined:
3428 return "This machine is already joined to a domain.";
3429 case NERR_SetupNotJoined:
3430 return "This machine is not currently joined to a domain.";
3431 case NERR_SetupDomainController:
3432 return "This machine is a domain controller and cannot be unjoined from a domain.";
3433 case NERR_DefaultJoinRequired:
3434 return "The destination domain controller does not support creating machine accounts in OUs.";
3435 case NERR_InvalidWorkgroupName:
3436 return "The specified workgroup name is invalid.";
3437 case NERR_NameUsesIncompatibleCodePage:
3438 return "The specified computer name is incompatible with the default language used on the domain controller.";
3439 case NERR_ComputerAccountNotFound:
3440 return "The specified computer account could not be found.";
3441 case NERR_PersonalSku:
3442 return "This version of Windows cannot be joined to a domain.";
3443 case NERR_PasswordMustChange:
3444 return "The password must change at the next logon.";
3445 case NERR_AccountLockedOut:
3446 return "The account is locked out.";
3447 case NERR_PasswordTooLong:
3448 return "The password is too long.";
3449 case NERR_PasswordNotComplexEnough:
3450 return "The password does not meet the complexity policy.";
3451 case NERR_PasswordFilterError:
3452 return "The password does not meet the requirements of the password filter DLLs.";
3456 msg = strerror (error_number);
3472 /******************************************************************************
3474 Original CVS version of dbus-sysdeps.c
3476 ******************************************************************************/
3477 /* -*- mode: C; c-file-style: "gnu" -*- */
3478 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
3480 * Copyright (C) 2002, 2003 Red Hat, Inc.
3481 * Copyright (C) 2003 CodeFactory AB
3482 * Copyright (C) 2005 Novell, Inc.
3484 * Licensed under the Academic Free License version 2.1
3486 * This program is free software; you can redistribute it and/or modify
3487 * it under the terms of the GNU General Public License as published by
3488 * the Free Software Foundation; either version 2 of the License, or
3489 * (at your option) any later version.
3491 * This program is distributed in the hope that it will be useful,
3492 * but WITHOUT ANY WARRANTY; without even the implied warranty of
3493 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3494 * GNU General Public License for more details.
3496 * You should have received a copy of the GNU General Public License
3497 * along with this program; if not, write to the Free Software
3498 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
3504 * @addtogroup DBusInternalsUtils
3508 int _dbus_mkdir (const char *path,
3511 return _mkdir(path);
3515 * Exit the process, returning the given value.
3517 * @param code the exit code
3520 _dbus_exit (int code)
3526 * Creates a socket and connects to a socket at the given host
3527 * and port. The connection fd is returned, and is set up as
3530 * @param host the host name to connect to, NULL for loopback
3531 * @param port the prot to connect to
3532 * @param error return location for error code
3533 * @returns connection file descriptor or -1 on error
3536 _dbus_connect_tcp_socket (const char *host,
3540 #ifdef ENABLE_DBUSSOCKET
3543 struct sockaddr_in addr;
3545 struct in_addr *haddr;
3548 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3550 _dbus_win_startup_winsock ();
3552 s.fd = socket (AF_INET, SOCK_STREAM, 0);
3554 if (DBUS_SOCKET_IS_INVALID (s.fd))
3556 DBUS_SOCKET_SET_ERRNO ();
3557 dbus_set_error (error,
3558 _dbus_error_from_errno (errno),
3559 "Failed to create socket: %s",
3560 _dbus_strerror (errno));
3568 ina.s_addr = htonl (INADDR_LOOPBACK);
3572 he = gethostbyname (host);
3575 DBUS_SOCKET_SET_ERRNO ();
3576 dbus_set_error (error,
3577 _dbus_error_from_errno (errno),
3578 "Failed to lookup hostname: %s",
3580 DBUS_CLOSE_SOCKET (s.fd);
3584 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
3587 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
3588 addr.sin_family = AF_INET;
3589 addr.sin_port = htons (port);
3591 if (DBUS_SOCKET_API_RETURNS_ERROR
3592 (connect (s.fd, (struct sockaddr*) &addr, sizeof (addr)) < 0))
3594 DBUS_SOCKET_SET_ERRNO ();
3595 dbus_set_error (error,
3596 _dbus_error_from_errno (errno),
3597 "Failed to connect to socket %s:%d %s",
3598 host, port, _dbus_strerror (errno));
3600 DBUS_CLOSE_SOCKET (s.fd);
3606 handle = _dbus_socket_to_handle (&s);
3608 if (!_dbus_set_fd_nonblocking (handle, error))
3610 _dbus_close_socket (handle, NULL);
3619 struct sockaddr_in addr;
3621 struct in_addr *haddr;
3624 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3626 _dbus_win_startup_winsock ();
3628 fd = socket (AF_INET, SOCK_STREAM, 0);
3630 if (DBUS_SOCKET_IS_INVALID (fd))
3632 DBUS_SOCKET_SET_ERRNO ();
3633 dbus_set_error (error,
3634 _dbus_error_from_errno (errno),
3635 "Failed to create socket: %s",
3636 _dbus_strerror (errno));
3644 ina.s_addr = htonl (INADDR_LOOPBACK);
3648 he = gethostbyname (host);
3651 DBUS_SOCKET_SET_ERRNO ();
3652 dbus_set_error (error,
3653 _dbus_error_from_errno (errno),
3654 "Failed to lookup hostname: %s",
3656 DBUS_CLOSE_SOCKET (fd);
3660 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
3663 memcpy (&addr.sin_addr, haddr, sizeof(struct in_addr));
3664 addr.sin_family = AF_INET;
3665 addr.sin_port = htons (port);
3667 if (DBUS_SOCKET_API_RETURNS_ERROR
3668 (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0))
3670 DBUS_SOCKET_SET_ERRNO ();
3671 dbus_set_error (error,
3672 _dbus_error_from_errno (errno),
3673 "Failed to connect to socket %s:%d %s",
3674 host, port, _dbus_strerror (errno));
3676 DBUS_CLOSE_SOCKET (fd);
3682 if (!_dbus_set_fd_nonblocking (fd, error))
3684 _dbus_close_socket (fd, NULL);
3695 _dbus_daemon_init(const char *host, dbus_uint32_t port);
3697 * Creates a socket and binds it to the given port,
3698 * then listens on the socket. The socket is
3699 * set to be nonblocking.
3700 * In case of port=0 a random free port is used and
3701 * returned in the port parameter.
3703 * @param host the interface to listen on, NULL for loopback, empty for any
3704 * @param port the port to listen on, if zero a free port will be used
3705 * @param error return location for errors
3706 * @returns the listening file descriptor or -1 on error
3710 _dbus_listen_tcp_socket (const char *host,
3711 dbus_uint32_t *port,
3712 dbus_bool_t inaddr_any,
3715 #ifdef ENABLE_DBUSSOCKET
3718 struct sockaddr_in addr;
3720 struct in_addr *haddr;
3721 socklen_t len = (socklen_t) sizeof (struct sockaddr);
3725 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3727 _dbus_win_startup_winsock ();
3729 slisten.fd = socket (AF_INET, SOCK_STREAM, 0);
3731 if (DBUS_SOCKET_IS_INVALID (slisten.fd))
3733 DBUS_SOCKET_SET_ERRNO ();
3734 dbus_set_error (error, _dbus_error_from_errno (errno),
3735 "Failed to create socket \"%s:%d\": %s",
3736 host, port, _dbus_strerror (errno));
3742 ina.s_addr = htonl (INADDR_LOOPBACK);
3747 ina.s_addr = htonl (INADDR_ANY);
3752 he = gethostbyname (host);
3755 DBUS_SOCKET_SET_ERRNO ();
3756 dbus_set_error (error,
3757 _dbus_error_from_errno (errno),
3758 "Failed to lookup hostname: %s",
3760 DBUS_CLOSE_SOCKET (slisten.fd);
3764 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
3768 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
3769 addr.sin_family = AF_INET;
3770 addr.sin_port = htons (*port);
3772 if (bind (slisten.fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
3774 DBUS_SOCKET_SET_ERRNO ();
3775 dbus_set_error (error, _dbus_error_from_errno (errno),
3776 "Failed to bind socket \"%s:%d\": %s",
3777 host, *port, _dbus_strerror (errno));
3778 DBUS_CLOSE_SOCKET (slisten.fd);
3782 if (DBUS_SOCKET_API_RETURNS_ERROR (listen (slisten.fd, 30 /* backlog */)))
3784 DBUS_SOCKET_SET_ERRNO ();
3785 dbus_set_error (error, _dbus_error_from_errno (errno),
3786 "Failed to listen on socket \"%s:%d\": %s",
3787 host, *port, _dbus_strerror (errno));
3788 DBUS_CLOSE_SOCKET (slisten.fd);
3792 getsockname(slisten.fd, (struct sockaddr*) &addr, &len);
3793 *port = (dbus_uint32_t) ntohs(addr.sin_port);
3795 _dbus_daemon_init(host, ntohs(addr.sin_port));
3797 handle = _dbus_socket_to_handle (&slisten);
3799 if (!_dbus_set_fd_nonblocking (handle, error))
3801 _dbus_close_socket (handle, NULL);
3808 struct sockaddr_in addr;
3810 struct in_addr *haddr;
3811 socklen_t len = (socklen_t) sizeof (struct sockaddr);
3815 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3817 _dbus_win_startup_winsock ();
3819 fd = socket (AF_INET, SOCK_STREAM, 0);
3821 if (DBUS_SOCKET_IS_INVALID (fd))
3823 DBUS_SOCKET_SET_ERRNO ();
3824 dbus_set_error (error, _dbus_error_from_errno (errno),
3825 "Failed to create socket \"%s:%d\": %s",
3826 host, port, _dbus_strerror (errno));
3832 ina.s_addr = htonl (INADDR_LOOPBACK);
3837 ina.s_addr = htonl (INADDR_ANY);
3842 he = gethostbyname (host);
3845 DBUS_SOCKET_SET_ERRNO ();
3846 dbus_set_error (error,
3847 _dbus_error_from_errno (errno),
3848 "Failed to lookup hostname: %s",
3850 DBUS_CLOSE_SOCKET (fd);
3854 haddr = ((struct in_addr *) (he->h_addr_list)[0]);
3858 memcpy (&addr.sin_addr, haddr, sizeof (struct in_addr));
3859 addr.sin_family = AF_INET;
3860 addr.sin_port = htons (*port);
3862 if (bind (fd, (struct sockaddr*) &addr, sizeof (struct sockaddr)))
3864 DBUS_SOCKET_SET_ERRNO ();
3865 dbus_set_error (error, _dbus_error_from_errno (errno),
3866 "Failed to bind socket \"%s:%d\": %s",
3867 host, *port, _dbus_strerror (errno));
3868 DBUS_CLOSE_SOCKET (fd);
3872 if (DBUS_SOCKET_API_RETURNS_ERROR (listen (fd, 30 /* backlog */)))
3874 DBUS_SOCKET_SET_ERRNO ();
3875 dbus_set_error (error, _dbus_error_from_errno (errno),
3876 "Failed to listen on socket \"%s:%d\": %s",
3877 host, *port, _dbus_strerror (errno));
3878 DBUS_CLOSE_SOCKET (fd);
3882 getsockname(fd, (struct sockaddr*) &addr, &len);
3883 *port = (dbus_uint32_t) ntohs(addr.sin_port);
3885 _dbus_daemon_init(host, ntohs(addr.sin_port));
3887 if (!_dbus_set_fd_nonblocking (fd, error))
3889 _dbus_close_socket (fd, NULL);
3899 * Accepts a connection on a listening socket.
3900 * Handles EINTR for you.
3902 * @param listen_fd the listen file descriptor
3903 * @returns the connection fd of the client, or -1 on error
3906 _dbus_accept (int listen_handle)
3908 #ifdef ENABLE_DBUSSOCKET
3909 DBusSocket *slisten;
3911 struct sockaddr addr;
3914 _dbus_handle_to_socket(listen_handle, &slisten);
3916 addrlen = sizeof (addr);
3918 //FIXME: why do we not try it again on Windows?
3919 #if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
3923 sclient.fd = accept (slisten->fd, &addr, &addrlen);
3925 if (DBUS_SOCKET_IS_INVALID (sclient.fd))
3927 DBUS_SOCKET_SET_ERRNO ();
3928 #if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
3936 return _dbus_socket_to_handle (&sclient);
3940 struct sockaddr addr;
3945 addrlen = sizeof (addr);
3947 //FIXME: why do we not try it again on Windows?
3948 #if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
3952 sclient = accept (fd, &addr, &addrlen);
3954 if (DBUS_SOCKET_IS_INVALID (sclient))
3956 DBUS_SOCKET_SET_ERRNO ();
3957 #if !defined(DBUS_WIN) && !defined(DBUS_WINCE)
3973 _dbus_send_credentials_socket (int handle,
3976 /* FIXME: for the session bus credentials shouldn't matter (?), but
3977 * for the system bus they are presumably essential. A rough outline
3978 * of a way to implement the credential transfer would be this:
3980 * client waits to *read* a byte.
3982 * server creates a named pipe with a random name, sends a byte
3983 * contining its length, and its name.
3985 * client reads the name, connects to it (using Win32 API).
3987 * server waits for connection to the named pipe, then calls
3988 * ImpersonateNamedPipeClient(), notes its now-current credentials,
3989 * calls RevertToSelf(), closes its handles to the named pipe, and
3990 * is done. (Maybe there is some other way to get the SID of a named
3991 * pipe client without having to use impersonation?)
3993 * client closes its handles and is done.
3995 * Ralf: Why not sending credentials over the given this connection ?
3996 * Using named pipes makes it impossible to be connected from a unix client.
4002 _dbus_string_init_const_len (&buf, "\0", 1);
4004 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
4006 if (bytes_written < 0 && errno == EINTR)
4009 if (bytes_written < 0)
4011 dbus_set_error (error, _dbus_error_from_errno (errno),
4012 "Failed to write credentials byte: %s",
4013 _dbus_strerror (errno));
4016 else if (bytes_written == 0)
4018 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
4019 "wrote zero bytes writing credentials byte");
4024 _dbus_assert (bytes_written == 1);
4025 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
4032 * Reads a single byte which must be nul (an error occurs otherwise),
4033 * and reads unix credentials if available. Fills in pid/uid/gid with
4034 * -1 if no credentials are available. Return value indicates whether
4035 * a byte was read, not whether we got valid credentials. On some
4036 * systems, such as Linux, reading/writing the byte isn't actually
4037 * required, but we do it anyway just to avoid multiple codepaths.
4039 * Fails if no byte is available, so you must select() first.
4041 * The point of the byte is that on some systems we have to
4042 * use sendmsg()/recvmsg() to transmit credentials.
4044 * @param client_fd the client file descriptor
4045 * @param credentials struct to fill with credentials of client
4046 * @param error location to store error code
4047 * @returns #TRUE on success
4050 _dbus_read_credentials_socket (int handle,
4051 DBusCredentials *credentials,
4056 _dbus_string_init(&buf);
4058 bytes_read = _dbus_read_socket(handle, &buf, 1 );
4061 _dbus_verbose("got one zero byte from server");
4064 _dbus_string_free(&buf);
4065 _dbus_credentials_add_from_current_process (credentials);
4066 _dbus_verbose("FIXME: get faked credentials from current process");
4072 * Checks to make sure the given directory is
4073 * private to the user
4075 * @param dir the name of the directory
4076 * @param error error return
4077 * @returns #FALSE on failure
4080 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
4082 const char *directory;
4085 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4090 #ifdef ENABLE_DBUSUSERINFO
4092 fill_user_info (DBusUserInfo *info,
4094 const DBusString *username,
4097 const char *username_c;
4099 /* exactly one of username/uid provided */
4100 _dbus_assert (username != NULL || uid != DBUS_UID_UNSET);
4101 _dbus_assert (username == NULL || uid == DBUS_UID_UNSET);
4103 info->uid = DBUS_UID_UNSET;
4104 info->primary_gid = DBUS_GID_UNSET;
4105 info->group_ids = NULL;
4106 info->n_group_ids = 0;
4107 info->username = NULL;
4108 info->homedir = NULL;
4110 if (username != NULL)
4111 username_c = _dbus_string_get_const_data (username);
4115 if (uid != DBUS_UID_UNSET)
4117 if (!fill_win_user_info_from_uid (uid, info, error))
4119 _dbus_verbose("%s after fill_win_user_info_from_uid\n",__FUNCTION__);
4125 wchar_t *wname = _dbus_win_utf8_to_utf16 (username_c, error);
4130 if (!fill_win_user_info_from_name (wname, info, error))
4141 * Gets user info for the given user ID.
4143 * @param info user info object to initialize
4144 * @param uid the user ID
4145 * @param error error return
4146 * @returns #TRUE on success
4149 _dbus_user_info_fill_uid (DBusUserInfo *info,
4153 return fill_user_info (info, uid,
4159 * Gets user info for the given username.
4161 * @param info user info object to initialize
4162 * @param username the username
4163 * @param error error return
4164 * @returns #TRUE on success
4167 _dbus_user_info_fill (DBusUserInfo *info,
4168 const DBusString *username,
4171 return fill_user_info (info, DBUS_UID_UNSET,
4177 * Appends the given filename to the given directory.
4179 * @todo it might be cute to collapse multiple '/' such as "foo//"
4182 * @param dir the directory name
4183 * @param next_component the filename
4184 * @returns #TRUE on success
4187 _dbus_concat_dir_and_file (DBusString *dir,
4188 const DBusString *next_component)
4190 dbus_bool_t dir_ends_in_slash;
4191 dbus_bool_t file_starts_with_slash;
4193 if (_dbus_string_get_length (dir) == 0 ||
4194 _dbus_string_get_length (next_component) == 0)
4198 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
4199 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
4201 file_starts_with_slash =
4202 ('/' == _dbus_string_get_byte (next_component, 0) ||
4203 '\\' == _dbus_string_get_byte (next_component, 0));
4205 if (dir_ends_in_slash && file_starts_with_slash)
4207 _dbus_string_shorten (dir, 1);
4209 else if (!(dir_ends_in_slash || file_starts_with_slash))
4211 if (!_dbus_string_append_byte (dir, '\\'))
4215 return _dbus_string_copy (next_component, 0, dir,
4216 _dbus_string_get_length (dir));
4219 /*---------------- DBusCredentials ----------------------------------
4222 * Adds the credentials corresponding to the given username.
4224 * @param credentials credentials to fill in
4225 * @param username the username
4226 * @returns #TRUE if the username existed and we got some credentials
4229 _dbus_credentials_add_from_user (DBusCredentials *credentials,
4230 const DBusString *username)
4232 return _dbus_credentials_add_windows_sid (credentials,
4233 _dbus_string_get_const_data(username));
4237 * Adds the credentials of the current process to the
4238 * passed-in credentials object.
4240 * @param credentials credentials to add to
4241 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
4245 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
4247 dbus_bool_t retval = FALSE;
4250 if (!_dbus_getsid(&sid))
4253 if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
4256 if (!_dbus_credentials_add_windows_sid (credentials,sid))
4271 * Append to the string the identity we would like to have when we
4272 * authenticate, on UNIX this is the current process UID and on
4273 * Windows something else, probably a Windows SID string. No escaping
4274 * is required, that is done in dbus-auth.c. The username here
4275 * need not be anything human-readable, it can be the machine-readable
4276 * form i.e. a user id.
4278 * @param str the string to append to
4279 * @returns #FALSE on no memory
4280 * @todo to which class belongs this
4283 _dbus_append_user_from_current_process (DBusString *str)
4285 dbus_bool_t retval = FALSE;
4288 if (!_dbus_getsid(&sid))
4291 retval = _dbus_string_append (str,sid);
4298 * Gets our process ID
4299 * @returns process ID
4304 return GetCurrentProcessId ();
4307 /** nanoseconds in a second */
4308 #define NANOSECONDS_PER_SECOND 1000000000
4309 /** microseconds in a second */
4310 #define MICROSECONDS_PER_SECOND 1000000
4311 /** milliseconds in a second */
4312 #define MILLISECONDS_PER_SECOND 1000
4313 /** nanoseconds in a millisecond */
4314 #define NANOSECONDS_PER_MILLISECOND 1000000
4315 /** microseconds in a millisecond */
4316 #define MICROSECONDS_PER_MILLISECOND 1000
4319 * Sleeps the given number of milliseconds.
4320 * @param milliseconds number of milliseconds
4323 _dbus_sleep_milliseconds (int milliseconds)
4325 Sleep (milliseconds);
4330 * Get current time, as in gettimeofday().
4332 * @param tv_sec return location for number of seconds
4333 * @param tv_usec return location for number of microseconds
4336 _dbus_get_current_time (long *tv_sec,
4340 dbus_uint64_t *time64 = (dbus_uint64_t *) &ft;
4342 GetSystemTimeAsFileTime (&ft);
4344 /* Convert from 100s of nanoseconds since 1601-01-01
4345 * to Unix epoch. Yes, this is Y2038 unsafe.
4347 *time64 -= DBUS_INT64_CONSTANT (116444736000000000);
4351 *tv_sec = *time64 / 1000000;
4354 *tv_usec = *time64 % 1000000;
4359 * signal (SIGPIPE, SIG_IGN);
4362 _dbus_disable_sigpipe (void)
4364 _dbus_verbose("FIXME: implement _dbus_disable_sigpipe (void)\n");
4369 * Appends the contents of the given file to the string,
4370 * returning error code. At the moment, won't open a file
4371 * more than a megabyte in size.
4373 * @param str the string to append to
4374 * @param filename filename to load
4375 * @param error place to set an error
4376 * @returns #FALSE if error was set
4379 _dbus_file_get_contents (DBusString *str,
4380 const DBusString *filename,
4387 const char *filename_c;
4389 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4391 filename_c = _dbus_string_get_const_data (filename);
4393 /* O_BINARY useful on Cygwin and Win32 */
4394 if (!_dbus_file_open (&file, filename_c, O_RDONLY | O_BINARY, -1))
4396 dbus_set_error (error, _dbus_error_from_errno (errno),
4397 "Failed to open \"%s\": %s",
4399 _dbus_strerror (errno));
4403 if (!_dbus_fstat (&file, &sb))
4405 dbus_set_error (error, _dbus_error_from_errno (errno),
4406 "Failed to stat \"%s\": %s",
4408 _dbus_strerror (errno));
4410 _dbus_verbose ("fstat() failed: %s",
4411 _dbus_strerror (errno));
4413 _dbus_file_close (&file, NULL);
4418 if (sb.st_size > _DBUS_ONE_MEGABYTE)
4420 dbus_set_error (error, DBUS_ERROR_FAILED,
4421 "File size %lu of \"%s\" is too large.",
4422 (unsigned long) sb.st_size, filename_c);
4423 _dbus_file_close (&file, NULL);
4428 orig_len = _dbus_string_get_length (str);
4429 if (sb.st_size > 0 && S_ISREG (sb.st_mode))
4433 while (total < (int) sb.st_size)
4435 bytes_read = _dbus_file_read (&file, str,
4436 sb.st_size - total);
4437 if (bytes_read <= 0)
4439 dbus_set_error (error, _dbus_error_from_errno (errno),
4440 "Error reading \"%s\": %s",
4442 _dbus_strerror (errno));
4444 _dbus_verbose ("read() failed: %s",
4445 _dbus_strerror (errno));
4447 _dbus_file_close (&file, NULL);
4448 _dbus_string_set_length (str, orig_len);
4452 total += bytes_read;
4455 _dbus_file_close (&file, NULL);
4458 else if (sb.st_size != 0)
4460 _dbus_verbose ("Can only open regular files at the moment.\n");
4461 dbus_set_error (error, DBUS_ERROR_FAILED,
4462 "\"%s\" is not a regular file",
4464 _dbus_file_close (&file, NULL);
4469 _dbus_file_close (&file, NULL);
4475 * Writes a string out to a file. If the file exists,
4476 * it will be atomically overwritten by the new data.
4478 * @param str the string to write out
4479 * @param filename the file to save string to
4480 * @param error error to be filled in on failure
4481 * @returns #FALSE on failure
4484 _dbus_string_save_to_file (const DBusString *str,
4485 const DBusString *filename,
4490 const char *filename_c;
4491 DBusString tmp_filename;
4492 const char *tmp_filename_c;
4494 dbus_bool_t need_unlink;
4497 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4500 need_unlink = FALSE;
4502 if (!_dbus_string_init (&tmp_filename))
4504 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4508 if (!_dbus_string_copy (filename, 0, &tmp_filename, 0))
4510 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4511 _dbus_string_free (&tmp_filename);
4515 if (!_dbus_string_append (&tmp_filename, "."))
4517 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4518 _dbus_string_free (&tmp_filename);
4522 #define N_TMP_FILENAME_RANDOM_BYTES 8
4523 if (!_dbus_generate_random_ascii (&tmp_filename, N_TMP_FILENAME_RANDOM_BYTES))
4525 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
4526 _dbus_string_free (&tmp_filename);
4530 filename_c = _dbus_string_get_const_data (filename);
4531 tmp_filename_c = _dbus_string_get_const_data (&tmp_filename);
4533 if (!_dbus_file_open (&file, tmp_filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
4536 dbus_set_error (error, _dbus_error_from_errno (errno),
4537 "Could not create %s: %s", tmp_filename_c,
4538 _dbus_strerror (errno));
4545 bytes_to_write = _dbus_string_get_length (str);
4547 while (total < bytes_to_write)
4551 bytes_written = _dbus_file_write (&file, str, total,
4552 bytes_to_write - total);
4554 if (bytes_written <= 0)
4556 dbus_set_error (error, _dbus_error_from_errno (errno),
4557 "Could not write to %s: %s", tmp_filename_c,
4558 _dbus_strerror (errno));
4563 total += bytes_written;
4566 if (!_dbus_file_close (&file, NULL))
4568 dbus_set_error (error, _dbus_error_from_errno (errno),
4569 "Could not close file %s: %s",
4570 tmp_filename_c, _dbus_strerror (errno));
4576 if ((unlink (filename_c) == -1 && errno != ENOENT) ||
4577 rename (tmp_filename_c, filename_c) < 0)
4579 dbus_set_error (error, _dbus_error_from_errno (errno),
4580 "Could not rename %s to %s: %s",
4581 tmp_filename_c, filename_c,
4582 _dbus_strerror (errno));
4587 need_unlink = FALSE;
4592 /* close first, then unlink, to prevent ".nfs34234235" garbage
4596 if (_dbus_is_valid_file(&file))
4597 _dbus_file_close (&file, NULL);
4599 if (need_unlink && unlink (tmp_filename_c) < 0)
4600 _dbus_verbose ("Failed to unlink temp file %s: %s\n",
4601 tmp_filename_c, _dbus_strerror (errno));
4603 _dbus_string_free (&tmp_filename);
4606 _DBUS_ASSERT_ERROR_IS_SET (error);
4612 /** Creates the given file, failing if the file already exists.
4614 * @param filename the filename
4615 * @param error error location
4616 * @returns #TRUE if we created the file and it didn't exist
4619 _dbus_create_file_exclusively (const DBusString *filename,
4623 const char *filename_c;
4625 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4627 filename_c = _dbus_string_get_const_data (filename);
4629 if (!_dbus_file_open (&file, filename_c, O_WRONLY | O_BINARY | O_EXCL | O_CREAT,
4632 dbus_set_error (error,
4634 "Could not create file %s: %s\n",
4636 _dbus_strerror (errno));
4640 if (!_dbus_file_close (&file, NULL))
4642 dbus_set_error (error,
4644 "Could not close file %s: %s\n",
4646 _dbus_strerror (errno));
4655 * Creates a directory; succeeds if the directory
4656 * is created or already existed.
4658 * @param filename directory filename
4659 * @param error initialized error object
4660 * @returns #TRUE on success
4663 _dbus_create_directory (const DBusString *filename,
4666 const char *filename_c;
4668 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4670 filename_c = _dbus_string_get_const_data (filename);
4672 if (_dbus_mkdir (filename_c, 0700) < 0)
4674 if (errno == EEXIST)
4677 dbus_set_error (error, DBUS_ERROR_FAILED,
4678 "Failed to create directory %s: %s\n",
4679 filename_c, _dbus_strerror (errno));
4688 pseudorandom_generate_random_bytes_buffer (char *buffer,
4694 /* fall back to pseudorandom */
4695 _dbus_verbose ("Falling back to pseudorandom for %d bytes\n",
4698 _dbus_get_current_time (NULL, &tv_usec);
4708 b = (r / (double) RAND_MAX) * 255.0;
4717 pseudorandom_generate_random_bytes (DBusString *str,
4723 old_len = _dbus_string_get_length (str);
4725 if (!_dbus_string_lengthen (str, n_bytes))
4728 p = _dbus_string_get_data_len (str, old_len, n_bytes);
4730 pseudorandom_generate_random_bytes_buffer (p, n_bytes);
4736 * Gets the temporary files directory by inspecting the environment variables
4737 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
4739 * @returns location of temp directory
4742 _dbus_get_tmpdir(void)
4744 static const char* tmpdir = NULL;
4749 tmpdir = getenv("TMP");
4751 tmpdir = getenv("TEMP");
4753 tmpdir = getenv("TMPDIR");
4755 tmpdir = "C:\\Temp";
4758 _dbus_assert(tmpdir != NULL);
4765 * Deletes the given file.
4767 * @param filename the filename
4768 * @param error error location
4770 * @returns #TRUE if unlink() succeeded
4773 _dbus_delete_file (const DBusString *filename,
4776 const char *filename_c;
4778 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
4780 filename_c = _dbus_string_get_const_data (filename);
4782 if (unlink (filename_c) < 0)
4784 dbus_set_error (error, DBUS_ERROR_FAILED,
4785 "Failed to delete file %s: %s\n",
4786 filename_c, _dbus_strerror (errno));
4794 * Generates the given number of random bytes,
4795 * using the best mechanism we can come up with.
4797 * @param str the string
4798 * @param n_bytes the number of random bytes to append to string
4799 * @returns #TRUE on success, #FALSE if no memory
4802 _dbus_generate_random_bytes (DBusString *str,
4805 return pseudorandom_generate_random_bytes (str, n_bytes);
4808 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_BUILD_TESTS)
4820 * Backtrace Generator
4822 * Copyright 2004 Eric Poech
4823 * Copyright 2004 Robert Shearman
4825 * This library is free software; you can redistribute it and/or
4826 * modify it under the terms of the GNU Lesser General Public
4827 * License as published by the Free Software Foundation; either
4828 * version 2.1 of the License, or (at your option) any later version.
4830 * This library is distributed in the hope that it will be useful,
4831 * but WITHOUT ANY WARRANTY; without even the implied warranty of
4832 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4833 * Lesser General Public License for more details.
4835 * You should have received a copy of the GNU Lesser General Public
4836 * License along with this library; if not, write to the Free Software
4837 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
4841 #include <imagehlp.h>
4844 #define DPRINTF _dbus_warn
4852 //#define MAKE_FUNCPTR(f) static typeof(f) * p##f
4854 //MAKE_FUNCPTR(StackWalk);
4855 //MAKE_FUNCPTR(SymGetModuleBase);
4856 //MAKE_FUNCPTR(SymFunctionTableAccess);
4857 //MAKE_FUNCPTR(SymInitialize);
4858 //MAKE_FUNCPTR(SymGetSymFromAddr);
4859 //MAKE_FUNCPTR(SymGetModuleInfo);
4860 static BOOL (WINAPI *pStackWalk)(
4864 LPSTACKFRAME StackFrame,
4865 PVOID ContextRecord,
4866 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
4867 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
4868 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
4869 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
4871 static DWORD (WINAPI *pSymGetModuleBase)(
4875 static PVOID (WINAPI *pSymFunctionTableAccess)(
4879 static BOOL (WINAPI *pSymInitialize)(
4881 PSTR UserSearchPath,
4884 static BOOL (WINAPI *pSymGetSymFromAddr)(
4887 PDWORD Displacement,
4888 PIMAGEHLP_SYMBOL Symbol
4890 static BOOL (WINAPI *pSymGetModuleInfo)(
4893 PIMAGEHLP_MODULE ModuleInfo
4895 static DWORD (WINAPI *pSymSetOptions)(
4900 static BOOL init_backtrace()
4902 HMODULE hmodDbgHelp = LoadLibraryA("dbghelp");
4904 #define GETFUNC(x) \
4905 p##x = (typeof(x)*)GetProcAddress(hmodDbgHelp, #x); \
4913 // GETFUNC(StackWalk);
4914 // GETFUNC(SymGetModuleBase);
4915 // GETFUNC(SymFunctionTableAccess);
4916 // GETFUNC(SymInitialize);
4917 // GETFUNC(SymGetSymFromAddr);
4918 // GETFUNC(SymGetModuleInfo);
4922 pStackWalk = (BOOL (WINAPI *)(
4926 LPSTACKFRAME StackFrame,
4927 PVOID ContextRecord,
4928 PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
4929 PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
4930 PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
4931 PTRANSLATE_ADDRESS_ROUTINE TranslateAddress
4932 ))GetProcAddress (hmodDbgHelp, FUNC(StackWalk));
4933 pSymGetModuleBase=(DWORD (WINAPI *)(
4936 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleBase));
4937 pSymFunctionTableAccess=(PVOID (WINAPI *)(
4940 ))GetProcAddress (hmodDbgHelp, FUNC(SymFunctionTableAccess));
4941 pSymInitialize = (BOOL (WINAPI *)(
4943 PSTR UserSearchPath,
4945 ))GetProcAddress (hmodDbgHelp, FUNC(SymInitialize));
4946 pSymGetSymFromAddr = (BOOL (WINAPI *)(
4949 PDWORD Displacement,
4950 PIMAGEHLP_SYMBOL Symbol
4951 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetSymFromAddr));
4952 pSymGetModuleInfo = (BOOL (WINAPI *)(
4955 PIMAGEHLP_MODULE ModuleInfo
4956 ))GetProcAddress (hmodDbgHelp, FUNC(SymGetModuleInfo));
4957 pSymSetOptions = (DWORD (WINAPI *)(
4959 ))GetProcAddress (hmodDbgHelp, FUNC(SymSetOptions));
4962 pSymSetOptions(SYMOPT_UNDNAME);
4964 pSymInitialize(GetCurrentProcess(), NULL, TRUE);
4969 static void dump_backtrace_for_thread(HANDLE hThread)
4976 if (!init_backtrace())
4979 /* can't use this function for current thread as GetThreadContext
4980 * doesn't support getting context from current thread */
4981 if (hThread == GetCurrentThread())
4984 DPRINTF("Backtrace:\n");
4986 memset(&context, 0, sizeof(context));
4987 context.ContextFlags = CONTEXT_FULL;
4989 SuspendThread(hThread);
4991 if (!GetThreadContext(hThread, &context))
4993 DPRINTF("Couldn't get thread context (error %ld)\n", GetLastError());
4994 ResumeThread(hThread);
4998 memset(&sf, 0, sizeof(sf));
5001 sf.AddrFrame.Offset = context.Ebp;
5002 sf.AddrFrame.Mode = AddrModeFlat;
5003 sf.AddrPC.Offset = context.Eip;
5004 sf.AddrPC.Mode = AddrModeFlat;
5005 dwImageType = IMAGE_FILE_MACHINE_I386;
5007 # error You need to fill in the STACKFRAME structure for your architecture
5010 while (pStackWalk(dwImageType, GetCurrentProcess(),
5011 hThread, &sf, &context, NULL, pSymFunctionTableAccess,
5012 pSymGetModuleBase, NULL))
5015 IMAGEHLP_SYMBOL * pSymbol = (IMAGEHLP_SYMBOL *)buffer;
5016 DWORD dwDisplacement;
5018 pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL);
5019 pSymbol->MaxNameLength = sizeof(buffer) - sizeof(IMAGEHLP_SYMBOL) + 1;
5021 if (!pSymGetSymFromAddr(GetCurrentProcess(), sf.AddrPC.Offset,
5022 &dwDisplacement, pSymbol))
5024 IMAGEHLP_MODULE ModuleInfo;
5025 ModuleInfo.SizeOfStruct = sizeof(ModuleInfo);
5027 if (!pSymGetModuleInfo(GetCurrentProcess(), sf.AddrPC.Offset,
5029 DPRINTF("1\t%p\n", (void*)sf.AddrPC.Offset);
5031 DPRINTF("2\t%s+0x%lx\n", ModuleInfo.ImageName,
5032 sf.AddrPC.Offset - ModuleInfo.BaseOfImage);
5034 else if (dwDisplacement)
5035 DPRINTF("3\t%s+0x%lx\n", pSymbol->Name, dwDisplacement);
5037 DPRINTF("4\t%s\n", pSymbol->Name);
5040 ResumeThread(hThread);
5043 static DWORD WINAPI dump_thread_proc(LPVOID lpParameter)
5045 dump_backtrace_for_thread((HANDLE)lpParameter);
5049 /* cannot get valid context from current thread, so we have to execute
5050 * backtrace from another thread */
5051 static void dump_backtrace()
5053 HANDLE hCurrentThread;
5056 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
5057 GetCurrentProcess(), &hCurrentThread, 0, FALSE, DUPLICATE_SAME_ACCESS);
5058 hThread = CreateThread(NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
5060 WaitForSingleObject(hThread, INFINITE);
5061 CloseHandle(hThread);
5062 CloseHandle(hCurrentThread);
5065 void _dbus_print_backtrace(void)
5071 void _dbus_print_backtrace(void)
5073 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
5077 static dbus_uint32_t fromAscii(char ascii)
5079 if(ascii >= '0' && ascii <= '9')
5081 if(ascii >= 'A' && ascii <= 'F')
5082 return ascii - 'A' + 10;
5083 if(ascii >= 'a' && ascii <= 'f')
5084 return ascii - 'a' + 10;
5088 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
5089 dbus_bool_t create_if_not_found,
5096 HW_PROFILE_INFOA info;
5097 char *lpc = &info.szHwProfileGuid[0];
5100 // the hw-profile guid lives long enough
5101 if(!GetCurrentHwProfileA(&info))
5103 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
5107 // Form: {12340001-4980-1920-6788-123456789012}
5110 u = ((fromAscii(lpc[0]) << 0) |
5111 (fromAscii(lpc[1]) << 4) |
5112 (fromAscii(lpc[2]) << 8) |
5113 (fromAscii(lpc[3]) << 12) |
5114 (fromAscii(lpc[4]) << 16) |
5115 (fromAscii(lpc[5]) << 20) |
5116 (fromAscii(lpc[6]) << 24) |
5117 (fromAscii(lpc[7]) << 28));
5118 machine_id->as_uint32s[0] = u;
5122 u = ((fromAscii(lpc[0]) << 0) |
5123 (fromAscii(lpc[1]) << 4) |
5124 (fromAscii(lpc[2]) << 8) |
5125 (fromAscii(lpc[3]) << 12) |
5126 (fromAscii(lpc[5]) << 16) |
5127 (fromAscii(lpc[6]) << 20) |
5128 (fromAscii(lpc[7]) << 24) |
5129 (fromAscii(lpc[8]) << 28));
5130 machine_id->as_uint32s[1] = u;
5134 u = ((fromAscii(lpc[0]) << 0) |
5135 (fromAscii(lpc[1]) << 4) |
5136 (fromAscii(lpc[2]) << 8) |
5137 (fromAscii(lpc[3]) << 12) |
5138 (fromAscii(lpc[5]) << 16) |
5139 (fromAscii(lpc[6]) << 20) |
5140 (fromAscii(lpc[7]) << 24) |
5141 (fromAscii(lpc[8]) << 28));
5142 machine_id->as_uint32s[2] = u;
5146 u = ((fromAscii(lpc[0]) << 0) |
5147 (fromAscii(lpc[1]) << 4) |
5148 (fromAscii(lpc[2]) << 8) |
5149 (fromAscii(lpc[3]) << 12) |
5150 (fromAscii(lpc[4]) << 16) |
5151 (fromAscii(lpc[5]) << 20) |
5152 (fromAscii(lpc[6]) << 24) |
5153 (fromAscii(lpc[7]) << 28));
5154 machine_id->as_uint32s[3] = u;
5160 HANDLE _dbus_global_lock (const char *mutexname)
5165 mutex = CreateMutex( NULL, FALSE, mutexname );
5171 gotMutex = WaitForSingleObject( mutex, INFINITE );
5174 case WAIT_ABANDONED:
5175 ReleaseMutex (mutex);
5176 CloseHandle (mutex);
5187 void _dbus_global_unlock (HANDLE mutex)
5189 ReleaseMutex (mutex);
5190 CloseHandle (mutex);
5193 // for proper cleanup in dbus-daemon
5194 static HANDLE hDBusDaemonMutex = NULL;
5195 static HANDLE hDBusSharedMem = NULL;
5196 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
5197 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
5198 // sync _dbus_get_autolaunch_address
5199 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
5200 // mutex to determine if dbus-daemon is already started (per user)
5201 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
5202 // named shm for dbus adress info (per user)
5203 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
5206 _dbus_daemon_init(const char *host, dbus_uint32_t port)
5209 const char *adr = NULL;
5210 char szUserName[64];
5211 DWORD dwUserNameSize = sizeof(szUserName);
5212 char szDBusDaemonMutex[128];
5213 char szDBusDaemonAddressInfo[128];
5214 char szAddress[128];
5219 _snprintf(szAddress, sizeof(szAddress) - 1, "tcp:host=%s,port=%d", host, port);
5221 _dbus_assert( GetUserName(szUserName, &dwUserNameSize) != 0);
5222 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
5223 cDBusDaemonMutex, szUserName);
5224 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
5225 cDBusDaemonAddressInfo, szUserName);
5227 // before _dbus_global_lock to keep correct lock/release order
5228 hDBusDaemonMutex = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
5230 _dbus_assert(WaitForSingleObject( hDBusDaemonMutex, 1000 ) == WAIT_OBJECT_0);
5232 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
5233 lock = _dbus_global_lock( cUniqueDBusInitMutex );
5236 hDBusSharedMem = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
5237 0, strlen( szAddress ) + 1, szDBusDaemonAddressInfo );
5238 _dbus_assert( hDBusSharedMem );
5240 adr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
5242 _dbus_assert( adr );
5244 strcpy( (char*) adr, szAddress);
5247 UnmapViewOfFile( (char*) adr );
5249 _dbus_global_unlock( lock );
5253 _dbus_daemon_release()
5257 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
5258 lock = _dbus_global_lock( cUniqueDBusInitMutex );
5260 CloseHandle( hDBusSharedMem );
5262 hDBusSharedMem = NULL;
5264 ReleaseMutex( hDBusDaemonMutex );
5266 CloseHandle( hDBusDaemonMutex );
5268 hDBusDaemonMutex = NULL;
5270 _dbus_global_unlock( lock );
5274 _dbus_get_autolaunch_shm(DBusString *adress)
5278 char szUserName[64];
5279 DWORD dwUserNameSize = sizeof(szUserName);
5280 char szDBusDaemonAddressInfo[128];
5282 if( !GetUserName(szUserName, &dwUserNameSize) )
5284 _snprintf(szDBusDaemonAddressInfo, sizeof(szDBusDaemonAddressInfo) - 1, "%s:%s",
5285 cDBusDaemonAddressInfo, szUserName);
5289 // we know that dbus-daemon is available, so we wait until shm is available
5290 sharedMem = OpenFileMapping( FILE_MAP_READ, FALSE, szDBusDaemonAddressInfo );
5291 if( sharedMem == 0 )
5293 } while( sharedMem == 0 );
5295 if( sharedMem == 0 )
5298 adr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
5303 _dbus_string_init( adress );
5305 _dbus_string_append( adress, adr );
5308 UnmapViewOfFile( (char*) adr );
5310 CloseHandle( sharedMem );
5316 _dbus_daemon_already_runs (DBusString *adress)
5320 dbus_bool_t bRet = TRUE;
5321 char szUserName[64];
5322 DWORD dwUserNameSize = sizeof(szUserName);
5323 char szDBusDaemonMutex[128];
5325 // sync _dbus_daemon_init, _dbus_daemon_uninit and _dbus_daemon_already_runs
5326 lock = _dbus_global_lock( cUniqueDBusInitMutex );
5328 if( !GetUserName(szUserName, &dwUserNameSize) )
5330 _snprintf(szDBusDaemonMutex, sizeof(szDBusDaemonMutex) - 1, "%s:%s",
5331 cDBusDaemonMutex, szUserName);
5334 daemon = CreateMutex( NULL, FALSE, szDBusDaemonMutex );
5335 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
5337 ReleaseMutex (daemon);
5338 CloseHandle (daemon);
5340 _dbus_global_unlock( lock );
5345 bRet = _dbus_get_autolaunch_shm( adress );
5348 CloseHandle ( daemon );
5350 _dbus_global_unlock( lock );
5356 _dbus_get_autolaunch_address (DBusString *address,
5361 PROCESS_INFORMATION pi;
5362 dbus_bool_t retval = FALSE;
5364 char dbus_exe_path[MAX_PATH];
5365 char dbus_args[MAX_PATH * 2];
5367 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
5369 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
5371 if (_dbus_daemon_already_runs(address))
5373 printf("dbus daemon already exists\n");
5378 if (!SearchPathA(NULL, "dbus-daemon.exe", NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
5380 printf ("could not find dbus-daemon executable\n");
5385 ZeroMemory( &si, sizeof(si) );
5387 ZeroMemory( &pi, sizeof(pi) );
5389 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
5391 // argv[i] = "--config-file=bus\\session.conf";
5392 printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
5393 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
5397 // Wait until started (see _dbus_get_autolaunch_shm())
5398 WaitForInputIdle(pi.hProcess, INFINITE);
5400 retval = _dbus_get_autolaunch_shm( address );
5407 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
5409 _DBUS_ASSERT_ERROR_IS_SET (error);
5411 _dbus_global_unlock (mutex);
5417 /** Makes the file readable by every user in the system.
5419 * @param filename the filename
5420 * @param error error location
5421 * @returns #TRUE if the file's permissions could be changed.
5424 _dbus_make_file_world_readable(const DBusString *filename,
5432 #define DBUS_STANDARD_SESSION_SERVICEDIR "/dbus-1/services"
5436 * Returns the standard directories for a session bus to look for service
5439 * On Windows this should be data directories:
5441 * %CommonProgramFiles%/dbus
5447 * @param dirs the directory list we are returning
5448 * @returns #FALSE on OOM
5452 _dbus_get_standard_session_servicedirs (DBusList **dirs)
5454 const char *common_progs;
5455 DBusString servicedir_path;
5457 if (!_dbus_string_init (&servicedir_path))
5460 if (!_dbus_string_append (&servicedir_path, DBUS_DATADIR _DBUS_PATH_SEPARATOR))
5463 common_progs = _dbus_getenv ("CommonProgramFiles");
5465 if (common_progs != NULL)
5467 if (!_dbus_string_append (&servicedir_path, common_progs))
5470 if (!_dbus_string_append (&servicedir_path, _DBUS_PATH_SEPARATOR))
5474 if (!_dbus_split_paths_and_append (&servicedir_path,
5475 DBUS_STANDARD_SESSION_SERVICEDIR,
5479 _dbus_string_free (&servicedir_path);
5483 _dbus_string_free (&servicedir_path);
5487 _DBUS_DEFINE_GLOBAL_LOCK (atomic);
5490 * Atomically increments an integer
5492 * @param atomic pointer to the integer to increment
5493 * @returns the value before incrementing
5497 _dbus_atomic_inc (DBusAtomic *atomic)
5499 // +/- 1 is needed here!
5500 return InterlockedIncrement (&atomic->value) - 1;
5504 * Atomically decrement an integer
5506 * @param atomic pointer to the integer to decrement
5507 * @returns the value before decrementing
5511 _dbus_atomic_dec (DBusAtomic *atomic)
5513 // +/- 1 is needed here!
5514 return InterlockedDecrement (&atomic->value) + 1;
5517 #endif /* asserts or tests enabled */
5520 * Called when the bus daemon is signaled to reload its configuration; any
5521 * caches should be nuked. Of course any caches that need explicit reload
5522 * are probably broken, but c'est la vie.
5527 _dbus_flush_caches (void)
5532 dbus_bool_t _dbus_windows_user_is_process_owner (const char *windows_sid)
5538 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
5539 * for Winsock so is abstracted)
5541 * @returns #TRUE if errno == EAGAIN or errno == EWOULDBLOCK
5544 _dbus_get_is_errno_eagain_or_ewouldblock (void)
5546 return errno == EAGAIN || errno == EWOULDBLOCK;
5550 * return the absolute path of the dbus installation
5552 * @param s buffer for installation path
5553 * @param len length of buffer
5554 * @returns #FALSE on failure
5557 _dbus_get_install_root(char *s, int len)
5560 int ret = GetModuleFileName(NULL,s,len);
5562 || ret == len && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
5567 else if ((p = strstr(s,"\\bin\\")))
5580 find config file either from installation or build root according to
5581 the following path layout
5583 bin/dbus-daemon[d].exe
5584 etc/<config-file>.conf
5587 bin/dbus-daemon[d].exe
5588 bus/<config-file>.conf
5591 _dbus_get_config_file_name(DBusString *config_file, char *s)
5593 char path[MAX_PATH*2];
5594 int path_size = sizeof(path);
5596 if (!_dbus_get_install_root(path,path_size))
5599 strcat_s(path,path_size,"etc\\");
5600 strcat_s(path,path_size,s);
5601 if (_dbus_file_exists(path))
5603 // find path from executable
5604 if (!_dbus_string_append (config_file, path))
5609 if (!_dbus_get_install_root(path,path_size))
5611 strcat_s(path,path_size,"bus\\");
5612 strcat_s(path,path_size,s);
5614 if (_dbus_file_exists(path))
5616 if (!_dbus_string_append (config_file, path))
5624 * Append the absolute path of the system.conf file
5625 * (there is no system bus on Windows so this can just
5626 * return FALSE and print a warning or something)
5628 * @param str the string to append to
5629 * @returns #FALSE if no memory
5632 _dbus_append_system_config_file (DBusString *str)
5634 return _dbus_get_config_file_name(str, "system.conf");
5638 * Append the absolute path of the session.conf file.
5640 * @param str the string to append to
5641 * @returns #FALSE if no memory
5644 _dbus_append_session_config_file (DBusString *str)
5646 return _dbus_get_config_file_name(str, "session.conf");
5650 * Appends the directory in which a keyring for the given credentials
5651 * should be stored. The credentials should have either a Windows or
5652 * UNIX user in them. The directory should be an absolute path.
5654 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
5655 * be something else, since the dotfile convention is not normal on Windows.
5657 * @param directory string to append directory to
5658 * @param credentials credentials the directory should be for
5660 * @returns #FALSE on no memory
5663 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
5664 DBusCredentials *credentials)
5669 const char *homepath;
5671 _dbus_assert (credentials != NULL);
5672 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
5674 if (!_dbus_string_init (&homedir))
5677 homepath = _dbus_getenv("HOMEPATH");
5678 if (homepath != NULL && *homepath != '\0')
5680 _dbus_string_append(&homedir,homepath);
5683 #ifdef DBUS_BUILD_TESTS
5685 const char *override;
5687 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
5688 if (override != NULL && *override != '\0')
5690 _dbus_string_set_length (&homedir, 0);
5691 if (!_dbus_string_append (&homedir, override))
5694 _dbus_verbose ("Using fake homedir for testing: %s\n",
5695 _dbus_string_get_const_data (&homedir));
5699 static dbus_bool_t already_warned = FALSE;
5700 if (!already_warned)
5702 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid\n");
5703 already_warned = TRUE;
5709 _dbus_string_init_const (&dotdir, ".dbus-keyrings");
5710 if (!_dbus_concat_dir_and_file (&homedir,
5714 if (!_dbus_string_copy (&homedir, 0,
5715 directory, _dbus_string_get_length (directory))) {
5719 _dbus_string_free (&homedir);
5723 _dbus_string_free (&homedir);
5727 /** @} end of sysdeps-win */
5728 /* tests in dbus-sysdeps-util.c */