1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
3 *
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
6 * Copyright (C) 2005 Novell, Inc.
7 * Copyright (C) 2006 Peter Kümmel <syntheticpp@gmx.net>
8 * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
9 * Copyright (C) 2006-2013 Ralf Habacker <ralf.habacker@freenet.de>
10 *
11 * Licensed under the Academic Free License version 2.1
12 *
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.
17 *
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.
22 *
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 *
27 */
28
29 #include <config.h>
30
31 #define STRSAFE_NO_DEPRECATE
32
33 #ifndef DBUS_WINCE
34 #ifndef _WIN32_WINNT
35 #define _WIN32_WINNT 0x0501
36 #endif
37 #endif
38
39 #include "dbus-internals.h"
40 #include "dbus-sha.h"
41 #include "dbus-sysdeps.h"
42 #include "dbus-threads.h"
43 #include "dbus-protocol.h"
44 #include "dbus-string.h"
45 #include "dbus-sysdeps.h"
46 #include "dbus-sysdeps-win.h"
47 #include "dbus-protocol.h"
48 #include "dbus-hash.h"
49 #include "dbus-sockets-win.h"
50 #include "dbus-list.h"
51 #include "dbus-nonce.h"
52 #include "dbus-credentials.h"
53
54 #include <windows.h>
55 #include <wincrypt.h>
56 #include <iphlpapi.h>
57
58 /* Declarations missing in mingw's and windows sdk 7.0 headers */
59 extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR StringSid, PSID *Sid);
60 extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);
61
62 #include <stdio.h>
63 #include <stdlib.h>
64
65 #include <string.h>
66 #if HAVE_ERRNO_H
67 #include <errno.h>
68 #endif
69 #ifndef DBUS_WINCE
70 #include <mbstring.h>
71 #include <sys/stat.h>
72 #include <sys/types.h>
73 #endif
74
75 #ifdef HAVE_WS2TCPIP_H
76 /* getaddrinfo for Windows CE (and Windows). */
77 #include <ws2tcpip.h>
78 #endif
79
80 #ifndef O_BINARY
81 #define O_BINARY 0
82 #endif
83
84 #ifndef PROCESS_QUERY_LIMITED_INFORMATION
85 /* MinGW32 < 4 does not define this value in its headers */
86 #define PROCESS_QUERY_LIMITED_INFORMATION (0x1000)
87 #endif
88
89 typedef int socklen_t;
90
91
92 void
_dbus_win_set_errno(int err)93 _dbus_win_set_errno (int err)
94 {
95 #ifdef DBUS_WINCE
96 SetLastError (err);
97 #else
98 errno = err;
99 #endif
100 }
101
102 static BOOL is_winxp_sp3_or_lower (void);
103
104 /*
105 * _MIB_TCPROW_EX and friends are not available in system headers
106 * and are mapped to attribute identical ...OWNER_PID typedefs.
107 */
108 typedef MIB_TCPROW_OWNER_PID _MIB_TCPROW_EX;
109 typedef MIB_TCPTABLE_OWNER_PID MIB_TCPTABLE_EX;
110 typedef PMIB_TCPTABLE_OWNER_PID PMIB_TCPTABLE_EX;
111 typedef DWORD (WINAPI *ProcAllocateAndGetTcpExtTableFromStack)(PMIB_TCPTABLE_EX*,BOOL,HANDLE,DWORD,DWORD);
112 static ProcAllocateAndGetTcpExtTableFromStack lpfnAllocateAndGetTcpExTableFromStack = NULL;
113
114 /**
115 * AllocateAndGetTcpExTableFromStack() is undocumented and not exported,
116 * but is the only way to do this in older XP versions.
117 * @return true if the procedures could be loaded
118 */
119 static BOOL
load_ex_ip_helper_procedures(void)120 load_ex_ip_helper_procedures(void)
121 {
122 HMODULE hModule = LoadLibrary ("iphlpapi.dll");
123 if (hModule == NULL)
124 {
125 _dbus_verbose ("could not load iphlpapi.dll\n");
126 return FALSE;
127 }
128
129 lpfnAllocateAndGetTcpExTableFromStack = (ProcAllocateAndGetTcpExtTableFromStack)GetProcAddress (hModule, "AllocateAndGetTcpExTableFromStack");
130 if (lpfnAllocateAndGetTcpExTableFromStack == NULL)
131 {
132 _dbus_verbose ("could not find function AllocateAndGetTcpExTableFromStack in iphlpapi.dll\n");
133 return FALSE;
134 }
135 return TRUE;
136 }
137
138 /**
139 * get pid from localhost tcp connection using peer_port
140 * This function is available on WinXP >= SP3
141 * @param peer_port peers tcp port
142 * @return process id or 0 if connection has not been found
143 */
144 static dbus_pid_t
get_pid_from_extended_tcp_table(int peer_port)145 get_pid_from_extended_tcp_table(int peer_port)
146 {
147 dbus_pid_t result;
148 DWORD errorCode, size = 0, i;
149 MIB_TCPTABLE_OWNER_PID *tcp_table;
150
151 if ((errorCode =
152 GetExtendedTcpTable (NULL, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == ERROR_INSUFFICIENT_BUFFER)
153 {
154 tcp_table = (MIB_TCPTABLE_OWNER_PID *) dbus_malloc (size);
155 if (tcp_table == NULL)
156 {
157 _dbus_verbose ("Error allocating memory\n");
158 return 0;
159 }
160 }
161 else
162 {
163 _dbus_win_warn_win_error ("unexpected error returned from GetExtendedTcpTable", errorCode);
164 return 0;
165 }
166
167 if ((errorCode = GetExtendedTcpTable (tcp_table, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) != NO_ERROR)
168 {
169 _dbus_verbose ("Error fetching tcp table %d\n", (int)errorCode);
170 dbus_free (tcp_table);
171 return 0;
172 }
173
174 result = 0;
175 for (i = 0; i < tcp_table->dwNumEntries; i++)
176 {
177 MIB_TCPROW_OWNER_PID *p = &tcp_table->table[i];
178 int local_address = ntohl (p->dwLocalAddr);
179 int local_port = ntohs (p->dwLocalPort);
180 if (p->dwState == MIB_TCP_STATE_ESTAB
181 && local_address == INADDR_LOOPBACK && local_port == peer_port)
182 result = p->dwOwningPid;
183 }
184
185 dbus_free (tcp_table);
186 _dbus_verbose ("got pid %lu\n", result);
187 return result;
188 }
189
190 /**
191 * get pid from localhost tcp connection using peer_port
192 * This function is available on all WinXP versions, but
193 * not in wine (at least version <= 1.6.0)
194 * @param peer_port peers tcp port
195 * @return process id or 0 if connection has not been found
196 */
197 static dbus_pid_t
get_pid_from_tcp_ex_table(int peer_port)198 get_pid_from_tcp_ex_table(int peer_port)
199 {
200 dbus_pid_t result;
201 DWORD errorCode, i;
202 PMIB_TCPTABLE_EX tcp_table = NULL;
203
204 if (!load_ex_ip_helper_procedures ())
205 {
206 _dbus_verbose
207 ("Error not been able to load iphelper procedures\n");
208 return 0;
209 }
210
211 errorCode = lpfnAllocateAndGetTcpExTableFromStack (&tcp_table, TRUE, GetProcessHeap(), 0, 2);
212
213 if (errorCode != NO_ERROR)
214 {
215 _dbus_verbose
216 ("Error not been able to call AllocateAndGetTcpExTableFromStack()\n");
217 return 0;
218 }
219
220 result = 0;
221 for (i = 0; i < tcp_table->dwNumEntries; i++)
222 {
223 _MIB_TCPROW_EX *p = &tcp_table->table[i];
224 int local_port = ntohs (p->dwLocalPort);
225 int local_address = ntohl (p->dwLocalAddr);
226 if (local_address == INADDR_LOOPBACK && local_port == peer_port)
227 {
228 result = p->dwOwningPid;
229 break;
230 }
231 }
232
233 HeapFree (GetProcessHeap(), 0, tcp_table);
234 _dbus_verbose ("got pid %lu\n", result);
235 return result;
236 }
237
238 /**
239 * @brief return peer process id from tcp handle for localhost connections
240 * @param handle tcp socket descriptor
241 * @return process id or 0 in case the process id could not be fetched
242 */
243 static dbus_pid_t
_dbus_get_peer_pid_from_tcp_handle(int handle)244 _dbus_get_peer_pid_from_tcp_handle (int handle)
245 {
246 struct sockaddr_storage addr;
247 socklen_t len = sizeof (addr);
248 int peer_port;
249
250 dbus_pid_t result;
251 dbus_bool_t is_localhost = FALSE;
252
253 getpeername (handle, (struct sockaddr *) &addr, &len);
254
255 if (addr.ss_family == AF_INET)
256 {
257 struct sockaddr_in *s = (struct sockaddr_in *) &addr;
258 peer_port = ntohs (s->sin_port);
259 is_localhost = (ntohl (s->sin_addr.s_addr) == INADDR_LOOPBACK);
260 }
261 else if (addr.ss_family == AF_INET6)
262 {
263 _dbus_verbose ("FIXME [61922]: IPV6 support not working on windows\n");
264 return 0;
265 /*
266 struct sockaddr_in6 *s = (struct sockaddr_in6 * )&addr;
267 peer_port = ntohs (s->sin6_port);
268 is_localhost = (memcmp(s->sin6_addr.s6_addr, in6addr_loopback.s6_addr, 16) == 0);
269 _dbus_verbose ("IPV6 %08x %08x\n", s->sin6_addr.s6_addr, in6addr_loopback.s6_addr);
270 */
271 }
272 else
273 {
274 _dbus_verbose ("no idea what address family %d is\n", addr.ss_family);
275 return 0;
276 }
277
278 if (!is_localhost)
279 {
280 _dbus_verbose ("could not fetch process id from remote process\n");
281 return 0;
282 }
283
284 if (peer_port == 0)
285 {
286 _dbus_verbose
287 ("Error not been able to fetch tcp peer port from connection\n");
288 return 0;
289 }
290
291 _dbus_verbose ("trying to get peer's pid\n");
292
293 result = get_pid_from_extended_tcp_table (peer_port);
294 if (result > 0)
295 return result;
296 result = get_pid_from_tcp_ex_table (peer_port);
297 return result;
298 }
299
300 /* Convert GetLastError() to a dbus error. */
301 const char*
_dbus_win_error_from_last_error(void)302 _dbus_win_error_from_last_error (void)
303 {
304 switch (GetLastError())
305 {
306 case 0:
307 return DBUS_ERROR_FAILED;
308
309 case ERROR_NO_MORE_FILES:
310 case ERROR_TOO_MANY_OPEN_FILES:
311 return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
312
313 case ERROR_ACCESS_DENIED:
314 case ERROR_CANNOT_MAKE:
315 return DBUS_ERROR_ACCESS_DENIED;
316
317 case ERROR_NOT_ENOUGH_MEMORY:
318 return DBUS_ERROR_NO_MEMORY;
319
320 case ERROR_FILE_EXISTS:
321 return DBUS_ERROR_FILE_EXISTS;
322
323 case ERROR_FILE_NOT_FOUND:
324 case ERROR_PATH_NOT_FOUND:
325 return DBUS_ERROR_FILE_NOT_FOUND;
326
327 default:
328 return DBUS_ERROR_FAILED;
329 }
330 }
331
332
333 char*
_dbus_win_error_string(int error_number)334 _dbus_win_error_string (int error_number)
335 {
336 char *msg;
337
338 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
339 FORMAT_MESSAGE_IGNORE_INSERTS |
340 FORMAT_MESSAGE_FROM_SYSTEM,
341 NULL, error_number, 0,
342 (LPSTR) &msg, 0, NULL);
343
344 if (msg[strlen (msg) - 1] == '\n')
345 msg[strlen (msg) - 1] = '\0';
346 if (msg[strlen (msg) - 1] == '\r')
347 msg[strlen (msg) - 1] = '\0';
348
349 return msg;
350 }
351
352 void
_dbus_win_free_error_string(char * string)353 _dbus_win_free_error_string (char *string)
354 {
355 LocalFree (string);
356 }
357
358 /**
359 * Socket interface
360 *
361 */
362
363 /**
364 * Thin wrapper around the read() system call that appends
365 * the data it reads to the DBusString buffer. It appends
366 * up to the given count, and returns the same value
367 * and same errno as read(). The only exception is that
368 * _dbus_read_socket() handles EINTR for you.
369 * _dbus_read_socket() can return ENOMEM, even though
370 * regular UNIX read doesn't.
371 *
372 * @param fd the file descriptor to read from
373 * @param buffer the buffer to append data to
374 * @param count the amount of data to read
375 * @returns the number of bytes read or -1
376 */
377
378 int
_dbus_read_socket(DBusSocket fd,DBusString * buffer,int count)379 _dbus_read_socket (DBusSocket fd,
380 DBusString *buffer,
381 int count)
382 {
383 int bytes_read;
384 int start;
385 char *data;
386
387 _dbus_assert (count >= 0);
388
389 start = _dbus_string_get_length (buffer);
390
391 if (!_dbus_string_lengthen (buffer, count))
392 {
393 _dbus_win_set_errno (ENOMEM);
394 return -1;
395 }
396
397 data = _dbus_string_get_data_len (buffer, start, count);
398
399 again:
400
401 _dbus_verbose ("recv: count=%d fd=%Iu\n", count, fd.sock);
402 bytes_read = recv (fd.sock, data, count, 0);
403
404 if (bytes_read == SOCKET_ERROR)
405 {
406 DBUS_SOCKET_SET_ERRNO();
407 _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
408 bytes_read = -1;
409 }
410 else
411 _dbus_verbose ("recv: = %d\n", bytes_read);
412
413 if (bytes_read < 0)
414 {
415 if (errno == EINTR)
416 goto again;
417 else
418 {
419 /* put length back (note that this doesn't actually realloc anything) */
420 _dbus_string_set_length (buffer, start);
421 return -1;
422 }
423 }
424 else
425 {
426 /* put length back (doesn't actually realloc) */
427 _dbus_string_set_length (buffer, start + bytes_read);
428
429 #if 0
430 if (bytes_read > 0)
431 _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
432 #endif
433
434 return bytes_read;
435 }
436 }
437
438 /**
439 * Thin wrapper around the write() system call that writes a part of a
440 * DBusString and handles EINTR for you.
441 *
442 * @param fd the file descriptor to write
443 * @param buffer the buffer to write data from
444 * @param start the first byte in the buffer to write
445 * @param len the number of bytes to try to write
446 * @returns the number of bytes written or -1 on error
447 */
448 int
_dbus_write_socket(DBusSocket fd,const DBusString * buffer,int start,int len)449 _dbus_write_socket (DBusSocket fd,
450 const DBusString *buffer,
451 int start,
452 int len)
453 {
454 const char *data;
455 int bytes_written;
456
457 data = _dbus_string_get_const_data_len (buffer, start, len);
458
459 again:
460
461 _dbus_verbose ("send: len=%d fd=%Iu\n", len, fd.sock);
462 bytes_written = send (fd.sock, data, len, 0);
463
464 if (bytes_written == SOCKET_ERROR)
465 {
466 DBUS_SOCKET_SET_ERRNO();
467 _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
468 bytes_written = -1;
469 }
470 else
471 _dbus_verbose ("send: = %d\n", bytes_written);
472
473 if (bytes_written < 0 && errno == EINTR)
474 goto again;
475
476 #if 0
477 if (bytes_written > 0)
478 _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
479 #endif
480
481 return bytes_written;
482 }
483
484
485 /**
486 * Closes a file descriptor.
487 *
488 * @param fd the file descriptor
489 * @param error error object
490 * @returns #FALSE if error set
491 */
492 dbus_bool_t
_dbus_close_socket(DBusSocket fd,DBusError * error)493 _dbus_close_socket (DBusSocket fd,
494 DBusError *error)
495 {
496 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
497
498 again:
499 if (closesocket (fd.sock) == SOCKET_ERROR)
500 {
501 DBUS_SOCKET_SET_ERRNO ();
502
503 if (errno == EINTR)
504 goto again;
505
506 dbus_set_error (error, _dbus_error_from_errno (errno),
507 "Could not close socket: socket=%Iu, , %s",
508 fd.sock, _dbus_strerror_from_errno ());
509 return FALSE;
510 }
511 _dbus_verbose ("socket=%Iu, \n", fd.sock);
512
513 return TRUE;
514 }
515
516 /**
517 * Sets the file descriptor to be close
518 * on exec. Should be called for all file
519 * descriptors in D-Bus code.
520 *
521 * @param handle the Windows HANDLE (a SOCKET is also OK)
522 */
523 static void
_dbus_win_handle_set_close_on_exec(HANDLE handle)524 _dbus_win_handle_set_close_on_exec (HANDLE handle)
525 {
526 if ( !SetHandleInformation( (HANDLE) handle,
527 HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
528 0 /*disable both flags*/ ) )
529 {
530 _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
531 }
532 }
533
534 /**
535 * Sets a file descriptor to be nonblocking.
536 *
537 * @param handle the file descriptor.
538 * @param error address of error location.
539 * @returns #TRUE on success.
540 */
541 dbus_bool_t
_dbus_set_socket_nonblocking(DBusSocket handle,DBusError * error)542 _dbus_set_socket_nonblocking (DBusSocket handle,
543 DBusError *error)
544 {
545 u_long one = 1;
546
547 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
548
549 if (ioctlsocket (handle.sock, FIONBIO, &one) == SOCKET_ERROR)
550 {
551 DBUS_SOCKET_SET_ERRNO ();
552 dbus_set_error (error, _dbus_error_from_errno (errno),
553 "Failed to set socket %Iu to nonblocking: %s",
554 handle.sock, _dbus_strerror_from_errno ());
555 return FALSE;
556 }
557
558 return TRUE;
559 }
560
561
562 /**
563 * Like _dbus_write() but will use writev() if possible
564 * to write both buffers in sequence. The return value
565 * is the number of bytes written in the first buffer,
566 * plus the number written in the second. If the first
567 * buffer is written successfully and an error occurs
568 * writing the second, the number of bytes in the first
569 * is returned (i.e. the error is ignored), on systems that
570 * don't have writev. Handles EINTR for you.
571 * The second buffer may be #NULL.
572 *
573 * @param fd the file descriptor
574 * @param buffer1 first buffer
575 * @param start1 first byte to write in first buffer
576 * @param len1 number of bytes to write from first buffer
577 * @param buffer2 second buffer, or #NULL
578 * @param start2 first byte to write in second buffer
579 * @param len2 number of bytes to write in second buffer
580 * @returns total bytes written from both buffers, or -1 on error
581 */
582 int
_dbus_write_socket_two(DBusSocket fd,const DBusString * buffer1,int start1,int len1,const DBusString * buffer2,int start2,int len2)583 _dbus_write_socket_two (DBusSocket fd,
584 const DBusString *buffer1,
585 int start1,
586 int len1,
587 const DBusString *buffer2,
588 int start2,
589 int len2)
590 {
591 WSABUF vectors[2];
592 const char *data1;
593 const char *data2;
594 int rc;
595 DWORD bytes_written;
596
597 _dbus_assert (buffer1 != NULL);
598 _dbus_assert (start1 >= 0);
599 _dbus_assert (start2 >= 0);
600 _dbus_assert (len1 >= 0);
601 _dbus_assert (len2 >= 0);
602
603
604 data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);
605
606 if (buffer2 != NULL)
607 data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
608 else
609 {
610 data2 = NULL;
611 start2 = 0;
612 len2 = 0;
613 }
614
615 vectors[0].buf = (char*) data1;
616 vectors[0].len = len1;
617 vectors[1].buf = (char*) data2;
618 vectors[1].len = len2;
619
620 again:
621
622 _dbus_verbose ("WSASend: len1+2=%d+%d fd=%Iu\n", len1, len2, fd.sock);
623 rc = WSASend (fd.sock,
624 vectors,
625 data2 ? 2 : 1,
626 &bytes_written,
627 0,
628 NULL,
629 NULL);
630
631 if (rc == SOCKET_ERROR)
632 {
633 DBUS_SOCKET_SET_ERRNO ();
634 _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
635 bytes_written = (DWORD) -1;
636 }
637 else
638 _dbus_verbose ("WSASend: = %ld\n", bytes_written);
639
640 if (bytes_written == (DWORD) -1 && errno == EINTR)
641 goto again;
642
643 return bytes_written;
644 }
645
646 #if 0
647
648 /**
649 * Opens the client side of a Windows named pipe. The connection D-BUS
650 * file descriptor index is returned. It is set up as nonblocking.
651 *
652 * @param path the path to named pipe socket
653 * @param error return location for error code
654 * @returns connection D-BUS file descriptor or -1 on error
655 */
656 int
657 _dbus_connect_named_pipe (const char *path,
658 DBusError *error)
659 {
660 _dbus_assert_not_reached ("not implemented");
661 }
662
663 #endif
664
665 /**
666 * @returns #FALSE if no memory
667 */
668 dbus_bool_t
_dbus_win_startup_winsock(void)669 _dbus_win_startup_winsock (void)
670 {
671 /* Straight from MSDN, deuglified */
672
673 /* Protected by _DBUS_LOCK_sysdeps */
674 static dbus_bool_t beenhere = FALSE;
675
676 WORD wVersionRequested;
677 WSADATA wsaData;
678 int err;
679
680 if (!_DBUS_LOCK (sysdeps))
681 return FALSE;
682
683 if (beenhere)
684 goto out;
685
686 wVersionRequested = MAKEWORD (2, 0);
687
688 err = WSAStartup (wVersionRequested, &wsaData);
689 if (err != 0)
690 {
691 _dbus_assert_not_reached ("Could not initialize WinSock");
692 _dbus_abort ();
693 }
694
695 /* Confirm that the WinSock DLL supports 2.0. Note that if the DLL
696 * supports versions greater than 2.0 in addition to 2.0, it will
697 * still return 2.0 in wVersion since that is the version we
698 * requested.
699 */
700 if (LOBYTE (wsaData.wVersion) != 2 ||
701 HIBYTE (wsaData.wVersion) != 0)
702 {
703 _dbus_assert_not_reached ("No usable WinSock found");
704 _dbus_abort ();
705 }
706
707 beenhere = TRUE;
708
709 out:
710 _DBUS_UNLOCK (sysdeps);
711 return TRUE;
712 }
713
714
715
716
717
718
719
720
721
722 /************************************************************************
723
724 UTF / string code
725
726 ************************************************************************/
727
728 /**
729 * Measure the message length without terminating nul
730 */
_dbus_printf_string_upper_bound(const char * format,va_list args)731 int _dbus_printf_string_upper_bound (const char *format,
732 va_list args)
733 {
734 /* MSVCRT's vsnprintf semantics are a bit different */
735 char buf[1024];
736 int bufsize;
737 int len;
738 va_list args_copy;
739
740 bufsize = sizeof (buf);
741 DBUS_VA_COPY (args_copy, args);
742 len = _vsnprintf (buf, bufsize - 1, format, args_copy);
743 va_end (args_copy);
744
745 while (len == -1) /* try again */
746 {
747 char *p;
748
749 bufsize *= 2;
750
751 p = malloc (bufsize);
752
753 if (p == NULL)
754 return -1;
755
756 DBUS_VA_COPY (args_copy, args);
757 len = _vsnprintf (p, bufsize - 1, format, args_copy);
758 va_end (args_copy);
759 free (p);
760 }
761
762 return len;
763 }
764
765
766 /**
767 * Returns the UTF-16 form of a UTF-8 string. The result should be
768 * freed with dbus_free() when no longer needed.
769 *
770 * @param str the UTF-8 string
771 * @param error return location for error code
772 */
773 wchar_t *
_dbus_win_utf8_to_utf16(const char * str,DBusError * error)774 _dbus_win_utf8_to_utf16 (const char *str,
775 DBusError *error)
776 {
777 DBusString s;
778 int n;
779 wchar_t *retval;
780
781 _dbus_string_init_const (&s, str);
782
783 if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
784 {
785 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
786 return NULL;
787 }
788
789 n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);
790
791 if (n == 0)
792 {
793 _dbus_win_set_error_from_win_error (error, GetLastError ());
794 return NULL;
795 }
796
797 retval = dbus_new (wchar_t, n);
798
799 if (!retval)
800 {
801 _DBUS_SET_OOM (error);
802 return NULL;
803 }
804
805 if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
806 {
807 dbus_free (retval);
808 dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
809 return NULL;
810 }
811
812 return retval;
813 }
814
815 /**
816 * Returns the UTF-8 form of a UTF-16 string. The result should be
817 * freed with dbus_free() when no longer needed.
818 *
819 * @param str the UTF-16 string
820 * @param error return location for error code
821 */
822 char *
_dbus_win_utf16_to_utf8(const wchar_t * str,DBusError * error)823 _dbus_win_utf16_to_utf8 (const wchar_t *str,
824 DBusError *error)
825 {
826 int n;
827 char *retval;
828
829 n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
830
831 if (n == 0)
832 {
833 _dbus_win_set_error_from_win_error (error, GetLastError ());
834 return NULL;
835 }
836
837 retval = dbus_malloc (n);
838
839 if (!retval)
840 {
841 _DBUS_SET_OOM (error);
842 return NULL;
843 }
844
845 if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
846 {
847 dbus_free (retval);
848 dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
849 return NULL;
850 }
851
852 return retval;
853 }
854
855
856
857
858
859
860 /************************************************************************
861
862
863 ************************************************************************/
864
865 dbus_bool_t
_dbus_win_account_to_sid(const wchar_t * waccount,void ** ppsid,DBusError * error)866 _dbus_win_account_to_sid (const wchar_t *waccount,
867 void **ppsid,
868 DBusError *error)
869 {
870 dbus_bool_t retval = FALSE;
871 DWORD sid_length, wdomain_length;
872 SID_NAME_USE use;
873 wchar_t *wdomain;
874
875 *ppsid = NULL;
876
877 sid_length = 0;
878 wdomain_length = 0;
879 if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
880 NULL, &wdomain_length, &use) &&
881 GetLastError () != ERROR_INSUFFICIENT_BUFFER)
882 {
883 _dbus_win_set_error_from_win_error (error, GetLastError ());
884 return FALSE;
885 }
886
887 *ppsid = dbus_malloc (sid_length);
888 if (!*ppsid)
889 {
890 _DBUS_SET_OOM (error);
891 return FALSE;
892 }
893
894 wdomain = dbus_new (wchar_t, wdomain_length);
895 if (!wdomain)
896 {
897 _DBUS_SET_OOM (error);
898 goto out1;
899 }
900
901 if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
902 wdomain, &wdomain_length, &use))
903 {
904 _dbus_win_set_error_from_win_error (error, GetLastError ());
905 goto out2;
906 }
907
908 if (!IsValidSid ((PSID) *ppsid))
909 {
910 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
911 goto out2;
912 }
913
914 retval = TRUE;
915
916 out2:
917 dbus_free (wdomain);
918 out1:
919 if (!retval)
920 {
921 dbus_free (*ppsid);
922 *ppsid = NULL;
923 }
924
925 return retval;
926 }
927
928 /** @} end of sysdeps-win */
929
930
931 /**
932 * The only reason this is separate from _dbus_getpid() is to allow it
933 * on Windows for logging but not for other purposes.
934 *
935 * @returns process ID to put in log messages
936 */
937 unsigned long
_dbus_pid_for_log(void)938 _dbus_pid_for_log (void)
939 {
940 return _dbus_getpid ();
941 }
942
943 #ifndef DBUS_WINCE
944
945 static BOOL
is_winxp_sp3_or_lower(void)946 is_winxp_sp3_or_lower (void)
947 {
948 OSVERSIONINFOEX osvi;
949 DWORDLONG dwlConditionMask = 0;
950 int op=VER_LESS_EQUAL;
951
952 // Initialize the OSVERSIONINFOEX structure.
953
954 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
955 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
956 osvi.dwMajorVersion = 5;
957 osvi.dwMinorVersion = 1;
958 osvi.wServicePackMajor = 3;
959 osvi.wServicePackMinor = 0;
960
961 // Initialize the condition mask.
962
963 VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, op );
964 VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, op );
965 VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMAJOR, op );
966 VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMINOR, op );
967
968 // Perform the test.
969
970 return VerifyVersionInfo(
971 &osvi,
972 VER_MAJORVERSION | VER_MINORVERSION |
973 VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
974 dwlConditionMask);
975 }
976
977 /** Gets our SID
978 * @param sid points to sid buffer, need to be freed with LocalFree()
979 * @param process_id the process id for which the sid should be returned (use 0 for current process)
980 * @returns process sid
981 */
982 dbus_bool_t
_dbus_getsid(char ** sid,dbus_pid_t process_id)983 _dbus_getsid(char **sid, dbus_pid_t process_id)
984 {
985 HANDLE process_token = INVALID_HANDLE_VALUE;
986 TOKEN_USER *token_user = NULL;
987 DWORD n;
988 PSID psid;
989 int retval = FALSE;
990
991 HANDLE process_handle;
992 if (process_id == 0)
993 process_handle = GetCurrentProcess();
994 else if (is_winxp_sp3_or_lower())
995 process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process_id);
996 else
997 process_handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id);
998
999 if (!OpenProcessToken (process_handle, TOKEN_QUERY, &process_token))
1000 {
1001 _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
1002 goto failed;
1003 }
1004 if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
1005 && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
1006 || (token_user = alloca (n)) == NULL
1007 || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
1008 {
1009 _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
1010 goto failed;
1011 }
1012 psid = token_user->User.Sid;
1013 if (!IsValidSid (psid))
1014 {
1015 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
1016 goto failed;
1017 }
1018 if (!ConvertSidToStringSidA (psid, sid))
1019 {
1020 _dbus_verbose("%s invalid sid\n",__FUNCTION__);
1021 goto failed;
1022 }
1023 //okay:
1024 retval = TRUE;
1025
1026 failed:
1027 CloseHandle (process_handle);
1028 if (process_token != INVALID_HANDLE_VALUE)
1029 CloseHandle (process_token);
1030
1031 _dbus_verbose("_dbus_getsid() got '%s' and returns %d\n", *sid, retval);
1032 return retval;
1033 }
1034 #endif
1035
1036 /************************************************************************
1037
1038 pipes
1039
1040 ************************************************************************/
1041
1042 /**
1043 * Creates pair of connect sockets (as in socketpair()).
1044 * Sets both ends of the pair nonblocking.
1045 *
1046 * Marks both file descriptors as close-on-exec
1047 *
1048 * @param fd1 return location for one end
1049 * @param fd2 return location for the other end
1050 * @param blocking #TRUE if pair should be blocking
1051 * @param error error return
1052 * @returns #FALSE on failure (if error is set)
1053 */
1054 dbus_bool_t
_dbus_socketpair(DBusSocket * fd1,DBusSocket * fd2,dbus_bool_t blocking,DBusError * error)1055 _dbus_socketpair (DBusSocket *fd1,
1056 DBusSocket *fd2,
1057 dbus_bool_t blocking,
1058 DBusError *error)
1059 {
1060 SOCKET temp, socket1 = -1, socket2 = -1;
1061 struct sockaddr_in saddr;
1062 int len;
1063 u_long arg;
1064
1065 if (!_dbus_win_startup_winsock ())
1066 {
1067 _DBUS_SET_OOM (error);
1068 return FALSE;
1069 }
1070
1071 temp = socket (AF_INET, SOCK_STREAM, 0);
1072 if (temp == INVALID_SOCKET)
1073 {
1074 DBUS_SOCKET_SET_ERRNO ();
1075 goto out0;
1076 }
1077
1078 _DBUS_ZERO (saddr);
1079 saddr.sin_family = AF_INET;
1080 saddr.sin_port = 0;
1081 saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
1082
1083 if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
1084 {
1085 DBUS_SOCKET_SET_ERRNO ();
1086 goto out0;
1087 }
1088
1089 if (listen (temp, 1) == SOCKET_ERROR)
1090 {
1091 DBUS_SOCKET_SET_ERRNO ();
1092 goto out0;
1093 }
1094
1095 len = sizeof (saddr);
1096 if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
1097 {
1098 DBUS_SOCKET_SET_ERRNO ();
1099 goto out0;
1100 }
1101
1102 socket1 = socket (AF_INET, SOCK_STREAM, 0);
1103 if (socket1 == INVALID_SOCKET)
1104 {
1105 DBUS_SOCKET_SET_ERRNO ();
1106 goto out0;
1107 }
1108
1109 if (connect (socket1, (struct sockaddr *)&saddr, len) == SOCKET_ERROR)
1110 {
1111 DBUS_SOCKET_SET_ERRNO ();
1112 goto out1;
1113 }
1114
1115 socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
1116 if (socket2 == INVALID_SOCKET)
1117 {
1118 DBUS_SOCKET_SET_ERRNO ();
1119 goto out1;
1120 }
1121
1122 if (!blocking)
1123 {
1124 arg = 1;
1125 if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
1126 {
1127 DBUS_SOCKET_SET_ERRNO ();
1128 goto out2;
1129 }
1130
1131 arg = 1;
1132 if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
1133 {
1134 DBUS_SOCKET_SET_ERRNO ();
1135 goto out2;
1136 }
1137 }
1138
1139 fd1->sock = socket1;
1140 fd2->sock = socket2;
1141
1142 _dbus_verbose ("full-duplex pipe %Iu:%Iu <-> %Iu:%Iu\n",
1143 fd1->sock, socket1, fd2->sock, socket2);
1144
1145 closesocket (temp);
1146
1147 return TRUE;
1148
1149 out2:
1150 closesocket (socket2);
1151 out1:
1152 closesocket (socket1);
1153 out0:
1154 closesocket (temp);
1155
1156 dbus_set_error (error, _dbus_error_from_errno (errno),
1157 "Could not setup socket pair: %s",
1158 _dbus_strerror_from_errno ());
1159
1160 return FALSE;
1161 }
1162
1163 /**
1164 * Wrapper for poll().
1165 *
1166 * @param fds the file descriptors to poll
1167 * @param n_fds number of descriptors in the array
1168 * @param timeout_milliseconds timeout or -1 for infinite
1169 * @returns numbers of fds with revents, or <0 on error
1170 */
1171 int
_dbus_poll(DBusPollFD * fds,int n_fds,int timeout_milliseconds)1172 _dbus_poll (DBusPollFD *fds,
1173 int n_fds,
1174 int timeout_milliseconds)
1175 {
1176 #define USE_CHRIS_IMPL 0
1177
1178 #if USE_CHRIS_IMPL
1179
1180 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1181 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1182 char *msgp;
1183
1184 int ret = 0;
1185 int i;
1186 struct timeval tv;
1187 int ready;
1188
1189 #define DBUS_STACK_WSAEVENTS 256
1190 WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
1191 WSAEVENT *pEvents = NULL;
1192 if (n_fds > DBUS_STACK_WSAEVENTS)
1193 pEvents = calloc(sizeof(WSAEVENT), n_fds);
1194 else
1195 pEvents = eventsOnStack;
1196
1197
1198 #ifdef DBUS_ENABLE_VERBOSE_MODE
1199 msgp = msg;
1200 msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
1201 for (i = 0; i < n_fds; i++)
1202 {
1203 DBusPollFD *fdp = &fds[i];
1204
1205
1206 if (fdp->events & _DBUS_POLLIN)
1207 msgp += sprintf (msgp, "R:%Iu ", fdp->fd.sock);
1208
1209 if (fdp->events & _DBUS_POLLOUT)
1210 msgp += sprintf (msgp, "W:%Iu ", fdp->fd.sock);
1211
1212 msgp += sprintf (msgp, "E:%Iu\n\t", fdp->fd.sock);
1213
1214 // FIXME: more robust code for long msg
1215 // create on heap when msg[] becomes too small
1216 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1217 {
1218 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1219 }
1220 }
1221
1222 msgp += sprintf (msgp, "\n");
1223 _dbus_verbose ("%s",msg);
1224 #endif
1225 for (i = 0; i < n_fds; i++)
1226 {
1227 DBusPollFD *fdp = &fds[i];
1228 WSAEVENT ev;
1229 long lNetworkEvents = FD_OOB;
1230
1231 ev = WSACreateEvent();
1232
1233 if (fdp->events & _DBUS_POLLIN)
1234 lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;
1235
1236 if (fdp->events & _DBUS_POLLOUT)
1237 lNetworkEvents |= FD_WRITE | FD_CONNECT;
1238
1239 WSAEventSelect(fdp->fd.sock, ev, lNetworkEvents);
1240
1241 pEvents[i] = ev;
1242 }
1243
1244
1245 ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);
1246
1247 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1248 {
1249 DBUS_SOCKET_SET_ERRNO ();
1250 if (errno != WSAEWOULDBLOCK)
1251 _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
1252 ret = -1;
1253 }
1254 else if (ready == WSA_WAIT_TIMEOUT)
1255 {
1256 _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
1257 ret = 0;
1258 }
1259 else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
1260 {
1261 msgp = msg;
1262 msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);
1263
1264 for (i = 0; i < n_fds; i++)
1265 {
1266 DBusPollFD *fdp = &fds[i];
1267 WSANETWORKEVENTS ne;
1268
1269 fdp->revents = 0;
1270
1271 WSAEnumNetworkEvents(fdp->fd.sock, pEvents[i], &ne);
1272
1273 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1274 fdp->revents |= _DBUS_POLLIN;
1275
1276 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1277 fdp->revents |= _DBUS_POLLOUT;
1278
1279 if (ne.lNetworkEvents & (FD_OOB))
1280 fdp->revents |= _DBUS_POLLERR;
1281
1282 if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
1283 msgp += sprintf (msgp, "R:%Iu ", fdp->fd.sock);
1284
1285 if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
1286 msgp += sprintf (msgp, "W:%Iu ", fdp->fd.sock);
1287
1288 if (ne.lNetworkEvents & (FD_OOB))
1289 msgp += sprintf (msgp, "E:%Iu ", fdp->fd.sock);
1290
1291 msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);
1292
1293 if(ne.lNetworkEvents)
1294 ret++;
1295
1296 WSAEventSelect(fdp->fd.sock, pEvents[i], 0);
1297 }
1298
1299 msgp += sprintf (msgp, "\n");
1300 _dbus_verbose ("%s",msg);
1301 }
1302 else
1303 {
1304 _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
1305 ret = -1;
1306 }
1307
1308 for(i = 0; i < n_fds; i++)
1309 {
1310 WSACloseEvent(pEvents[i]);
1311 }
1312
1313 if (n_fds > DBUS_STACK_WSAEVENTS)
1314 free(pEvents);
1315
1316 return ret;
1317
1318 #else /* USE_CHRIS_IMPL */
1319
1320 #ifdef DBUS_ENABLE_VERBOSE_MODE
1321 #define DBUS_POLL_CHAR_BUFFER_SIZE 2000
1322 char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
1323 char *msgp;
1324 #endif
1325
1326 fd_set read_set, write_set, err_set;
1327 SOCKET max_fd = 0;
1328 int i;
1329 struct timeval tv;
1330 int ready;
1331
1332 FD_ZERO (&read_set);
1333 FD_ZERO (&write_set);
1334 FD_ZERO (&err_set);
1335
1336
1337 #ifdef DBUS_ENABLE_VERBOSE_MODE
1338 msgp = msg;
1339 msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
1340 for (i = 0; i < n_fds; i++)
1341 {
1342 DBusPollFD *fdp = &fds[i];
1343
1344
1345 if (fdp->events & _DBUS_POLLIN)
1346 msgp += sprintf (msgp, "R:%Iu ", fdp->fd.sock);
1347
1348 if (fdp->events & _DBUS_POLLOUT)
1349 msgp += sprintf (msgp, "W:%Iu ", fdp->fd.sock);
1350
1351 msgp += sprintf (msgp, "E:%Iu\n\t", fdp->fd.sock);
1352
1353 // FIXME: more robust code for long msg
1354 // create on heap when msg[] becomes too small
1355 if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
1356 {
1357 _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
1358 }
1359 }
1360
1361 msgp += sprintf (msgp, "\n");
1362 _dbus_verbose ("%s",msg);
1363 #endif
1364 for (i = 0; i < n_fds; i++)
1365 {
1366 DBusPollFD *fdp = &fds[i];
1367
1368 if (fdp->events & _DBUS_POLLIN)
1369 FD_SET (fdp->fd.sock, &read_set);
1370
1371 if (fdp->events & _DBUS_POLLOUT)
1372 FD_SET (fdp->fd.sock, &write_set);
1373
1374 FD_SET (fdp->fd.sock, &err_set);
1375
1376 max_fd = MAX (max_fd, fdp->fd.sock);
1377 }
1378
1379 // Avoid random lockups with send(), for lack of a better solution so far
1380 tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
1381 tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
1382
1383 ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1384
1385 if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
1386 {
1387 DBUS_SOCKET_SET_ERRNO ();
1388 if (errno != WSAEWOULDBLOCK)
1389 _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1390 }
1391 else if (ready == 0)
1392 _dbus_verbose ("select: = 0\n");
1393 else
1394 if (ready > 0)
1395 {
1396 #ifdef DBUS_ENABLE_VERBOSE_MODE
1397 msgp = msg;
1398 msgp += sprintf (msgp, "select: = %d:\n\t", ready);
1399
1400 for (i = 0; i < n_fds; i++)
1401 {
1402 DBusPollFD *fdp = &fds[i];
1403
1404 if (FD_ISSET (fdp->fd.sock, &read_set))
1405 msgp += sprintf (msgp, "R:%Iu ", fdp->fd.sock);
1406
1407 if (FD_ISSET (fdp->fd.sock, &write_set))
1408 msgp += sprintf (msgp, "W:%Iu ", fdp->fd.sock);
1409
1410 if (FD_ISSET (fdp->fd.sock, &err_set))
1411 msgp += sprintf (msgp, "E:%Iu\n\t", fdp->fd.sock);
1412 }
1413 msgp += sprintf (msgp, "\n");
1414 _dbus_verbose ("%s",msg);
1415 #endif
1416
1417 for (i = 0; i < n_fds; i++)
1418 {
1419 DBusPollFD *fdp = &fds[i];
1420
1421 fdp->revents = 0;
1422
1423 if (FD_ISSET (fdp->fd.sock, &read_set))
1424 fdp->revents |= _DBUS_POLLIN;
1425
1426 if (FD_ISSET (fdp->fd.sock, &write_set))
1427 fdp->revents |= _DBUS_POLLOUT;
1428
1429 if (FD_ISSET (fdp->fd.sock, &err_set))
1430 fdp->revents |= _DBUS_POLLERR;
1431 }
1432 }
1433 return ready;
1434 #endif /* USE_CHRIS_IMPL */
1435 }
1436
1437
1438
1439
1440 /******************************************************************************
1441
1442 Original CVS version of dbus-sysdeps.c
1443
1444 ******************************************************************************/
1445 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1446 /* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
1447 *
1448 * Copyright (C) 2002, 2003 Red Hat, Inc.
1449 * Copyright (C) 2003 CodeFactory AB
1450 * Copyright (C) 2005 Novell, Inc.
1451 *
1452 * Licensed under the Academic Free License version 2.1
1453 *
1454 * This program is free software; you can redistribute it and/or modify
1455 * it under the terms of the GNU General Public License as published by
1456 * the Free Software Foundation; either version 2 of the License, or
1457 * (at your option) any later version.
1458 *
1459 * This program is distributed in the hope that it will be useful,
1460 * but WITHOUT ANY WARRANTY; without even the implied warranty of
1461 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1462 * GNU General Public License for more details.
1463 *
1464 * You should have received a copy of the GNU General Public License
1465 * along with this program; if not, write to the Free Software
1466 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1467 *
1468 */
1469
1470
1471 /**
1472 * Exit the process, returning the given value.
1473 *
1474 * @param code the exit code
1475 */
1476 void
_dbus_exit(int code)1477 _dbus_exit (int code)
1478 {
1479 _exit (code);
1480 }
1481
1482 /**
1483 * Creates a socket and connects to a socket at the given host
1484 * and port. The connection fd is returned, and is set up as
1485 * nonblocking.
1486 *
1487 * @param host the host name to connect to
1488 * @param port the port to connect to
1489 * @param family the address family to listen on, NULL for all
1490 * @param error return location for error code
1491 * @returns connection file descriptor or -1 on error
1492 */
1493 DBusSocket
_dbus_connect_tcp_socket(const char * host,const char * port,const char * family,DBusError * error)1494 _dbus_connect_tcp_socket (const char *host,
1495 const char *port,
1496 const char *family,
1497 DBusError *error)
1498 {
1499 return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
1500 }
1501
1502 DBusSocket
_dbus_connect_tcp_socket_with_nonce(const char * host,const char * port,const char * family,const char * noncefile,DBusError * error)1503 _dbus_connect_tcp_socket_with_nonce (const char *host,
1504 const char *port,
1505 const char *family,
1506 const char *noncefile,
1507 DBusError *error)
1508 {
1509 DBusSocket fd = DBUS_SOCKET_INIT;
1510 int res;
1511 struct addrinfo hints;
1512 struct addrinfo *ai, *tmp;
1513
1514 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1515
1516 if (!_dbus_win_startup_winsock ())
1517 {
1518 _DBUS_SET_OOM (error);
1519 return _dbus_socket_get_invalid ();
1520 }
1521
1522 _DBUS_ZERO (hints);
1523
1524 if (!family)
1525 hints.ai_family = AF_UNSPEC;
1526 else if (!strcmp(family, "ipv4"))
1527 hints.ai_family = AF_INET;
1528 else if (!strcmp(family, "ipv6"))
1529 hints.ai_family = AF_INET6;
1530 else
1531 {
1532 dbus_set_error (error,
1533 DBUS_ERROR_INVALID_ARGS,
1534 "Unknown address family %s", family);
1535 return _dbus_socket_get_invalid ();
1536 }
1537 hints.ai_protocol = IPPROTO_TCP;
1538 hints.ai_socktype = SOCK_STREAM;
1539 #ifdef AI_ADDRCONFIG
1540 hints.ai_flags = AI_ADDRCONFIG;
1541 #else
1542 hints.ai_flags = 0;
1543 #endif
1544
1545 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1546 {
1547 dbus_set_error (error,
1548 _dbus_error_from_errno (res),
1549 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1550 host, port, _dbus_strerror(res), res);
1551 return _dbus_socket_get_invalid ();
1552 }
1553
1554 tmp = ai;
1555 while (tmp)
1556 {
1557 if ((fd.sock = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1558 {
1559 DBUS_SOCKET_SET_ERRNO ();
1560 dbus_set_error (error,
1561 _dbus_error_from_errno (errno),
1562 "Failed to open socket: %s",
1563 _dbus_strerror_from_errno ());
1564 freeaddrinfo(ai);
1565 return _dbus_socket_get_invalid ();
1566 }
1567 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1568
1569 if (connect (fd.sock, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1570 {
1571 DBUS_SOCKET_SET_ERRNO ();
1572 closesocket(fd.sock);
1573 fd.sock = INVALID_SOCKET;
1574 tmp = tmp->ai_next;
1575 continue;
1576 }
1577
1578 break;
1579 }
1580 freeaddrinfo(ai);
1581
1582 if (!_dbus_socket_is_valid (fd))
1583 {
1584 dbus_set_error (error,
1585 _dbus_error_from_errno (errno),
1586 "Failed to connect to socket \"%s:%s\" %s",
1587 host, port, _dbus_strerror_from_errno ());
1588 return _dbus_socket_get_invalid ();
1589 }
1590
1591 if (noncefile != NULL)
1592 {
1593 DBusString noncefileStr;
1594 dbus_bool_t ret;
1595 if (!_dbus_string_init (&noncefileStr) ||
1596 !_dbus_string_append(&noncefileStr, noncefile))
1597 {
1598 closesocket (fd.sock);
1599 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1600 return _dbus_socket_get_invalid ();
1601 }
1602
1603 ret = _dbus_send_nonce (fd, &noncefileStr, error);
1604
1605 _dbus_string_free (&noncefileStr);
1606
1607 if (!ret)
1608 {
1609 closesocket (fd.sock);
1610 return _dbus_socket_get_invalid ();
1611 }
1612 }
1613
1614 /* Every SOCKET is also a HANDLE. */
1615 _dbus_win_handle_set_close_on_exec ((HANDLE) fd.sock);
1616
1617 if (!_dbus_set_socket_nonblocking (fd, error))
1618 {
1619 closesocket (fd.sock);
1620 return _dbus_socket_get_invalid ();
1621 }
1622
1623 return fd;
1624 }
1625
1626 /**
1627 * Creates a socket and binds it to the given path, then listens on
1628 * the socket. The socket is set to be nonblocking. In case of port=0
1629 * a random free port is used and returned in the port parameter.
1630 * If inaddr_any is specified, the hostname is ignored.
1631 *
1632 * @param host the host name to listen on
1633 * @param port the port to listen on, if zero a free port will be used
1634 * @param family the address family to listen on, NULL for all
1635 * @param retport string to return the actual port listened on
1636 * @param fds_p location to store returned file descriptors
1637 * @param error return location for errors
1638 * @returns the number of listening file descriptors or -1 on error
1639 */
1640
1641 int
_dbus_listen_tcp_socket(const char * host,const char * port,const char * family,DBusString * retport,DBusSocket ** fds_p,DBusError * error)1642 _dbus_listen_tcp_socket (const char *host,
1643 const char *port,
1644 const char *family,
1645 DBusString *retport,
1646 DBusSocket **fds_p,
1647 DBusError *error)
1648 {
1649 DBusSocket *listen_fd = NULL;
1650 int nlisten_fd = 0, res, i, port_num = -1;
1651 struct addrinfo hints;
1652 struct addrinfo *ai, *tmp;
1653
1654 // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
1655 //That's required for family == IPv6(which is the default on Vista if family is not given)
1656 //So we use our own union instead of sockaddr_gen:
1657
1658 typedef union {
1659 struct sockaddr Address;
1660 struct sockaddr_in AddressIn;
1661 struct sockaddr_in6 AddressIn6;
1662 } mysockaddr_gen;
1663
1664 *fds_p = NULL;
1665 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1666
1667 if (!_dbus_win_startup_winsock ())
1668 {
1669 _DBUS_SET_OOM (error);
1670 return -1;
1671 }
1672
1673 _DBUS_ZERO (hints);
1674
1675 if (!family)
1676 hints.ai_family = AF_INET;
1677 else if (!strcmp(family, "ipv4"))
1678 hints.ai_family = AF_INET;
1679 else if (!strcmp(family, "ipv6"))
1680 hints.ai_family = AF_INET6;
1681 else
1682 {
1683 dbus_set_error (error,
1684 DBUS_ERROR_INVALID_ARGS,
1685 "Unknown address family %s", family);
1686 return -1;
1687 }
1688
1689 hints.ai_protocol = IPPROTO_TCP;
1690 hints.ai_socktype = SOCK_STREAM;
1691 #ifdef AI_ADDRCONFIG
1692 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1693 #else
1694 hints.ai_flags = AI_PASSIVE;
1695 #endif
1696
1697 redo_lookup_with_port:
1698 if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1699 {
1700 dbus_set_error (error,
1701 _dbus_error_from_errno (res),
1702 "Failed to lookup host/port: \"%s:%s\": %s (%d)",
1703 host ? host : "*", port, _dbus_strerror(res), res);
1704 return -1;
1705 }
1706
1707 tmp = ai;
1708 while (tmp)
1709 {
1710 DBusSocket fd = DBUS_SOCKET_INIT, *newlisten_fd;
1711 if ((fd.sock = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1712 {
1713 DBUS_SOCKET_SET_ERRNO ();
1714 dbus_set_error (error,
1715 _dbus_error_from_errno (errno),
1716 "Failed to open socket: %s",
1717 _dbus_strerror_from_errno ());
1718 goto failed;
1719 }
1720 _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1721
1722 if (bind (fd.sock, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1723 {
1724 DBUS_SOCKET_SET_ERRNO ();
1725 closesocket (fd.sock);
1726 if (errno == WSAEADDRINUSE)
1727 {
1728 /* Calling this function with port=0 tries to
1729 * bind the same port twice, so we should
1730 * ignore the second bind.
1731 */
1732 tmp = tmp->ai_next;
1733 continue;
1734 }
1735 dbus_set_error (error, _dbus_error_from_errno (errno),
1736 "Failed to bind socket \"%s:%s\": %s",
1737 host ? host : "*", port, _dbus_strerror_from_errno ());
1738 goto failed;
1739 }
1740
1741 if (listen (fd.sock, 30 /* backlog */) == SOCKET_ERROR)
1742 {
1743 DBUS_SOCKET_SET_ERRNO ();
1744 dbus_set_error (error, _dbus_error_from_errno (errno),
1745 "Failed to listen on socket \"%s:%s\": %s",
1746 host ? host : "*", port, _dbus_strerror_from_errno ());
1747 closesocket (fd.sock);
1748 goto failed;
1749 }
1750
1751 newlisten_fd = dbus_realloc(listen_fd, sizeof(DBusSocket)*(nlisten_fd+1));
1752 if (!newlisten_fd)
1753 {
1754 closesocket (fd.sock);
1755 dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
1756 "Failed to allocate file handle array");
1757 goto failed;
1758 }
1759 listen_fd = newlisten_fd;
1760 listen_fd[nlisten_fd] = fd;
1761 nlisten_fd++;
1762
1763 if (!_dbus_string_get_length(retport))
1764 {
1765 /* If the user didn't specify a port, or used 0, then
1766 the kernel chooses a port. After the first address
1767 is bound to, we need to force all remaining addresses
1768 to use the same port */
1769 if (!port || !strcmp(port, "0"))
1770 {
1771 mysockaddr_gen addr;
1772 socklen_t addrlen = sizeof(addr);
1773 char portbuf[NI_MAXSERV];
1774
1775 if (getsockname(fd.sock, &addr.Address, &addrlen) == SOCKET_ERROR ||
1776 (res = getnameinfo (&addr.Address, addrlen, NULL, 0,
1777 portbuf, sizeof(portbuf),
1778 NI_NUMERICSERV)) != 0)
1779 {
1780 DBUS_SOCKET_SET_ERRNO ();
1781 dbus_set_error (error, _dbus_error_from_errno (errno),
1782 "Failed to resolve port \"%s:%s\": %s",
1783 host ? host : "*", port, _dbus_strerror_from_errno());
1784 goto failed;
1785 }
1786 if (!_dbus_string_append(retport, portbuf))
1787 {
1788 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1789 goto failed;
1790 }
1791
1792 /* Release current address list & redo lookup */
1793 port = _dbus_string_get_const_data(retport);
1794 freeaddrinfo(ai);
1795 goto redo_lookup_with_port;
1796 }
1797 else
1798 {
1799 if (!_dbus_string_append(retport, port))
1800 {
1801 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1802 goto failed;
1803 }
1804 }
1805 }
1806
1807 tmp = tmp->ai_next;
1808 }
1809 freeaddrinfo(ai);
1810 ai = NULL;
1811
1812 if (!nlisten_fd)
1813 {
1814 _dbus_win_set_errno (WSAEADDRINUSE);
1815 dbus_set_error (error, _dbus_error_from_errno (errno),
1816 "Failed to bind socket \"%s:%s\": %s",
1817 host ? host : "*", port, _dbus_strerror_from_errno ());
1818 return -1;
1819 }
1820
1821 sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1822
1823 for (i = 0 ; i < nlisten_fd ; i++)
1824 {
1825 _dbus_win_handle_set_close_on_exec ((HANDLE) listen_fd[i].sock);
1826 if (!_dbus_set_socket_nonblocking (listen_fd[i], error))
1827 {
1828 goto failed;
1829 }
1830 }
1831
1832 *fds_p = listen_fd;
1833
1834 return nlisten_fd;
1835
1836 failed:
1837 if (ai)
1838 freeaddrinfo(ai);
1839 for (i = 0 ; i < nlisten_fd ; i++)
1840 closesocket (listen_fd[i].sock);
1841 dbus_free(listen_fd);
1842 return -1;
1843 }
1844
1845
1846 /**
1847 * Accepts a connection on a listening socket.
1848 * Handles EINTR for you.
1849 *
1850 * @param listen_fd the listen file descriptor
1851 * @returns the connection fd of the client, or -1 on error
1852 */
1853 DBusSocket
_dbus_accept(DBusSocket listen_fd)1854 _dbus_accept (DBusSocket listen_fd)
1855 {
1856 DBusSocket client_fd;
1857
1858 retry:
1859 client_fd.sock = accept (listen_fd.sock, NULL, NULL);
1860
1861 if (!_dbus_socket_is_valid (client_fd))
1862 {
1863 DBUS_SOCKET_SET_ERRNO ();
1864 if (errno == EINTR)
1865 goto retry;
1866 }
1867
1868 _dbus_verbose ("client fd %Iu accepted\n", client_fd.sock);
1869
1870 return client_fd;
1871 }
1872
1873
1874
1875
1876 dbus_bool_t
_dbus_send_credentials_socket(DBusSocket handle,DBusError * error)1877 _dbus_send_credentials_socket (DBusSocket handle,
1878 DBusError *error)
1879 {
1880 /* FIXME: for the session bus credentials shouldn't matter (?), but
1881 * for the system bus they are presumably essential. A rough outline
1882 * of a way to implement the credential transfer would be this:
1883 *
1884 * client waits to *read* a byte.
1885 *
1886 * server creates a named pipe with a random name, sends a byte
1887 * contining its length, and its name.
1888 *
1889 * client reads the name, connects to it (using Win32 API).
1890 *
1891 * server waits for connection to the named pipe, then calls
1892 * ImpersonateNamedPipeClient(), notes its now-current credentials,
1893 * calls RevertToSelf(), closes its handles to the named pipe, and
1894 * is done. (Maybe there is some other way to get the SID of a named
1895 * pipe client without having to use impersonation?)
1896 *
1897 * client closes its handles and is done.
1898 *
1899 * Ralf: Why not sending credentials over the given this connection ?
1900 * Using named pipes makes it impossible to be connected from a unix client.
1901 *
1902 */
1903 int bytes_written;
1904 DBusString buf;
1905
1906 _dbus_string_init_const_len (&buf, "\0", 1);
1907 again:
1908 bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1909
1910 if (bytes_written < 0 && errno == EINTR)
1911 goto again;
1912
1913 if (bytes_written < 0)
1914 {
1915 dbus_set_error (error, _dbus_error_from_errno (errno),
1916 "Failed to write credentials byte: %s",
1917 _dbus_strerror_from_errno ());
1918 return FALSE;
1919 }
1920 else if (bytes_written == 0)
1921 {
1922 dbus_set_error (error, DBUS_ERROR_IO_ERROR,
1923 "wrote zero bytes writing credentials byte");
1924 return FALSE;
1925 }
1926 else
1927 {
1928 _dbus_assert (bytes_written == 1);
1929 _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
1930 return TRUE;
1931 }
1932 return TRUE;
1933 }
1934
1935 /**
1936 * Reads a single byte which must be nul (an error occurs otherwise),
1937 * and reads unix credentials if available. Fills in pid/uid/gid with
1938 * -1 if no credentials are available. Return value indicates whether
1939 * a byte was read, not whether we got valid credentials. On some
1940 * systems, such as Linux, reading/writing the byte isn't actually
1941 * required, but we do it anyway just to avoid multiple codepaths.
1942 *
1943 * Fails if no byte is available, so you must select() first.
1944 *
1945 * The point of the byte is that on some systems we have to
1946 * use sendmsg()/recvmsg() to transmit credentials.
1947 *
1948 * @param handle the client file descriptor
1949 * @param credentials struct to fill with credentials of client
1950 * @param error location to store error code
1951 * @returns #TRUE on success
1952 */
1953 dbus_bool_t
_dbus_read_credentials_socket(DBusSocket handle,DBusCredentials * credentials,DBusError * error)1954 _dbus_read_credentials_socket (DBusSocket handle,
1955 DBusCredentials *credentials,
1956 DBusError *error)
1957 {
1958 int bytes_read = 0;
1959 DBusString buf;
1960
1961 char *sid = NULL;
1962 dbus_pid_t pid;
1963 int retval = FALSE;
1964
1965 // could fail due too OOM
1966 if (_dbus_string_init (&buf))
1967 {
1968 bytes_read = _dbus_read_socket (handle, &buf, 1 );
1969
1970 if (bytes_read > 0)
1971 _dbus_verbose ("got one zero byte from server\n");
1972
1973 _dbus_string_free (&buf);
1974 }
1975
1976 pid = _dbus_get_peer_pid_from_tcp_handle (handle.sock);
1977 if (pid == 0)
1978 return TRUE;
1979
1980 _dbus_credentials_add_pid (credentials, pid);
1981
1982 if (_dbus_getsid (&sid, pid))
1983 {
1984 if (!_dbus_credentials_add_windows_sid (credentials, sid))
1985 goto out;
1986 }
1987
1988 retval = TRUE;
1989
1990 out:
1991 if (sid)
1992 LocalFree (sid);
1993
1994 return retval;
1995 }
1996
1997 /**
1998 * Checks to make sure the given directory is
1999 * private to the user
2000 *
2001 * @param dir the name of the directory
2002 * @param error error return
2003 * @returns #FALSE on failure
2004 **/
2005 dbus_bool_t
_dbus_check_dir_is_private_to_user(DBusString * dir,DBusError * error)2006 _dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
2007 {
2008 /* TODO */
2009 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2010 return TRUE;
2011 }
2012
2013
2014 /**
2015 * Appends the given filename to the given directory.
2016 *
2017 * @todo it might be cute to collapse multiple '/' such as "foo//"
2018 * concat "//bar"
2019 *
2020 * @param dir the directory name
2021 * @param next_component the filename
2022 * @returns #TRUE on success
2023 */
2024 dbus_bool_t
_dbus_concat_dir_and_file(DBusString * dir,const DBusString * next_component)2025 _dbus_concat_dir_and_file (DBusString *dir,
2026 const DBusString *next_component)
2027 {
2028 dbus_bool_t dir_ends_in_slash;
2029 dbus_bool_t file_starts_with_slash;
2030
2031 if (_dbus_string_get_length (dir) == 0 ||
2032 _dbus_string_get_length (next_component) == 0)
2033 return TRUE;
2034
2035 dir_ends_in_slash =
2036 ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
2037 '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));
2038
2039 file_starts_with_slash =
2040 ('/' == _dbus_string_get_byte (next_component, 0) ||
2041 '\\' == _dbus_string_get_byte (next_component, 0));
2042
2043 if (dir_ends_in_slash && file_starts_with_slash)
2044 {
2045 _dbus_string_shorten (dir, 1);
2046 }
2047 else if (!(dir_ends_in_slash || file_starts_with_slash))
2048 {
2049 if (!_dbus_string_append_byte (dir, '\\'))
2050 return FALSE;
2051 }
2052
2053 return _dbus_string_copy (next_component, 0, dir,
2054 _dbus_string_get_length (dir));
2055 }
2056
2057 /*---------------- DBusCredentials ----------------------------------*/
2058
2059 /**
2060 * Adds the credentials corresponding to the given username.
2061 *
2062 * @param credentials credentials to fill in
2063 * @param username the username
2064 * @returns #TRUE if the username existed and we got some credentials
2065 */
2066 dbus_bool_t
_dbus_credentials_add_from_user(DBusCredentials * credentials,const DBusString * username)2067 _dbus_credentials_add_from_user (DBusCredentials *credentials,
2068 const DBusString *username)
2069 {
2070 return _dbus_credentials_add_windows_sid (credentials,
2071 _dbus_string_get_const_data(username));
2072 }
2073
2074 /**
2075 * Adds the credentials of the current process to the
2076 * passed-in credentials object.
2077 *
2078 * @param credentials credentials to add to
2079 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
2080 */
2081
2082 dbus_bool_t
_dbus_credentials_add_from_current_process(DBusCredentials * credentials)2083 _dbus_credentials_add_from_current_process (DBusCredentials *credentials)
2084 {
2085 dbus_bool_t retval = FALSE;
2086 char *sid = NULL;
2087
2088 if (!_dbus_getsid(&sid, _dbus_getpid()))
2089 goto failed;
2090
2091 if (!_dbus_credentials_add_pid (credentials, _dbus_getpid()))
2092 goto failed;
2093
2094 if (!_dbus_credentials_add_windows_sid (credentials,sid))
2095 goto failed;
2096
2097 retval = TRUE;
2098 goto end;
2099 failed:
2100 retval = FALSE;
2101 end:
2102 if (sid)
2103 LocalFree(sid);
2104
2105 return retval;
2106 }
2107
2108 /**
2109 * Append to the string the identity we would like to have when we
2110 * authenticate, on UNIX this is the current process UID and on
2111 * Windows something else, probably a Windows SID string. No escaping
2112 * is required, that is done in dbus-auth.c. The username here
2113 * need not be anything human-readable, it can be the machine-readable
2114 * form i.e. a user id.
2115 *
2116 * @param str the string to append to
2117 * @returns #FALSE on no memory
2118 * @todo to which class belongs this
2119 */
2120 dbus_bool_t
_dbus_append_user_from_current_process(DBusString * str)2121 _dbus_append_user_from_current_process (DBusString *str)
2122 {
2123 dbus_bool_t retval = FALSE;
2124 char *sid = NULL;
2125
2126 if (!_dbus_getsid(&sid, _dbus_getpid()))
2127 return FALSE;
2128
2129 retval = _dbus_string_append (str,sid);
2130
2131 LocalFree(sid);
2132 return retval;
2133 }
2134
2135 /**
2136 * Gets our process ID
2137 * @returns process ID
2138 */
2139 dbus_pid_t
_dbus_getpid(void)2140 _dbus_getpid (void)
2141 {
2142 return GetCurrentProcessId ();
2143 }
2144
2145 /** Gets our Unix UID
2146 * @returns on Windows, just DBUS_UID_UNSET
2147 */
2148 dbus_uid_t
_dbus_getuid(void)2149 _dbus_getuid (void)
2150 {
2151 return DBUS_UID_UNSET;
2152 }
2153
2154 /** nanoseconds in a second */
2155 #define NANOSECONDS_PER_SECOND 1000000000
2156 /** microseconds in a second */
2157 #define MICROSECONDS_PER_SECOND 1000000
2158 /** milliseconds in a second */
2159 #define MILLISECONDS_PER_SECOND 1000
2160 /** nanoseconds in a millisecond */
2161 #define NANOSECONDS_PER_MILLISECOND 1000000
2162 /** microseconds in a millisecond */
2163 #define MICROSECONDS_PER_MILLISECOND 1000
2164
2165 /**
2166 * Sleeps the given number of milliseconds.
2167 * @param milliseconds number of milliseconds
2168 */
2169 void
_dbus_sleep_milliseconds(int milliseconds)2170 _dbus_sleep_milliseconds (int milliseconds)
2171 {
2172 Sleep (milliseconds);
2173 }
2174
2175
2176 /**
2177 * Get current time, as in gettimeofday(). Never uses the monotonic
2178 * clock.
2179 *
2180 * @param tv_sec return location for number of seconds
2181 * @param tv_usec return location for number of microseconds
2182 */
2183 void
_dbus_get_real_time(long * tv_sec,long * tv_usec)2184 _dbus_get_real_time (long *tv_sec,
2185 long *tv_usec)
2186 {
2187 FILETIME ft;
2188 dbus_uint64_t time64;
2189
2190 GetSystemTimeAsFileTime (&ft);
2191
2192 memcpy (&time64, &ft, sizeof (time64));
2193
2194 /* Convert from 100s of nanoseconds since 1601-01-01
2195 * to Unix epoch. Yes, this is Y2038 unsafe.
2196 */
2197 time64 -= DBUS_INT64_CONSTANT (116444736000000000);
2198 time64 /= 10;
2199
2200 if (tv_sec)
2201 *tv_sec = time64 / 1000000;
2202
2203 if (tv_usec)
2204 *tv_usec = time64 % 1000000;
2205 }
2206
2207 /**
2208 * Get current time, as in gettimeofday(). Use the monotonic clock if
2209 * available, to avoid problems when the system time changes.
2210 *
2211 * @param tv_sec return location for number of seconds
2212 * @param tv_usec return location for number of microseconds
2213 */
2214 void
_dbus_get_monotonic_time(long * tv_sec,long * tv_usec)2215 _dbus_get_monotonic_time (long *tv_sec,
2216 long *tv_usec)
2217 {
2218 /* no implementation yet, fall back to wall-clock time */
2219 _dbus_get_real_time (tv_sec, tv_usec);
2220 }
2221
2222 /**
2223 * signal (SIGPIPE, SIG_IGN);
2224 */
2225 void
_dbus_disable_sigpipe(void)2226 _dbus_disable_sigpipe (void)
2227 {
2228 }
2229
2230 /**
2231 * Creates a directory. Unlike _dbus_ensure_directory(), this only succeeds
2232 * if the directory is genuinely newly-created.
2233 *
2234 * @param filename directory filename
2235 * @param error initialized error object
2236 * @returns #TRUE on success
2237 */
2238 dbus_bool_t
_dbus_create_directory(const DBusString * filename,DBusError * error)2239 _dbus_create_directory (const DBusString *filename,
2240 DBusError *error)
2241 {
2242 const char *filename_c;
2243
2244 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2245
2246 filename_c = _dbus_string_get_const_data (filename);
2247
2248 if (!CreateDirectoryA (filename_c, NULL))
2249 {
2250 dbus_set_error (error, DBUS_ERROR_FAILED,
2251 "Failed to create directory %s: %s\n",
2252 filename_c, _dbus_strerror_from_errno ());
2253 return FALSE;
2254 }
2255 else
2256 return TRUE;
2257 }
2258
2259 /**
2260 * Creates a directory; succeeds if the directory
2261 * is created or already existed.
2262 *
2263 * @param filename directory filename
2264 * @param error initialized error object
2265 * @returns #TRUE on success
2266 */
2267 dbus_bool_t
_dbus_ensure_directory(const DBusString * filename,DBusError * error)2268 _dbus_ensure_directory (const DBusString *filename,
2269 DBusError *error)
2270 {
2271 const char *filename_c;
2272
2273 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2274
2275 filename_c = _dbus_string_get_const_data (filename);
2276
2277 if (!CreateDirectoryA (filename_c, NULL))
2278 {
2279 if (GetLastError () == ERROR_ALREADY_EXISTS)
2280 return TRUE;
2281
2282 dbus_set_error (error, DBUS_ERROR_FAILED,
2283 "Failed to create directory %s: %s\n",
2284 filename_c, _dbus_strerror_from_errno ());
2285 return FALSE;
2286 }
2287 else
2288 return TRUE;
2289 }
2290
2291
2292 /**
2293 * Generates the given number of random bytes,
2294 * using the best mechanism we can come up with.
2295 *
2296 * @param str the string
2297 * @param n_bytes the number of random bytes to append to string
2298 * @param error location to store reason for failure
2299 * @returns #TRUE on success
2300 */
2301 dbus_bool_t
_dbus_generate_random_bytes(DBusString * str,int n_bytes,DBusError * error)2302 _dbus_generate_random_bytes (DBusString *str,
2303 int n_bytes,
2304 DBusError *error)
2305 {
2306 int old_len;
2307 unsigned char *p;
2308 HCRYPTPROV hprov;
2309
2310 old_len = _dbus_string_get_length (str);
2311
2312 if (!_dbus_string_lengthen (str, n_bytes))
2313 {
2314 _DBUS_SET_OOM (error);
2315 return FALSE;
2316 }
2317
2318 p = _dbus_string_get_udata_len (str, old_len, n_bytes);
2319
2320 if (!CryptAcquireContext (&hprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
2321 {
2322 _DBUS_SET_OOM (error);
2323 return FALSE;
2324 }
2325
2326 if (!CryptGenRandom (hprov, n_bytes, p))
2327 {
2328 _DBUS_SET_OOM (error);
2329 CryptReleaseContext (hprov, 0);
2330 return FALSE;
2331 }
2332
2333 CryptReleaseContext (hprov, 0);
2334
2335 return TRUE;
2336 }
2337
2338 /**
2339 * Gets the temporary files directory by inspecting the environment variables
2340 * TMPDIR, TMP, and TEMP in that order. If none of those are set "/tmp" is returned
2341 *
2342 * @returns location of temp directory, or #NULL if no memory for locking
2343 */
2344 const char*
_dbus_get_tmpdir(void)2345 _dbus_get_tmpdir(void)
2346 {
2347 /* Protected by _DBUS_LOCK_sysdeps */
2348 static const char* tmpdir = NULL;
2349 static char buf[1000];
2350
2351 if (!_DBUS_LOCK (sysdeps))
2352 return NULL;
2353
2354 if (tmpdir == NULL)
2355 {
2356 unsigned char *last_slash;
2357 unsigned char *p = (unsigned char *)buf;
2358
2359 if (!GetTempPathA (sizeof (buf), buf))
2360 {
2361 _dbus_warn ("GetTempPath failed");
2362 _dbus_abort ();
2363 }
2364
2365 /* Drop terminating backslash or slash */
2366 last_slash = _mbsrchr (p, '\\');
2367 if (last_slash > p && last_slash[1] == '\0')
2368 last_slash[0] = '\0';
2369 last_slash = _mbsrchr (p, '/');
2370 if (last_slash > p && last_slash[1] == '\0')
2371 last_slash[0] = '\0';
2372
2373 tmpdir = buf;
2374 }
2375
2376 _DBUS_UNLOCK (sysdeps);
2377
2378 _dbus_assert(tmpdir != NULL);
2379
2380 return tmpdir;
2381 }
2382
2383
2384 /**
2385 * Deletes the given file.
2386 *
2387 * @param filename the filename
2388 * @param error error location
2389 *
2390 * @returns #TRUE if unlink() succeeded
2391 */
2392 dbus_bool_t
_dbus_delete_file(const DBusString * filename,DBusError * error)2393 _dbus_delete_file (const DBusString *filename,
2394 DBusError *error)
2395 {
2396 const char *filename_c;
2397
2398 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
2399
2400 filename_c = _dbus_string_get_const_data (filename);
2401
2402 if (DeleteFileA (filename_c) == 0)
2403 {
2404 dbus_set_error (error, DBUS_ERROR_FAILED,
2405 "Failed to delete file %s: %s\n",
2406 filename_c, _dbus_strerror_from_errno ());
2407 return FALSE;
2408 }
2409 else
2410 return TRUE;
2411 }
2412
2413 #if !defined (DBUS_DISABLE_ASSERT) || defined(DBUS_ENABLE_EMBEDDED_TESTS)
2414
2415 #if defined(_MSC_VER) || defined(DBUS_WINCE)
2416 # ifdef BACKTRACES
2417 # undef BACKTRACES
2418 # endif
2419 #else
2420 # define BACKTRACES
2421 #endif
2422
2423 #ifdef BACKTRACES
2424 /*
2425 * Backtrace Generator
2426 *
2427 * Copyright 2004 Eric Poech
2428 * Copyright 2004 Robert Shearman
2429 *
2430 * This library is free software; you can redistribute it and/or
2431 * modify it under the terms of the GNU Lesser General Public
2432 * License as published by the Free Software Foundation; either
2433 * version 2.1 of the License, or (at your option) any later version.
2434 *
2435 * This library is distributed in the hope that it will be useful,
2436 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2437 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2438 * Lesser General Public License for more details.
2439 *
2440 * You should have received a copy of the GNU Lesser General Public
2441 * License along with this library; if not, write to the Free Software
2442 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2443 */
2444
2445 #include <winver.h>
2446 #include <imagehlp.h>
2447 #include <stdio.h>
2448
2449 #define DPRINTF(fmt, ...) fprintf (stderr, fmt, ##__VA_ARGS__)
2450
2451 #ifdef _MSC_VER
2452 #define BOOL int
2453
2454 #define __i386__
2455 #endif
2456
dump_backtrace_for_thread(HANDLE hThread)2457 static void dump_backtrace_for_thread (HANDLE hThread)
2458 {
2459 ADDRESS old_address;
2460 STACKFRAME sf;
2461 CONTEXT context;
2462 DWORD dwImageType;
2463 int i = 0;
2464
2465 SymSetOptions (SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
2466 SymInitialize (GetCurrentProcess (), NULL, TRUE);
2467
2468
2469 /* can't use this function for current thread as GetThreadContext
2470 * doesn't support getting context from current thread */
2471 if (hThread == GetCurrentThread())
2472 return;
2473
2474 DPRINTF ("Backtrace:\n");
2475
2476 _DBUS_ZERO (old_address);
2477 _DBUS_ZERO (context);
2478 context.ContextFlags = CONTEXT_FULL;
2479
2480 SuspendThread (hThread);
2481
2482 if (!GetThreadContext (hThread, &context))
2483 {
2484 DPRINTF ("Couldn't get thread context (error %ld)\n", GetLastError ());
2485 ResumeThread (hThread);
2486 return;
2487 }
2488
2489 _DBUS_ZERO (sf);
2490
2491 #ifdef __i386__
2492 dwImageType = IMAGE_FILE_MACHINE_I386;
2493 sf.AddrFrame.Offset = context.Ebp;
2494 sf.AddrFrame.Mode = AddrModeFlat;
2495 sf.AddrPC.Offset = context.Eip;
2496 sf.AddrPC.Mode = AddrModeFlat;
2497 #elif defined(_M_X64)
2498 dwImageType = IMAGE_FILE_MACHINE_AMD64;
2499 sf.AddrPC.Offset = context.Rip;
2500 sf.AddrPC.Mode = AddrModeFlat;
2501 sf.AddrFrame.Offset = context.Rsp;
2502 sf.AddrFrame.Mode = AddrModeFlat;
2503 sf.AddrStack.Offset = context.Rsp;
2504 sf.AddrStack.Mode = AddrModeFlat;
2505 #elif defined(_M_IA64)
2506 dwImageType = IMAGE_FILE_MACHINE_IA64;
2507 sf.AddrPC.Offset = context.StIIP;
2508 sf.AddrPC.Mode = AddrModeFlat;
2509 sf.AddrFrame.Offset = context.IntSp;
2510 sf.AddrFrame.Mode = AddrModeFlat;
2511 sf.AddrBStore.Offset= context.RsBSP;
2512 sf.AddrBStore.Mode = AddrModeFlat;
2513 sf.AddrStack.Offset = context.IntSp;
2514 sf.AddrStack.Mode = AddrModeFlat;
2515 #else
2516 # error You need to fill in the STACKFRAME structure for your architecture
2517 #endif
2518
2519 /*
2520 backtrace format
2521 <level> <address> <symbol>[+offset] [ '[' <file> ':' <line> ']' ] [ 'in' <module> ]
2522 example:
2523 6 0xf75ade6b wine_switch_to_stack+0x2a [/usr/src/debug/wine-snapshot/libs/wine/port.c:59] in libwine.so.1
2524 */
2525 while (StackWalk (dwImageType, GetCurrentProcess (),
2526 hThread, &sf, &context, NULL, SymFunctionTableAccess,
2527 SymGetModuleBase, NULL))
2528 {
2529 char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(char)];
2530 PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
2531 DWORD64 displacement;
2532 IMAGEHLP_LINE line;
2533 DWORD dwDisplacement;
2534 IMAGEHLP_MODULE moduleInfo;
2535
2536 /*
2537 on Wine64 version 1.7.54, we get an infinite number of stack entries
2538 pointing to the same stack frame (_start+0x29 in <wine-loader>)
2539 see bug https://bugs.winehq.org/show_bug.cgi?id=39606
2540 */
2541 #ifndef __i386__
2542 if (old_address.Offset == sf.AddrPC.Offset)
2543 {
2544 break;
2545 }
2546 #endif
2547
2548 pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
2549 pSymbol->MaxNameLen = MAX_SYM_NAME;
2550
2551 if (SymFromAddr (GetCurrentProcess (), sf.AddrPC.Offset, &displacement, pSymbol))
2552 {
2553 if (displacement)
2554 DPRINTF ("%3d %s+0x%I64x", i++, pSymbol->Name, displacement);
2555 else
2556 DPRINTF ("%3d %s", i++, pSymbol->Name);
2557 }
2558 else
2559 DPRINTF ("%3d 0x%Ix", i++, sf.AddrPC.Offset);
2560
2561 line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
2562 if (SymGetLineFromAddr (GetCurrentProcess (), sf.AddrPC.Offset, &dwDisplacement, &line))
2563 {
2564 DPRINTF (" [%s:%ld]", line.FileName, line.LineNumber);
2565 }
2566
2567 moduleInfo.SizeOfStruct = sizeof(moduleInfo);
2568 if (SymGetModuleInfo (GetCurrentProcess (), sf.AddrPC.Offset, &moduleInfo))
2569 {
2570 DPRINTF (" in %s", moduleInfo.ModuleName);
2571 }
2572 DPRINTF ("\n");
2573 old_address = sf.AddrPC;
2574 }
2575 ResumeThread (hThread);
2576 }
2577
dump_thread_proc(LPVOID lpParameter)2578 static DWORD WINAPI dump_thread_proc (LPVOID lpParameter)
2579 {
2580 dump_backtrace_for_thread ((HANDLE) lpParameter);
2581 return 0;
2582 }
2583
2584 /* cannot get valid context from current thread, so we have to execute
2585 * backtrace from another thread */
2586 static void
dump_backtrace(void)2587 dump_backtrace (void)
2588 {
2589 HANDLE hCurrentThread;
2590 HANDLE hThread;
2591 DWORD dwThreadId;
2592 DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
2593 GetCurrentProcess (), &hCurrentThread,
2594 0, FALSE, DUPLICATE_SAME_ACCESS);
2595 hThread = CreateThread (NULL, 0, dump_thread_proc, (LPVOID)hCurrentThread,
2596 0, &dwThreadId);
2597 WaitForSingleObject (hThread, INFINITE);
2598 CloseHandle (hThread);
2599 CloseHandle (hCurrentThread);
2600 }
2601 #endif
2602 #endif /* asserts or tests enabled */
2603
2604 #ifdef BACKTRACES
_dbus_print_backtrace(void)2605 void _dbus_print_backtrace (void)
2606 {
2607 dump_backtrace ();
2608 }
2609 #else
_dbus_print_backtrace(void)2610 void _dbus_print_backtrace (void)
2611 {
2612 _dbus_verbose (" D-Bus not compiled with backtrace support\n");
2613 }
2614 #endif
2615
fromAscii(char ascii)2616 static dbus_uint32_t fromAscii(char ascii)
2617 {
2618 if(ascii >= '0' && ascii <= '9')
2619 return ascii - '0';
2620 if(ascii >= 'A' && ascii <= 'F')
2621 return ascii - 'A' + 10;
2622 if(ascii >= 'a' && ascii <= 'f')
2623 return ascii - 'a' + 10;
2624 return 0;
2625 }
2626
_dbus_read_local_machine_uuid(DBusGUID * machine_id,dbus_bool_t create_if_not_found,DBusError * error)2627 dbus_bool_t _dbus_read_local_machine_uuid (DBusGUID *machine_id,
2628 dbus_bool_t create_if_not_found,
2629 DBusError *error)
2630 {
2631 #ifdef DBUS_WINCE
2632 return TRUE;
2633 // TODO
2634 #else
2635 HW_PROFILE_INFOA info;
2636 char *lpc = &info.szHwProfileGuid[0];
2637 dbus_uint32_t u;
2638
2639 // the hw-profile guid lives long enough
2640 if(!GetCurrentHwProfileA(&info))
2641 {
2642 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL); // FIXME
2643 return FALSE;
2644 }
2645
2646 // Form: {12340001-4980-1920-6788-123456789012}
2647 lpc++;
2648 // 12340001
2649 u = ((fromAscii(lpc[0]) << 0) |
2650 (fromAscii(lpc[1]) << 4) |
2651 (fromAscii(lpc[2]) << 8) |
2652 (fromAscii(lpc[3]) << 12) |
2653 (fromAscii(lpc[4]) << 16) |
2654 (fromAscii(lpc[5]) << 20) |
2655 (fromAscii(lpc[6]) << 24) |
2656 (fromAscii(lpc[7]) << 28));
2657 machine_id->as_uint32s[0] = u;
2658
2659 lpc += 9;
2660 // 4980-1920
2661 u = ((fromAscii(lpc[0]) << 0) |
2662 (fromAscii(lpc[1]) << 4) |
2663 (fromAscii(lpc[2]) << 8) |
2664 (fromAscii(lpc[3]) << 12) |
2665 (fromAscii(lpc[5]) << 16) |
2666 (fromAscii(lpc[6]) << 20) |
2667 (fromAscii(lpc[7]) << 24) |
2668 (fromAscii(lpc[8]) << 28));
2669 machine_id->as_uint32s[1] = u;
2670
2671 lpc += 10;
2672 // 6788-1234
2673 u = ((fromAscii(lpc[0]) << 0) |
2674 (fromAscii(lpc[1]) << 4) |
2675 (fromAscii(lpc[2]) << 8) |
2676 (fromAscii(lpc[3]) << 12) |
2677 (fromAscii(lpc[5]) << 16) |
2678 (fromAscii(lpc[6]) << 20) |
2679 (fromAscii(lpc[7]) << 24) |
2680 (fromAscii(lpc[8]) << 28));
2681 machine_id->as_uint32s[2] = u;
2682
2683 lpc += 9;
2684 // 56789012
2685 u = ((fromAscii(lpc[0]) << 0) |
2686 (fromAscii(lpc[1]) << 4) |
2687 (fromAscii(lpc[2]) << 8) |
2688 (fromAscii(lpc[3]) << 12) |
2689 (fromAscii(lpc[4]) << 16) |
2690 (fromAscii(lpc[5]) << 20) |
2691 (fromAscii(lpc[6]) << 24) |
2692 (fromAscii(lpc[7]) << 28));
2693 machine_id->as_uint32s[3] = u;
2694 #endif
2695 return TRUE;
2696 }
2697
2698 static
_dbus_global_lock(const char * mutexname)2699 HANDLE _dbus_global_lock (const char *mutexname)
2700 {
2701 HANDLE mutex;
2702 DWORD gotMutex;
2703
2704 mutex = CreateMutexA( NULL, FALSE, mutexname );
2705 if( !mutex )
2706 {
2707 return FALSE;
2708 }
2709
2710 gotMutex = WaitForSingleObject( mutex, INFINITE );
2711 switch( gotMutex )
2712 {
2713 case WAIT_ABANDONED:
2714 ReleaseMutex (mutex);
2715 CloseHandle (mutex);
2716 return 0;
2717 case WAIT_FAILED:
2718 case WAIT_TIMEOUT:
2719 return 0;
2720 default:
2721 return mutex;
2722 }
2723 }
2724
2725 static
_dbus_global_unlock(HANDLE mutex)2726 void _dbus_global_unlock (HANDLE mutex)
2727 {
2728 ReleaseMutex (mutex);
2729 CloseHandle (mutex);
2730 }
2731
2732 // for proper cleanup in dbus-daemon
2733 static HANDLE hDBusDaemonMutex = NULL;
2734 static HANDLE hDBusSharedMem = NULL;
2735 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2736 static const char *cUniqueDBusInitMutex = "UniqueDBusInitMutex";
2737 // sync _dbus_get_autolaunch_address
2738 static const char *cDBusAutolaunchMutex = "DBusAutolaunchMutex";
2739 // mutex to determine if dbus-daemon is already started (per user)
2740 static const char *cDBusDaemonMutex = "DBusDaemonMutex";
2741 // named shm for dbus adress info (per user)
2742 static const char *cDBusDaemonAddressInfo = "DBusDaemonAddressInfo";
2743
2744 static dbus_bool_t
_dbus_get_install_root_as_hash(DBusString * out)2745 _dbus_get_install_root_as_hash(DBusString *out)
2746 {
2747 DBusString install_path;
2748
2749 _dbus_string_init(&install_path);
2750
2751 if (!_dbus_get_install_root (&install_path) ||
2752 _dbus_string_get_length (&install_path) == 0)
2753 return FALSE;
2754
2755 _dbus_string_init(out);
2756 _dbus_string_tolower_ascii(&install_path,0,_dbus_string_get_length(&install_path));
2757
2758 if (!_dbus_sha_compute (&install_path, out))
2759 return FALSE;
2760
2761 return TRUE;
2762 }
2763
2764 static dbus_bool_t
_dbus_get_address_string(DBusString * out,const char * basestring,const char * scope)2765 _dbus_get_address_string (DBusString *out, const char *basestring, const char *scope)
2766 {
2767 _dbus_string_init(out);
2768 _dbus_string_append(out,basestring);
2769
2770 if (!scope)
2771 {
2772 return TRUE;
2773 }
2774 else if (strcmp(scope,"*install-path") == 0
2775 // for 1.3 compatibility
2776 || strcmp(scope,"install-path") == 0)
2777 {
2778 DBusString temp;
2779 if (!_dbus_get_install_root_as_hash(&temp))
2780 {
2781 _dbus_string_free(out);
2782 return FALSE;
2783 }
2784 _dbus_string_append(out,"-");
2785 _dbus_string_append(out,_dbus_string_get_const_data(&temp));
2786 _dbus_string_free(&temp);
2787 }
2788 else if (strcmp(scope,"*user") == 0)
2789 {
2790 _dbus_string_append(out,"-");
2791 if (!_dbus_append_user_from_current_process(out))
2792 {
2793 _dbus_string_free(out);
2794 return FALSE;
2795 }
2796 }
2797 else if (strlen(scope) > 0)
2798 {
2799 _dbus_string_append(out,"-");
2800 _dbus_string_append(out,scope);
2801 return TRUE;
2802 }
2803 return TRUE;
2804 }
2805
2806 static dbus_bool_t
_dbus_get_shm_name(DBusString * out,const char * scope)2807 _dbus_get_shm_name (DBusString *out,const char *scope)
2808 {
2809 return _dbus_get_address_string (out,cDBusDaemonAddressInfo,scope);
2810 }
2811
2812 static dbus_bool_t
_dbus_get_mutex_name(DBusString * out,const char * scope)2813 _dbus_get_mutex_name (DBusString *out,const char *scope)
2814 {
2815 return _dbus_get_address_string (out,cDBusDaemonMutex,scope);
2816 }
2817
2818 dbus_bool_t
_dbus_daemon_is_session_bus_address_published(const char * scope)2819 _dbus_daemon_is_session_bus_address_published (const char *scope)
2820 {
2821 HANDLE lock;
2822 DBusString mutex_name;
2823
2824 if (!_dbus_get_mutex_name(&mutex_name,scope))
2825 {
2826 _dbus_string_free( &mutex_name );
2827 return FALSE;
2828 }
2829
2830 if (hDBusDaemonMutex)
2831 return TRUE;
2832
2833 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2834 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2835
2836 // we use CreateMutex instead of OpenMutex because of possible race conditions,
2837 // see http://msdn.microsoft.com/en-us/library/ms684315%28VS.85%29.aspx
2838 hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2839
2840 /* The client uses mutex ownership to detect a running server, so the server should do so too.
2841 Fortunally the client deletes the mutex in the lock protected area, so checking presence
2842 will work too. */
2843
2844 _dbus_global_unlock( lock );
2845
2846 _dbus_string_free( &mutex_name );
2847
2848 if (hDBusDaemonMutex == NULL)
2849 return FALSE;
2850 if (GetLastError() == ERROR_ALREADY_EXISTS)
2851 {
2852 CloseHandle(hDBusDaemonMutex);
2853 hDBusDaemonMutex = NULL;
2854 return TRUE;
2855 }
2856 // mutex wasn't created before, so return false.
2857 // We leave the mutex name allocated for later reusage
2858 // in _dbus_daemon_publish_session_bus_address.
2859 return FALSE;
2860 }
2861
2862 dbus_bool_t
_dbus_daemon_publish_session_bus_address(const char * address,const char * scope)2863 _dbus_daemon_publish_session_bus_address (const char* address, const char *scope)
2864 {
2865 HANDLE lock;
2866 char *shared_addr = NULL;
2867 DBusString shm_name;
2868 DBusString mutex_name;
2869 dbus_uint64_t len;
2870
2871 _dbus_assert (address);
2872
2873 if (!_dbus_get_mutex_name(&mutex_name,scope))
2874 {
2875 _dbus_string_free( &mutex_name );
2876 return FALSE;
2877 }
2878
2879 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2880 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2881
2882 if (!hDBusDaemonMutex)
2883 {
2884 hDBusDaemonMutex = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
2885 }
2886 _dbus_string_free( &mutex_name );
2887
2888 // acquire the mutex
2889 if (WaitForSingleObject( hDBusDaemonMutex, 10 ) != WAIT_OBJECT_0)
2890 {
2891 _dbus_global_unlock( lock );
2892 CloseHandle( hDBusDaemonMutex );
2893 return FALSE;
2894 }
2895
2896 if (!_dbus_get_shm_name(&shm_name,scope))
2897 {
2898 _dbus_string_free( &shm_name );
2899 _dbus_global_unlock( lock );
2900 return FALSE;
2901 }
2902
2903 // create shm
2904 len = strlen (address) + 1;
2905
2906 hDBusSharedMem = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
2907 len >> 32, len & 0xffffffffu,
2908 _dbus_string_get_const_data(&shm_name) );
2909 _dbus_assert( hDBusSharedMem );
2910
2911 shared_addr = MapViewOfFile( hDBusSharedMem, FILE_MAP_WRITE, 0, 0, 0 );
2912
2913 _dbus_assert (shared_addr);
2914
2915 strcpy( shared_addr, address);
2916
2917 // cleanup
2918 UnmapViewOfFile( shared_addr );
2919
2920 _dbus_global_unlock( lock );
2921 _dbus_verbose( "published session bus address at %s\n",_dbus_string_get_const_data (&shm_name) );
2922
2923 _dbus_string_free( &shm_name );
2924 return TRUE;
2925 }
2926
2927 void
_dbus_daemon_unpublish_session_bus_address(void)2928 _dbus_daemon_unpublish_session_bus_address (void)
2929 {
2930 HANDLE lock;
2931
2932 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
2933 lock = _dbus_global_lock( cUniqueDBusInitMutex );
2934
2935 CloseHandle( hDBusSharedMem );
2936
2937 hDBusSharedMem = NULL;
2938
2939 ReleaseMutex( hDBusDaemonMutex );
2940
2941 CloseHandle( hDBusDaemonMutex );
2942
2943 hDBusDaemonMutex = NULL;
2944
2945 _dbus_global_unlock( lock );
2946 }
2947
2948 static dbus_bool_t
_dbus_get_autolaunch_shm(DBusString * address,DBusString * shm_name)2949 _dbus_get_autolaunch_shm (DBusString *address, DBusString *shm_name)
2950 {
2951 HANDLE sharedMem;
2952 char *shared_addr;
2953 int i;
2954
2955 // read shm
2956 for(i=0;i<20;++i) {
2957 // we know that dbus-daemon is available, so we wait until shm is available
2958 sharedMem = OpenFileMappingA( FILE_MAP_READ, FALSE, _dbus_string_get_const_data(shm_name));
2959 if( sharedMem == 0 )
2960 Sleep( 100 );
2961 if ( sharedMem != 0)
2962 break;
2963 }
2964
2965 if( sharedMem == 0 )
2966 return FALSE;
2967
2968 shared_addr = MapViewOfFile( sharedMem, FILE_MAP_READ, 0, 0, 0 );
2969
2970 if( !shared_addr )
2971 return FALSE;
2972
2973 _dbus_string_init( address );
2974
2975 _dbus_string_append( address, shared_addr );
2976
2977 // cleanup
2978 UnmapViewOfFile( shared_addr );
2979
2980 CloseHandle( sharedMem );
2981
2982 return TRUE;
2983 }
2984
2985 static dbus_bool_t
_dbus_daemon_already_runs(DBusString * address,DBusString * shm_name,const char * scope)2986 _dbus_daemon_already_runs (DBusString *address, DBusString *shm_name, const char *scope)
2987 {
2988 HANDLE lock;
2989 HANDLE daemon;
2990 DBusString mutex_name;
2991 dbus_bool_t bRet = TRUE;
2992
2993 if (!_dbus_get_mutex_name(&mutex_name,scope))
2994 {
2995 _dbus_string_free( &mutex_name );
2996 return FALSE;
2997 }
2998
2999 // sync _dbus_daemon_publish_session_bus_address, _dbus_daemon_unpublish_session_bus_address and _dbus_daemon_already_runs
3000 lock = _dbus_global_lock( cUniqueDBusInitMutex );
3001
3002 // do checks
3003 daemon = CreateMutexA( NULL, FALSE, _dbus_string_get_const_data(&mutex_name) );
3004 if(WaitForSingleObject( daemon, 10 ) != WAIT_TIMEOUT)
3005 {
3006 ReleaseMutex (daemon);
3007 CloseHandle (daemon);
3008
3009 _dbus_global_unlock( lock );
3010 _dbus_string_free( &mutex_name );
3011 return FALSE;
3012 }
3013
3014 // read shm
3015 bRet = _dbus_get_autolaunch_shm( address, shm_name );
3016
3017 // cleanup
3018 CloseHandle ( daemon );
3019
3020 _dbus_global_unlock( lock );
3021 _dbus_string_free( &mutex_name );
3022
3023 return bRet;
3024 }
3025
3026 dbus_bool_t
_dbus_get_autolaunch_address(const char * scope,DBusString * address,DBusError * error)3027 _dbus_get_autolaunch_address (const char *scope, DBusString *address,
3028 DBusError *error)
3029 {
3030 HANDLE mutex;
3031 STARTUPINFOA si;
3032 PROCESS_INFORMATION pi;
3033 dbus_bool_t retval = FALSE;
3034 LPSTR lpFile;
3035 char dbus_exe_path[MAX_PATH];
3036 char dbus_args[MAX_PATH * 2];
3037 const char * daemon_name = DBUS_DAEMON_NAME ".exe";
3038 DBusString shm_name;
3039
3040 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3041
3042 if (!_dbus_get_shm_name(&shm_name,scope))
3043 {
3044 dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not determine shm name");
3045 return FALSE;
3046 }
3047
3048 mutex = _dbus_global_lock ( cDBusAutolaunchMutex );
3049
3050 if (_dbus_daemon_already_runs(address,&shm_name,scope))
3051 {
3052 _dbus_verbose( "found running dbus daemon for scope '%s' at %s\n",
3053 scope ? scope : "", _dbus_string_get_const_data (&shm_name) );
3054 retval = TRUE;
3055 goto out;
3056 }
3057
3058 if (!SearchPathA(NULL, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3059 {
3060 // Look in directory containing dbus shared library
3061 HMODULE hmod;
3062 char dbus_module_path[MAX_PATH];
3063 DWORD rc;
3064
3065 _dbus_verbose( "did not found dbus daemon executable on default search path, "
3066 "trying path where dbus shared library is located");
3067
3068 hmod = _dbus_win_get_dll_hmodule();
3069 rc = GetModuleFileNameA(hmod, dbus_module_path, sizeof(dbus_module_path));
3070 if (rc <= 0)
3071 {
3072 dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not retrieve dbus shared library file name");
3073 retval = FALSE;
3074 goto out;
3075 }
3076 else
3077 {
3078 char *ext_idx = strrchr(dbus_module_path, '\\');
3079 if (ext_idx)
3080 *ext_idx = '\0';
3081 if (!SearchPathA(dbus_module_path, daemon_name, NULL, sizeof(dbus_exe_path), dbus_exe_path, &lpFile))
3082 {
3083 dbus_set_error_const (error, DBUS_ERROR_FAILED, "could not find dbus-daemon executable");
3084 retval = FALSE;
3085 printf ("please add the path to %s to your PATH environment variable\n", daemon_name);
3086 printf ("or start the daemon manually\n\n");
3087 goto out;
3088 }
3089 _dbus_verbose( "found dbus daemon executable at %s",dbus_module_path);
3090 }
3091 }
3092
3093
3094 // Create process
3095 ZeroMemory( &si, sizeof(si) );
3096 si.cb = sizeof(si);
3097 ZeroMemory( &pi, sizeof(pi) );
3098
3099 _snprintf(dbus_args, sizeof(dbus_args) - 1, "\"%s\" %s", dbus_exe_path, " --session");
3100
3101 // argv[i] = "--config-file=bus\\session.conf";
3102 // printf("create process \"%s\" %s\n", dbus_exe_path, dbus_args);
3103 if(CreateProcessA(dbus_exe_path, dbus_args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
3104 {
3105 CloseHandle (pi.hThread);
3106 CloseHandle (pi.hProcess);
3107 retval = _dbus_get_autolaunch_shm( address, &shm_name );
3108 if (retval == FALSE)
3109 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to get autolaunch address from launched dbus-daemon");
3110 }
3111 else
3112 {
3113 dbus_set_error_const (error, DBUS_ERROR_FAILED, "Failed to launch dbus-daemon");
3114 retval = FALSE;
3115 }
3116
3117 out:
3118 if (retval)
3119 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3120 else
3121 _DBUS_ASSERT_ERROR_IS_SET (error);
3122
3123 _dbus_global_unlock (mutex);
3124 _dbus_string_free (&shm_name);
3125
3126 return retval;
3127 }
3128
3129
3130 /** Makes the file readable by every user in the system.
3131 *
3132 * @param filename the filename
3133 * @param error error location
3134 * @returns #TRUE if the file's permissions could be changed.
3135 */
3136 dbus_bool_t
_dbus_make_file_world_readable(const DBusString * filename,DBusError * error)3137 _dbus_make_file_world_readable(const DBusString *filename,
3138 DBusError *error)
3139 {
3140 // TODO
3141 return TRUE;
3142 }
3143
3144 /**
3145 * Atomically increments an integer
3146 *
3147 * @param atomic pointer to the integer to increment
3148 * @returns the value before incrementing
3149 *
3150 */
3151 dbus_int32_t
_dbus_atomic_inc(DBusAtomic * atomic)3152 _dbus_atomic_inc (DBusAtomic *atomic)
3153 {
3154 // +/- 1 is needed here!
3155 // no volatile argument with mingw
3156 return InterlockedIncrement (&atomic->value) - 1;
3157 }
3158
3159 /**
3160 * Atomically decrement an integer
3161 *
3162 * @param atomic pointer to the integer to decrement
3163 * @returns the value before decrementing
3164 *
3165 */
3166 dbus_int32_t
_dbus_atomic_dec(DBusAtomic * atomic)3167 _dbus_atomic_dec (DBusAtomic *atomic)
3168 {
3169 // +/- 1 is needed here!
3170 // no volatile argument with mingw
3171 return InterlockedDecrement (&atomic->value) + 1;
3172 }
3173
3174 /**
3175 * Atomically get the value of an integer. It may change at any time
3176 * thereafter, so this is mostly only useful for assertions.
3177 *
3178 * @param atomic pointer to the integer to get
3179 * @returns the value at this moment
3180 */
3181 dbus_int32_t
_dbus_atomic_get(DBusAtomic * atomic)3182 _dbus_atomic_get (DBusAtomic *atomic)
3183 {
3184 /* In this situation, GLib issues a MemoryBarrier() and then returns
3185 * atomic->value. However, mingw from mingw.org (not to be confused with
3186 * mingw-w64 from mingw-w64.sf.net) does not have MemoryBarrier in its
3187 * headers, so we have to get a memory barrier some other way.
3188 *
3189 * InterlockedIncrement is older, and is documented on MSDN to be a full
3190 * memory barrier, so let's use that.
3191 */
3192 long dummy = 0;
3193
3194 InterlockedExchange (&dummy, 1);
3195
3196 return atomic->value;
3197 }
3198
3199 /**
3200 * Called when the bus daemon is signaled to reload its configuration; any
3201 * caches should be nuked. Of course any caches that need explicit reload
3202 * are probably broken, but c'est la vie.
3203 *
3204 *
3205 */
3206 void
_dbus_flush_caches(void)3207 _dbus_flush_caches (void)
3208 {
3209 }
3210
3211 /**
3212 * See if errno is EAGAIN or EWOULDBLOCK (this has to be done differently
3213 * for Winsock so is abstracted)
3214 *
3215 * @returns #TRUE if e == EAGAIN or e == EWOULDBLOCK
3216 */
3217 dbus_bool_t
_dbus_get_is_errno_eagain_or_ewouldblock(int e)3218 _dbus_get_is_errno_eagain_or_ewouldblock (int e)
3219 {
3220 return e == WSAEWOULDBLOCK;
3221 }
3222
3223 /**
3224 * Fill str with the absolute path of the D-Bus installation, or truncate str
3225 * to zero length if we cannot determine it.
3226 *
3227 * @param str buffer for installation path
3228 * @returns #FALSE on OOM, #TRUE if not OOM
3229 */
3230 dbus_bool_t
_dbus_get_install_root(DBusString * str)3231 _dbus_get_install_root (DBusString *str)
3232 {
3233 /* this is just an initial guess */
3234 DWORD pathLength = MAX_PATH;
3235 unsigned char *lastSlash;
3236 unsigned char *prefix;
3237
3238 do
3239 {
3240 /* allocate enough space for our best guess at the length */
3241 if (!_dbus_string_set_length (str, pathLength))
3242 {
3243 _dbus_string_set_length (str, 0);
3244 return FALSE;
3245 }
3246
3247 SetLastError (0);
3248 pathLength = GetModuleFileNameA (_dbus_win_get_dll_hmodule (),
3249 _dbus_string_get_data (str), _dbus_string_get_length (str));
3250
3251 if (pathLength == 0 || GetLastError () != 0)
3252 {
3253 /* failed, but not OOM */
3254 _dbus_string_set_length (str, 0);
3255 return TRUE;
3256 }
3257
3258 /* if the return is strictly less than the buffer size, it has
3259 * not been truncated, so we can continue */
3260 if (pathLength < (DWORD) _dbus_string_get_length (str))
3261 {
3262 /* reduce the length to match what Windows filled in */
3263 if (!_dbus_string_set_length (str, pathLength))
3264 {
3265 _dbus_string_set_length (str, 0);
3266 return FALSE;
3267 }
3268
3269 break;
3270 }
3271
3272 /* else it may have been truncated; try with a larger buffer */
3273 pathLength *= 2;
3274 }
3275 while (TRUE);
3276
3277 /* the rest of this function works by direct byte manipulation of the
3278 * underlying buffer */
3279 prefix = _dbus_string_get_udata (str);
3280
3281 lastSlash = _mbsrchr (prefix, '\\');
3282 if (lastSlash == NULL) {
3283 /* failed, but not OOM */
3284 _dbus_string_set_length (str, 0);
3285 return TRUE;
3286 }
3287 //cut off binary name
3288 lastSlash[1] = 0;
3289
3290 //cut possible "\\bin"
3291 //this fails if we are in a double-byte system codepage and the
3292 //folder's name happens to end with the *bytes*
3293 //"\\bin"... (I.e. the second byte of some Han character and then
3294 //the Latin "bin", but that is not likely I think...
3295 if (lastSlash - prefix >= 4 && _mbsnicmp (lastSlash - 4, (const unsigned char *)"\\bin", 4) == 0)
3296 lastSlash[-3] = 0;
3297 else if (lastSlash - prefix >= 10 && _mbsnicmp (lastSlash - 10, (const unsigned char *)"\\bin\\debug", 10) == 0)
3298 lastSlash[-9] = 0;
3299 else if (lastSlash - prefix >= 12 && _mbsnicmp (lastSlash - 12, (const unsigned char *)"\\bin\\release", 12) == 0)
3300 lastSlash[-11] = 0;
3301
3302 /* fix up the length to match the byte-manipulation */
3303 _dbus_string_set_length (str, strlen ((char *) prefix));
3304
3305 return TRUE;
3306 }
3307
3308 /* See comment in dbus-sysdeps-unix.c */
3309 dbus_bool_t
_dbus_lookup_session_address(dbus_bool_t * supported,DBusString * address,DBusError * error)3310 _dbus_lookup_session_address (dbus_bool_t *supported,
3311 DBusString *address,
3312 DBusError *error)
3313 {
3314 /* Probably fill this in with something based on COM? */
3315 *supported = FALSE;
3316 return TRUE;
3317 }
3318
3319 /**
3320 * Appends the directory in which a keyring for the given credentials
3321 * should be stored. The credentials should have either a Windows or
3322 * UNIX user in them. The directory should be an absolute path.
3323 *
3324 * On UNIX the directory is ~/.dbus-keyrings while on Windows it should probably
3325 * be something else, since the dotfile convention is not normal on Windows.
3326 *
3327 * @param directory string to append directory to
3328 * @param credentials credentials the directory should be for
3329 *
3330 * @returns #FALSE on no memory
3331 */
3332 dbus_bool_t
_dbus_append_keyring_directory_for_credentials(DBusString * directory,DBusCredentials * credentials)3333 _dbus_append_keyring_directory_for_credentials (DBusString *directory,
3334 DBusCredentials *credentials)
3335 {
3336 DBusString homedir;
3337 DBusString dotdir;
3338 const char *homepath;
3339 const char *homedrive;
3340
3341 _dbus_assert (credentials != NULL);
3342 _dbus_assert (!_dbus_credentials_are_anonymous (credentials));
3343
3344 if (!_dbus_string_init (&homedir))
3345 return FALSE;
3346
3347 homedrive = _dbus_getenv("HOMEDRIVE");
3348 if (homedrive != NULL && *homedrive != '\0')
3349 {
3350 _dbus_string_append(&homedir,homedrive);
3351 }
3352
3353 homepath = _dbus_getenv("HOMEPATH");
3354 if (homepath != NULL && *homepath != '\0')
3355 {
3356 _dbus_string_append(&homedir,homepath);
3357 }
3358
3359 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
3360 {
3361 const char *override;
3362
3363 override = _dbus_getenv ("DBUS_TEST_HOMEDIR");
3364 if (override != NULL && *override != '\0')
3365 {
3366 _dbus_string_set_length (&homedir, 0);
3367 if (!_dbus_string_append (&homedir, override))
3368 goto failed;
3369
3370 _dbus_verbose ("Using fake homedir for testing: %s\n",
3371 _dbus_string_get_const_data (&homedir));
3372 }
3373 else
3374 {
3375 /* Not strictly thread-safe, but if we fail at thread-safety here,
3376 * the worst that will happen is some extra warnings. */
3377 static dbus_bool_t already_warned = FALSE;
3378 if (!already_warned)
3379 {
3380 _dbus_warn ("Using your real home directory for testing, set DBUS_TEST_HOMEDIR to avoid");
3381 already_warned = TRUE;
3382 }
3383 }
3384 }
3385 #endif
3386
3387 #ifdef DBUS_WINCE
3388 /* It's not possible to create a .something directory in Windows CE
3389 using the file explorer. */
3390 #define KEYRING_DIR "dbus-keyrings"
3391 #else
3392 #define KEYRING_DIR ".dbus-keyrings"
3393 #endif
3394
3395 _dbus_string_init_const (&dotdir, KEYRING_DIR);
3396 if (!_dbus_concat_dir_and_file (&homedir,
3397 &dotdir))
3398 goto failed;
3399
3400 if (!_dbus_string_copy (&homedir, 0,
3401 directory, _dbus_string_get_length (directory))) {
3402 goto failed;
3403 }
3404
3405 _dbus_string_free (&homedir);
3406 return TRUE;
3407
3408 failed:
3409 _dbus_string_free (&homedir);
3410 return FALSE;
3411 }
3412
3413 /** Checks if a file exists
3414 *
3415 * @param file full path to the file
3416 * @returns #TRUE if file exists
3417 */
3418 dbus_bool_t
_dbus_file_exists(const char * file)3419 _dbus_file_exists (const char *file)
3420 {
3421 DWORD attributes = GetFileAttributesA (file);
3422
3423 if (attributes != INVALID_FILE_ATTRIBUTES && GetLastError() != ERROR_PATH_NOT_FOUND)
3424 return TRUE;
3425 else
3426 return FALSE;
3427 }
3428
3429 /**
3430 * A wrapper around strerror() because some platforms
3431 * may be lame and not have strerror().
3432 *
3433 * @param error_number errno.
3434 * @returns error description.
3435 */
3436 const char*
_dbus_strerror(int error_number)3437 _dbus_strerror (int error_number)
3438 {
3439 #ifdef DBUS_WINCE
3440 // TODO
3441 return "unknown";
3442 #else
3443 const char *msg;
3444
3445 switch (error_number)
3446 {
3447 case WSAEINTR:
3448 return "Interrupted function call";
3449 case WSAEACCES:
3450 return "Permission denied";
3451 case WSAEFAULT:
3452 return "Bad address";
3453 case WSAEINVAL:
3454 return "Invalid argument";
3455 case WSAEMFILE:
3456 return "Too many open files";
3457 case WSAEWOULDBLOCK:
3458 return "Resource temporarily unavailable";
3459 case WSAEINPROGRESS:
3460 return "Operation now in progress";
3461 case WSAEALREADY:
3462 return "Operation already in progress";
3463 case WSAENOTSOCK:
3464 return "Socket operation on nonsocket";
3465 case WSAEDESTADDRREQ:
3466 return "Destination address required";
3467 case WSAEMSGSIZE:
3468 return "Message too long";
3469 case WSAEPROTOTYPE:
3470 return "Protocol wrong type for socket";
3471 case WSAENOPROTOOPT:
3472 return "Bad protocol option";
3473 case WSAEPROTONOSUPPORT:
3474 return "Protocol not supported";
3475 case WSAESOCKTNOSUPPORT:
3476 return "Socket type not supported";
3477 case WSAEOPNOTSUPP:
3478 return "Operation not supported";
3479 case WSAEPFNOSUPPORT:
3480 return "Protocol family not supported";
3481 case WSAEAFNOSUPPORT:
3482 return "Address family not supported by protocol family";
3483 case WSAEADDRINUSE:
3484 return "Address already in use";
3485 case WSAEADDRNOTAVAIL:
3486 return "Cannot assign requested address";
3487 case WSAENETDOWN:
3488 return "Network is down";
3489 case WSAENETUNREACH:
3490 return "Network is unreachable";
3491 case WSAENETRESET:
3492 return "Network dropped connection on reset";
3493 case WSAECONNABORTED:
3494 return "Software caused connection abort";
3495 case WSAECONNRESET:
3496 return "Connection reset by peer";
3497 case WSAENOBUFS:
3498 return "No buffer space available";
3499 case WSAEISCONN:
3500 return "Socket is already connected";
3501 case WSAENOTCONN:
3502 return "Socket is not connected";
3503 case WSAESHUTDOWN:
3504 return "Cannot send after socket shutdown";
3505 case WSAETIMEDOUT:
3506 return "Connection timed out";
3507 case WSAECONNREFUSED:
3508 return "Connection refused";
3509 case WSAEHOSTDOWN:
3510 return "Host is down";
3511 case WSAEHOSTUNREACH:
3512 return "No route to host";
3513 case WSAEPROCLIM:
3514 return "Too many processes";
3515 case WSAEDISCON:
3516 return "Graceful shutdown in progress";
3517 case WSATYPE_NOT_FOUND:
3518 return "Class type not found";
3519 case WSAHOST_NOT_FOUND:
3520 return "Host not found";
3521 case WSATRY_AGAIN:
3522 return "Nonauthoritative host not found";
3523 case WSANO_RECOVERY:
3524 return "This is a nonrecoverable error";
3525 case WSANO_DATA:
3526 return "Valid name, no data record of requested type";
3527 case WSA_INVALID_HANDLE:
3528 return "Specified event object handle is invalid";
3529 case WSA_INVALID_PARAMETER:
3530 return "One or more parameters are invalid";
3531 case WSA_IO_INCOMPLETE:
3532 return "Overlapped I/O event object not in signaled state";
3533 case WSA_IO_PENDING:
3534 return "Overlapped operations will complete later";
3535 case WSA_NOT_ENOUGH_MEMORY:
3536 return "Insufficient memory available";
3537 case WSA_OPERATION_ABORTED:
3538 return "Overlapped operation aborted";
3539 #ifdef WSAINVALIDPROCTABLE
3540
3541 case WSAINVALIDPROCTABLE:
3542 return "Invalid procedure table from service provider";
3543 #endif
3544 #ifdef WSAINVALIDPROVIDER
3545
3546 case WSAINVALIDPROVIDER:
3547 return "Invalid service provider version number";
3548 #endif
3549 #ifdef WSAPROVIDERFAILEDINIT
3550
3551 case WSAPROVIDERFAILEDINIT:
3552 return "Unable to initialize a service provider";
3553 #endif
3554
3555 case WSASYSCALLFAILURE:
3556 return "System call failure";
3557
3558 default:
3559 msg = strerror (error_number);
3560
3561 if (msg == NULL)
3562 msg = "unknown";
3563
3564 return msg;
3565 }
3566 #endif //DBUS_WINCE
3567 }
3568
3569 /**
3570 * Assigns an error name and message corresponding to a Win32 error
3571 * code to a DBusError. Does nothing if error is #NULL.
3572 *
3573 * @param error the error.
3574 * @param code the Win32 error code
3575 */
3576 void
_dbus_win_set_error_from_win_error(DBusError * error,int code)3577 _dbus_win_set_error_from_win_error (DBusError *error,
3578 int code)
3579 {
3580 char *msg;
3581
3582 /* As we want the English message, use the A API */
3583 FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
3584 FORMAT_MESSAGE_IGNORE_INSERTS |
3585 FORMAT_MESSAGE_FROM_SYSTEM,
3586 NULL, code, MAKELANGID (LANG_ENGLISH, SUBLANG_ENGLISH_US),
3587 (LPSTR) &msg, 0, NULL);
3588 if (msg)
3589 {
3590 dbus_set_error (error, "win32.error", "%s", msg);
3591 LocalFree (msg);
3592 }
3593 else
3594 dbus_set_error (error, "win32.error", "Unknown error code %d or FormatMessage failed", code);
3595 }
3596
3597 void
_dbus_win_warn_win_error(const char * message,unsigned long code)3598 _dbus_win_warn_win_error (const char *message,
3599 unsigned long code)
3600 {
3601 DBusError error;
3602
3603 dbus_error_init (&error);
3604 _dbus_win_set_error_from_win_error (&error, code);
3605 _dbus_warn ("%s: %s", message, error.message);
3606 dbus_error_free (&error);
3607 }
3608
3609 /**
3610 * Removes a directory; Directory must be empty
3611 *
3612 * @param filename directory filename
3613 * @param error initialized error object
3614 * @returns #TRUE on success
3615 */
3616 dbus_bool_t
_dbus_delete_directory(const DBusString * filename,DBusError * error)3617 _dbus_delete_directory (const DBusString *filename,
3618 DBusError *error)
3619 {
3620 const char *filename_c;
3621
3622 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
3623
3624 filename_c = _dbus_string_get_const_data (filename);
3625
3626 if (RemoveDirectoryA (filename_c) == 0)
3627 {
3628 char *emsg = _dbus_win_error_string (GetLastError ());
3629 dbus_set_error (error, _dbus_win_error_from_last_error (),
3630 "Failed to remove directory %s: %s",
3631 filename_c, emsg);
3632 _dbus_win_free_error_string (emsg);
3633 return FALSE;
3634 }
3635
3636 return TRUE;
3637 }
3638
3639 /**
3640 * Checks whether the filename is an absolute path
3641 *
3642 * @param filename the filename
3643 * @returns #TRUE if an absolute path
3644 */
3645 dbus_bool_t
_dbus_path_is_absolute(const DBusString * filename)3646 _dbus_path_is_absolute (const DBusString *filename)
3647 {
3648 if (_dbus_string_get_length (filename) > 0)
3649 return _dbus_string_get_byte (filename, 1) == ':'
3650 || _dbus_string_get_byte (filename, 0) == '\\'
3651 || _dbus_string_get_byte (filename, 0) == '/';
3652 else
3653 return FALSE;
3654 }
3655
3656 dbus_bool_t
_dbus_check_setuid(void)3657 _dbus_check_setuid (void)
3658 {
3659 return FALSE;
3660 }
3661
3662 int
_dbus_save_socket_errno(void)3663 _dbus_save_socket_errno (void)
3664 {
3665 return errno;
3666 }
3667
3668 void
_dbus_restore_socket_errno(int saved_errno)3669 _dbus_restore_socket_errno (int saved_errno)
3670 {
3671 _dbus_win_set_errno (saved_errno);
3672 }
3673
3674 static const char *log_tag = "dbus";
3675 static DBusLogFlags log_flags = DBUS_LOG_FLAGS_STDERR;
3676
3677 /**
3678 * Initialize the system log.
3679 *
3680 * The "tag" is not copied, and must remain valid for the entire lifetime of
3681 * the process or until _dbus_init_system_log() is called again. In practice
3682 * it will normally be a constant.
3683 *
3684 * @param tag the name of the executable (syslog tag)
3685 * @param mode whether to log to stderr, the system log or both
3686 */
3687 void
_dbus_init_system_log(const char * tag,DBusLogFlags flags)3688 _dbus_init_system_log (const char *tag,
3689 DBusLogFlags flags)
3690 {
3691 /* We never want to turn off logging completely */
3692 _dbus_assert (
3693 (flags & (DBUS_LOG_FLAGS_STDERR | DBUS_LOG_FLAGS_SYSTEM_LOG)) != 0);
3694
3695 log_tag = tag;
3696 log_flags = flags;
3697 }
3698
3699 /**
3700 * Log a message to the system log file (e.g. syslog on Unix).
3701 *
3702 * @param severity a severity value
3703 * @param msg a printf-style format string
3704 * @param args arguments for the format string
3705 */
3706 void
_dbus_logv(DBusSystemLogSeverity severity,const char * msg,va_list args)3707 _dbus_logv (DBusSystemLogSeverity severity,
3708 const char *msg,
3709 va_list args)
3710 {
3711 const char *s = "";
3712 va_list tmp;
3713
3714 switch(severity)
3715 {
3716 case DBUS_SYSTEM_LOG_INFO: s = "info"; break;
3717 case DBUS_SYSTEM_LOG_WARNING: s = "warning"; break;
3718 case DBUS_SYSTEM_LOG_SECURITY: s = "security"; break;
3719 case DBUS_SYSTEM_LOG_ERROR: s = "error"; break;
3720 default: _dbus_assert_not_reached ("invalid log severity");
3721 }
3722
3723 if (log_flags & DBUS_LOG_FLAGS_SYSTEM_LOG)
3724 {
3725 char buf[1024];
3726 char format[1024];
3727
3728 DBUS_VA_COPY (tmp, args);
3729 snprintf (format, sizeof (format), "%s: %s", s, msg);
3730 vsnprintf(buf, sizeof(buf), format, tmp);
3731 OutputDebugStringA(buf);
3732 va_end (tmp);
3733 }
3734
3735 if (log_flags & DBUS_LOG_FLAGS_STDERR)
3736 {
3737 DBUS_VA_COPY (tmp, args);
3738 fprintf (stderr, "%s[%lu]: %s: ", log_tag, _dbus_pid_for_log (), s);
3739 vfprintf (stderr, msg, tmp);
3740 fprintf (stderr, "\n");
3741 va_end (tmp);
3742 }
3743 }
3744
3745 /** @} end of sysdeps-win */
3746 /* tests in dbus-sysdeps-util.c */
3747