dbus-sysdeps-win.c 96.5 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 3 4 5 6
/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-BUS implementation)
 * 
 * Copyright (C) 2002, 2003  Red Hat, Inc.
 * Copyright (C) 2003 CodeFactory AB
 * 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 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * Licensed under the Academic Free License version 2.1
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * 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 30
#include <config.h>

31 32 33
#define STRSAFE_NO_DEPRECATE

#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 42 43 44
#include "dbus-sysdeps.h"
#include "dbus-threads.h"
#include "dbus-protocol.h"
#include "dbus-string.h"
45
#include "dbus-sysdeps.h"
46 47 48 49 50
#include "dbus-sysdeps-win.h"
#include "dbus-protocol.h"
#include "dbus-hash.h"
#include "dbus-sockets-win.h"
#include "dbus-list.h"
Frank Osterfeld's avatar
Frank Osterfeld committed
51
#include "dbus-nonce.h"
52
#include "dbus-credentials.h"
53 54

#include <windows.h>
55
#include <ws2tcpip.h>
56
#include <wincrypt.h>
57
#include <iphlpapi.h>
58

59
/* Declarations missing in mingw's and windows sdk 7.0 headers */
60 61 62
extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR  StringSid, PSID *Sid);
extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);

63
#include <stdio.h>
Ralf Habacker's avatar
Ralf Habacker committed
64
#include <stdlib.h>
65 66

#include <string.h>
67
#if HAVE_ERRNO_H
68
#include <errno.h>
69
#endif
70 71
#ifndef DBUS_WINCE
#include <mbstring.h>
72 73
#include <sys/stat.h>
#include <sys/types.h>
74
#endif
75

76 77 78 79 80
#ifdef HAVE_WS2TCPIP_H
/* getaddrinfo for Windows CE (and Windows).  */
#include <ws2tcpip.h>
#endif

81 82 83 84
#ifndef O_BINARY
#define O_BINARY 0
#endif

Matt Fischer's avatar
Matt Fischer committed
85 86 87 88 89
#ifndef PROCESS_QUERY_LIMITED_INFORMATION
/* MinGW32 < 4 does not define this value in its headers */
#define PROCESS_QUERY_LIMITED_INFORMATION (0x1000)
#endif

90
typedef int socklen_t;
91

92 93 94 95

void
_dbus_win_set_errno (int err)
{
96 97 98
#ifdef DBUS_WINCE
  SetLastError (err);
#else
99
  errno = err;
100
#endif
101 102
}

103 104 105 106 107 108 109 110 111 112 113 114
static BOOL is_winxp_sp3_or_lower();

/*
 * _MIB_TCPROW_EX and friends are not available in system headers
 *  and are mapped to attribute identical ...OWNER_PID typedefs.
 */
typedef MIB_TCPROW_OWNER_PID _MIB_TCPROW_EX;
typedef MIB_TCPTABLE_OWNER_PID MIB_TCPTABLE_EX;
typedef PMIB_TCPTABLE_OWNER_PID PMIB_TCPTABLE_EX;
typedef DWORD (WINAPI *ProcAllocateAndGetTcpExtTableFromStack)(PMIB_TCPTABLE_EX*,BOOL,HANDLE,DWORD,DWORD);
static ProcAllocateAndGetTcpExtTableFromStack lpfnAllocateAndGetTcpExTableFromStack = NULL;

115 116 117 118 119
/**
 * AllocateAndGetTcpExTableFromStack() is undocumented and not exported,
 * but is the only way to do this in older XP versions.
 * @return true if the procedures could be loaded
 */
Ralf Habacker's avatar
Ralf Habacker committed
120 121
static BOOL
load_ex_ip_helper_procedures(void)
122
{
Ralf Habacker's avatar
Ralf Habacker committed
123 124 125 126 127 128
  HMODULE hModule = LoadLibrary ("iphlpapi.dll");
  if (hModule == NULL)
    {
      _dbus_verbose ("could not load iphlpapi.dll\n");
      return FALSE;
    }
129

Ralf Habacker's avatar
Ralf Habacker committed
130 131 132 133 134 135 136 137
  lpfnAllocateAndGetTcpExTableFromStack = (ProcAllocateAndGetTcpExtTableFromStack)GetProcAddress (hModule, "AllocateAndGetTcpExTableFromStack");
  if (lpfnAllocateAndGetTcpExTableFromStack == NULL)
    {
      _dbus_verbose ("could not find function AllocateAndGetTcpExTableFromStack in iphlpapi.dll\n");
      return FALSE;
    }
  return TRUE;
}
138

Ralf Habacker's avatar
Ralf Habacker committed
139 140 141 142 143 144 145 146
/**
 * get pid from localhost tcp connection using peer_port
 * This function is available on WinXP >= SP3
 * @param peer_port peers tcp port
 * @return process id or 0 if connection has not been found
 */
static dbus_pid_t
get_pid_from_extended_tcp_table(int peer_port)
147 148
{
  dbus_pid_t result;
149
  DWORD errorCode, size = 0, i;
150 151
  MIB_TCPTABLE_OWNER_PID *tcp_table;

152
  if ((errorCode =
153 154 155 156 157 158 159 160 161
       GetExtendedTcpTable (NULL, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) == ERROR_INSUFFICIENT_BUFFER)
    {
      tcp_table = (MIB_TCPTABLE_OWNER_PID *) dbus_malloc (size);
      if (tcp_table == NULL)
        {
          _dbus_verbose ("Error allocating memory\n");
          return 0;
        }
    }
Ralf Habacker's avatar
Ralf Habacker committed
162 163
  else
    {
164
      _dbus_win_warn_win_error ("unexpected error returned from GetExtendedTcpTable", errorCode);
Ralf Habacker's avatar
Ralf Habacker committed
165 166
      return 0;
    }
167

168
  if ((errorCode = GetExtendedTcpTable (tcp_table, &size, TRUE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0)) != NO_ERROR)
169
    {
170
      _dbus_verbose ("Error fetching tcp table %d\n", (int)errorCode);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
      dbus_free (tcp_table);
      return 0;
    }

  result = 0;
  for (i = 0; i < tcp_table->dwNumEntries; i++)
    {
      MIB_TCPROW_OWNER_PID *p = &tcp_table->table[i];
      int local_address = ntohl (p->dwLocalAddr);
      int local_port = ntohs (p->dwLocalPort);
      if (p->dwState == MIB_TCP_STATE_ESTAB
          && local_address == INADDR_LOOPBACK && local_port == peer_port)
         result = p->dwOwningPid;
    }

  dbus_free (tcp_table);
187
  _dbus_verbose ("got pid %lu\n", result);
188 189 190
  return result;
}

Ralf Habacker's avatar
Ralf Habacker committed
191 192 193 194 195 196 197 198 199
/**
 * get pid from localhost tcp connection using peer_port
 * This function is available on all WinXP versions, but
 * not in wine (at least version <= 1.6.0)
 * @param peer_port peers tcp port
 * @return process id or 0 if connection has not been found
 */
static dbus_pid_t
get_pid_from_tcp_ex_table(int peer_port)
200 201
{
  dbus_pid_t result;
202 203
  DWORD errorCode, i;
  PMIB_TCPTABLE_EX tcp_table = NULL;
204 205 206 207 208 209 210 211

  if (!load_ex_ip_helper_procedures ())
    {
      _dbus_verbose
        ("Error not been able to load iphelper procedures\n");
      return 0;
    }

212
  errorCode = lpfnAllocateAndGetTcpExTableFromStack (&tcp_table, TRUE, GetProcessHeap(), 0, 2);
213 214 215 216 217 218 219

  if (errorCode != NO_ERROR)
    {
      _dbus_verbose
        ("Error not been able to call AllocateAndGetTcpExTableFromStack()\n");
      return 0;
    }
220

221
  result = 0;
222
  for (i = 0; i < tcp_table->dwNumEntries; i++)
223
    {
224 225 226
      _MIB_TCPROW_EX *p = &tcp_table->table[i];
      int local_port = ntohs (p->dwLocalPort);
      int local_address = ntohl (p->dwLocalAddr);
227 228
      if (local_address == INADDR_LOOPBACK && local_port == peer_port)
        {
229
          result = p->dwOwningPid;
230 231 232
          break;
        }
    }
Ralf Habacker's avatar
Ralf Habacker committed
233 234

  HeapFree (GetProcessHeap(), 0, tcp_table);
235
  _dbus_verbose ("got pid %lu\n", result);
236 237 238
  return result;
}

239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
/**
 * @brief return peer process id from tcp handle for localhost connections
 * @param handle tcp socket descriptor
 * @return process id or 0 in case the process id could not be fetched
 */
static dbus_pid_t
_dbus_get_peer_pid_from_tcp_handle (int handle)
{
  struct sockaddr_storage addr;
  socklen_t len = sizeof (addr);
  int peer_port;

  dbus_pid_t result;
  dbus_bool_t is_localhost = FALSE;

  getpeername (handle, (struct sockaddr *) &addr, &len);

  if (addr.ss_family == AF_INET)
    {
      struct sockaddr_in *s = (struct sockaddr_in *) &addr;
      peer_port = ntohs (s->sin_port);
Ralf Habacker's avatar
Ralf Habacker committed
260
      is_localhost = (ntohl (s->sin_addr.s_addr) == INADDR_LOOPBACK);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    }
  else if (addr.ss_family == AF_INET6)
    {
      _dbus_verbose ("FIXME [61922]: IPV6 support not working on windows\n");
      return 0;
      /*
         struct sockaddr_in6 *s = (struct sockaddr_in6 * )&addr;
         peer_port = ntohs (s->sin6_port);
         is_localhost = (memcmp(s->sin6_addr.s6_addr, in6addr_loopback.s6_addr, 16) == 0);
         _dbus_verbose ("IPV6 %08x %08x\n", s->sin6_addr.s6_addr, in6addr_loopback.s6_addr);
       */
    }
  else
    {
      _dbus_verbose ("no idea what address family %d is\n", addr.ss_family);
      return 0;
    }

  if (!is_localhost)
    {
      _dbus_verbose ("could not fetch process id from remote process\n");
      return 0;
    }

  if (peer_port == 0)
    {
      _dbus_verbose
        ("Error not been able to fetch tcp peer port from connection\n");
      return 0;
    }

Ralf Habacker's avatar
Ralf Habacker committed
292
  _dbus_verbose ("trying to get peers pid");
293

Ralf Habacker's avatar
Ralf Habacker committed
294
  result = get_pid_from_extended_tcp_table (peer_port);
295
  if (result > 0)
296
      return result;
Ralf Habacker's avatar
Ralf Habacker committed
297
  result = get_pid_from_tcp_ex_table (peer_port);
298 299
  return result;
}
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

/* Convert GetLastError() to a dbus error.  */
const char*
_dbus_win_error_from_last_error (void)
{
  switch (GetLastError())
    {
    case 0:
      return DBUS_ERROR_FAILED;
    
    case ERROR_NO_MORE_FILES:
    case ERROR_TOO_MANY_OPEN_FILES:
      return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */

    case ERROR_ACCESS_DENIED:
    case ERROR_CANNOT_MAKE:
      return DBUS_ERROR_ACCESS_DENIED;

    case ERROR_NOT_ENOUGH_MEMORY:
      return DBUS_ERROR_NO_MEMORY;

    case ERROR_FILE_EXISTS:
      return DBUS_ERROR_FILE_EXISTS;

    case ERROR_FILE_NOT_FOUND:
    case ERROR_PATH_NOT_FOUND:
      return DBUS_ERROR_FILE_NOT_FOUND;
    }
  
  return DBUS_ERROR_FAILED;
}


333
char*
334 335 336 337
_dbus_win_error_string (int error_number)
{
  char *msg;

338 339 340 341 342
  FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_IGNORE_INSERTS |
                  FORMAT_MESSAGE_FROM_SYSTEM,
                  NULL, error_number, 0,
                  (LPSTR) &msg, 0, NULL);
343 344 345 346 347 348 349 350 351

  if (msg[strlen (msg) - 1] == '\n')
    msg[strlen (msg) - 1] = '\0';
  if (msg[strlen (msg) - 1] == '\r')
    msg[strlen (msg) - 1] = '\0';

  return msg;
}

352
void
353 354 355 356 357
_dbus_win_free_error_string (char *string)
{
  LocalFree (string);
}

358 359 360 361 362 363 364 365 366 367
/**
 * Socket interface
 *
 */

/**
 * Thin wrapper around the read() system call that appends
 * the data it reads to the DBusString buffer. It appends
 * up to the given count, and returns the same value
 * and same errno as read(). The only exception is that
368 369 370
 * _dbus_read_socket() handles EINTR for you. 
 * _dbus_read_socket() can return ENOMEM, even though 
 * regular UNIX read doesn't.
371 372 373 374 375 376
 *
 * @param fd the file descriptor to read from
 * @param buffer the buffer to append data to
 * @param count the amount of data to read
 * @returns the number of bytes read or -1
 */
377

378
int
Ralf Habacker's avatar
*...  
Ralf Habacker committed
379
_dbus_read_socket (int               fd,
380 381 382 383 384 385 386 387 388 389 390 391 392
                   DBusString       *buffer,
                   int               count)
{
  int bytes_read;
  int start;
  char *data;

  _dbus_assert (count >= 0);

  start = _dbus_string_get_length (buffer);

  if (!_dbus_string_lengthen (buffer, count))
    {
393
      _dbus_win_set_errno (ENOMEM);
394 395 396 397 398
      return -1;
    }

  data = _dbus_string_get_data_len (buffer, start, count);

Ralf Habacker's avatar
*...  
Ralf Habacker committed
399 400 401 402 403 404 405 406
 again:
 
  _dbus_verbose ("recv: count=%d fd=%d\n", count, fd);
  bytes_read = recv (fd, data, count, 0);
  
  if (bytes_read == SOCKET_ERROR)
	{
	  DBUS_SOCKET_SET_ERRNO();
407
	  _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
Ralf Habacker's avatar
*...  
Ralf Habacker committed
408 409 410 411
	  bytes_read = -1;
	}
	else
	  _dbus_verbose ("recv: = %d\n", bytes_read);
412

Ralf Habacker's avatar
*...  
Ralf Habacker committed
413
  if (bytes_read < 0)
414
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
415 416 417
      if (errno == EINTR)
        goto again;
      else    	
418
        {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
419 420 421
          /* put length back (note that this doesn't actually realloc anything) */
          _dbus_string_set_length (buffer, start);
          return -1;
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
        }
    }
  else
    {
      /* put length back (doesn't actually realloc) */
      _dbus_string_set_length (buffer, start + bytes_read);

#if 0
      if (bytes_read > 0)
        _dbus_verbose_bytes_of_string (buffer, start, bytes_read);
#endif

      return bytes_read;
    }
}

/**
 * Thin wrapper around the write() system call that writes a part of a
 * DBusString and handles EINTR for you.
 * 
 * @param fd the file descriptor to write
 * @param buffer the buffer to write data from
 * @param start the first byte in the buffer to write
 * @param len the number of bytes to try to write
 * @returns the number of bytes written or -1 on error
 */
int
Ralf Habacker's avatar
*...  
Ralf Habacker committed
449
_dbus_write_socket (int               fd,
450 451 452 453 454 455 456 457 458
                    const DBusString *buffer,
                    int               start,
                    int               len)
{
  const char *data;
  int bytes_written;

  data = _dbus_string_get_const_data_len (buffer, start, len);

Ralf Habacker's avatar
*...  
Ralf Habacker committed
459
 again:
460

Ralf Habacker's avatar
*...  
Ralf Habacker committed
461 462 463 464
  _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
  bytes_written = send (fd, data, len, 0);

  if (bytes_written == SOCKET_ERROR)
465
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
466
      DBUS_SOCKET_SET_ERRNO();
467
      _dbus_verbose ("send: failed: %s\n", _dbus_strerror_from_errno ());
Ralf Habacker's avatar
*...  
Ralf Habacker committed
468
      bytes_written = -1;
469
    }
Ralf Habacker's avatar
*...  
Ralf Habacker committed
470 471
    else
      _dbus_verbose ("send: = %d\n", bytes_written);
472

Ralf Habacker's avatar
*...  
Ralf Habacker committed
473 474 475
  if (bytes_written < 0 && errno == EINTR)
    goto again;
    
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
#if 0
  if (bytes_written > 0)
    _dbus_verbose_bytes_of_string (buffer, start, bytes_written);
#endif

  return bytes_written;
}


/**
 * Closes a file descriptor.
 *
 * @param fd the file descriptor
 * @param error error object
 * @returns #FALSE if error set
 */
dbus_bool_t
Ralf Habacker's avatar
*...  
Ralf Habacker committed
493
_dbus_close_socket (int        fd,
494 495
                    DBusError *error)
{
496 497
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

Ralf Habacker's avatar
*...  
Ralf Habacker committed
498 499
 again:
  if (closesocket (fd) == SOCKET_ERROR)
500
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
501 502 503 504 505 506 507
      DBUS_SOCKET_SET_ERRNO ();
      
      if (errno == EINTR)
        goto again;
        
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Could not close socket: socket=%d, , %s",
508
                      fd, _dbus_strerror_from_errno ());
Ralf Habacker's avatar
*...  
Ralf Habacker committed
509
      return FALSE;
510
    }
Ralf Habacker's avatar
*...  
Ralf Habacker committed
511
  _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
512 513

  return TRUE;
514 515 516 517 518 519 520
}

/**
 * Sets the file descriptor to be close
 * on exec. Should be called for all file
 * descriptors in D-Bus code.
 *
521
 * @param handle the Windows HANDLE (a SOCKET is also OK)
522
 */
523 524
static void
_dbus_win_handle_set_close_on_exec (HANDLE handle)
525
{
526 527 528 529 530 531
  if ( !SetHandleInformation( (HANDLE) handle,
                        HANDLE_FLAG_INHERIT | HANDLE_FLAG_PROTECT_FROM_CLOSE,
                        0 /*disable both flags*/ ) )
    {
      _dbus_win_warn_win_error ("Disabling socket handle inheritance failed:", GetLastError());
    }
532 533 534 535 536
}

/**
 * Sets a file descriptor to be nonblocking.
 *
537
 * @param handle the file descriptor.
538 539 540 541 542 543 544 545 546 547 548
 * @param error address of error location.
 * @returns #TRUE on success.
 */
dbus_bool_t
_dbus_set_fd_nonblocking (int             handle,
                          DBusError      *error)
{
  u_long one = 1;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

Ralf Habacker's avatar
*...  
Ralf Habacker committed
549
  if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
550
    {
551 552
      DBUS_SOCKET_SET_ERRNO ();
      dbus_set_error (error, _dbus_error_from_errno (errno),
Ralf Habacker's avatar
*...  
Ralf Habacker committed
553
                      "Failed to set socket %d:%d to nonblocking: %s", handle,
554
                      _dbus_strerror_from_errno ());
Ralf Habacker's avatar
*...  
Ralf Habacker committed
555
      return FALSE;
556 557
    }

558
  return TRUE;
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
}


/**
 * Like _dbus_write() but will use writev() if possible
 * to write both buffers in sequence. The return value
 * is the number of bytes written in the first buffer,
 * plus the number written in the second. If the first
 * buffer is written successfully and an error occurs
 * writing the second, the number of bytes in the first
 * is returned (i.e. the error is ignored), on systems that
 * don't have writev. Handles EINTR for you.
 * The second buffer may be #NULL.
 *
 * @param fd the file descriptor
 * @param buffer1 first buffer
 * @param start1 first byte to write in first buffer
 * @param len1 number of bytes to write from first buffer
 * @param buffer2 second buffer, or #NULL
 * @param start2 first byte to write in second buffer
 * @param len2 number of bytes to write in second buffer
 * @returns total bytes written from both buffers, or -1 on error
 */
int
Ralf Habacker's avatar
*...  
Ralf Habacker committed
583
_dbus_write_socket_two (int               fd,
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
                        const DBusString *buffer1,
                        int               start1,
                        int               len1,
                        const DBusString *buffer2,
                        int               start2,
                        int               len2)
{
  WSABUF vectors[2];
  const char *data1;
  const char *data2;
  int rc;
  DWORD bytes_written;

  _dbus_assert (buffer1 != NULL);
  _dbus_assert (start1 >= 0);
  _dbus_assert (start2 >= 0);
  _dbus_assert (len1 >= 0);
  _dbus_assert (len2 >= 0);


  data1 = _dbus_string_get_const_data_len (buffer1, start1, len1);

  if (buffer2 != NULL)
    data2 = _dbus_string_get_const_data_len (buffer2, start2, len2);
  else
    {
      data2 = NULL;
      start2 = 0;
      len2 = 0;
    }

Ralf Habacker's avatar
*...  
Ralf Habacker committed
615 616 617 618
  vectors[0].buf = (char*) data1;
  vectors[0].len = len1;
  vectors[1].buf = (char*) data2;
  vectors[1].len = len2;
619

Ralf Habacker's avatar
*...  
Ralf Habacker committed
620 621 622 623 624 625 626 627 628 629 630
 again:
 
  _dbus_verbose ("WSASend: len1+2=%d+%d fd=%d\n", len1, len2, fd);
  rc = WSASend (fd, 
                vectors,
                data2 ? 2 : 1, 
                &bytes_written,
                0, 
                NULL, 
                NULL);
                
631
  if (rc == SOCKET_ERROR)
632
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
633
      DBUS_SOCKET_SET_ERRNO ();
634
      _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror_from_errno ());
Ralf Habacker's avatar
*...  
Ralf Habacker committed
635
      bytes_written = -1;
636 637
    }
  else
Ralf Habacker's avatar
*...  
Ralf Habacker committed
638 639 640 641 642 643
    _dbus_verbose ("WSASend: = %ld\n", bytes_written);
    
  if (bytes_written < 0 && errno == EINTR)
    goto again;
      
  return bytes_written;
644 645
}

646 647 648 649 650 651
dbus_bool_t
_dbus_socket_is_invalid (int fd)
{
    return fd == INVALID_SOCKET ? TRUE : FALSE;
}

652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
#if 0

/**
 * Opens the client side of a Windows named pipe. The connection D-BUS
 * file descriptor index is returned. It is set up as nonblocking.
 * 
 * @param path the path to named pipe socket
 * @param error return location for error code
 * @returns connection D-BUS file descriptor or -1 on error
 */
int
_dbus_connect_named_pipe (const char     *path,
                          DBusError      *error)
{
  _dbus_assert_not_reached ("not implemented");
}

#endif

671 672 673 674
/**
 * @returns #FALSE if no memory
 */
dbus_bool_t
675 676 677 678
_dbus_win_startup_winsock (void)
{
  /* Straight from MSDN, deuglified */

679
  /* Protected by _DBUS_LOCK_sysdeps */
680 681 682 683 684 685
  static dbus_bool_t beenhere = FALSE;

  WORD wVersionRequested;
  WSADATA wsaData;
  int err;

686 687 688
  if (!_DBUS_LOCK (sysdeps))
    return FALSE;

689
  if (beenhere)
690
    goto out;
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

  wVersionRequested = MAKEWORD (2, 0);

  err = WSAStartup (wVersionRequested, &wsaData);
  if (err != 0)
    {
      _dbus_assert_not_reached ("Could not initialize WinSock");
      _dbus_abort ();
    }

  /* Confirm that the WinSock DLL supports 2.0.  Note that if the DLL
   * supports versions greater than 2.0 in addition to 2.0, it will
   * still return 2.0 in wVersion since that is the version we
   * requested.
   */
  if (LOBYTE (wsaData.wVersion) != 2 ||
      HIBYTE (wsaData.wVersion) != 0)
    {
      _dbus_assert_not_reached ("No usable WinSock found");
      _dbus_abort ();
    }

  beenhere = TRUE;
714 715 716 717

out:
  _DBUS_UNLOCK (sysdeps);
  return TRUE;
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
}









/************************************************************************
 
 UTF / string code
 
 ************************************************************************/

/**
 * Measure the message length without terminating nul 
 */
int _dbus_printf_string_upper_bound (const char *format,
                                     va_list args)
{
  /* MSVCRT's vsnprintf semantics are a bit different */
741 742
  char buf[1024];
  int bufsize;
743
  int len;
744
  va_list args_copy;
745 746

  bufsize = sizeof (buf);
747 748 749
  DBUS_VA_COPY (args_copy, args);
  len = _vsnprintf (buf, bufsize - 1, format, args_copy);
  va_end (args_copy);
750 751

  while (len == -1) /* try again */
752 753
    {
      char *p;
754 755 756 757

      bufsize *= 2;

      p = malloc (bufsize);
758 759 760 761

      if (p == NULL)
        return -1;

762 763 764
      DBUS_VA_COPY (args_copy, args);
      len = _vsnprintf (p, bufsize - 1, format, args_copy);
      va_end (args_copy);
765
      free (p);
766
    }
767

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
  return len;
}


/**
 * Returns the UTF-16 form of a UTF-8 string. The result should be
 * freed with dbus_free() when no longer needed.
 *
 * @param str the UTF-8 string
 * @param error return location for error code
 */
wchar_t *
_dbus_win_utf8_to_utf16 (const char *str,
                         DBusError  *error)
{
  DBusString s;
  int n;
  wchar_t *retval;

  _dbus_string_init_const (&s, str);

  if (!_dbus_string_validate_utf8 (&s, 0, _dbus_string_get_length (&s)))
    {
      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid UTF-8");
      return NULL;
    }

  n = MultiByteToWideChar (CP_UTF8, 0, str, -1, NULL, 0);

  if (n == 0)
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      return NULL;
    }

  retval = dbus_new (wchar_t, n);

  if (!retval)
    {
      _DBUS_SET_OOM (error);
      return NULL;
    }

  if (MultiByteToWideChar (CP_UTF8, 0, str, -1, retval, n) != n)
    {
      dbus_free (retval);
      dbus_set_error_const (error, DBUS_ERROR_FAILED, "MultiByteToWideChar inconsistency");
      return NULL;
    }

  return retval;
}

/**
 * Returns the UTF-8 form of a UTF-16 string. The result should be
 * freed with dbus_free() when no longer needed.
 *
 * @param str the UTF-16 string
 * @param error return location for error code
 */
char *
_dbus_win_utf16_to_utf8 (const wchar_t *str,
                         DBusError     *error)
{
  int n;
  char *retval;

  n = WideCharToMultiByte (CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);

  if (n == 0)
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      return NULL;
    }

  retval = dbus_malloc (n);

  if (!retval)
    {
      _DBUS_SET_OOM (error);
      return NULL;
    }

  if (WideCharToMultiByte (CP_UTF8, 0, str, -1, retval, n, NULL, NULL) != n)
    {
      dbus_free (retval);
      dbus_set_error_const (error, DBUS_ERROR_FAILED, "WideCharToMultiByte inconsistency");
      return NULL;
    }

  return retval;
}






/************************************************************************
 
 
 ************************************************************************/

dbus_bool_t
_dbus_win_account_to_sid (const wchar_t *waccount,
                          void      	 **ppsid,
                          DBusError 	  *error)
{
  dbus_bool_t retval = FALSE;
  DWORD sid_length, wdomain_length;
  SID_NAME_USE use;
  wchar_t *wdomain;

  *ppsid = NULL;

  sid_length = 0;
  wdomain_length = 0;
  if (!LookupAccountNameW (NULL, waccount, NULL, &sid_length,
                           NULL, &wdomain_length, &use) &&
      GetLastError () != ERROR_INSUFFICIENT_BUFFER)
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      return FALSE;
    }

  *ppsid = dbus_malloc (sid_length);
  if (!*ppsid)
    {
      _DBUS_SET_OOM (error);
      return FALSE;
    }

  wdomain = dbus_new (wchar_t, wdomain_length);
  if (!wdomain)
    {
      _DBUS_SET_OOM (error);
      goto out1;
    }

  if (!LookupAccountNameW (NULL, waccount, (PSID) *ppsid, &sid_length,
                           wdomain, &wdomain_length, &use))
    {
      _dbus_win_set_error_from_win_error (error, GetLastError ());
      goto out2;
    }

  if (!IsValidSid ((PSID) *ppsid))
    {
      dbus_set_error_const (error, DBUS_ERROR_FAILED, "Invalid SID");
      goto out2;
    }

  retval = TRUE;

out2:
  dbus_free (wdomain);
out1:
  if (!retval)
    {
      dbus_free (*ppsid);
      *ppsid = NULL;
    }

  return retval;
}

/** @} end of sysdeps-win */


937 938 939 940 941 942 943 944 945 946 947 948
/**
 * The only reason this is separate from _dbus_getpid() is to allow it
 * on Windows for logging but not for other purposes.
 * 
 * @returns process ID to put in log messages
 */
unsigned long
_dbus_pid_for_log (void)
{
  return _dbus_getpid ();
}

949
#ifndef DBUS_WINCE
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981

static BOOL is_winxp_sp3_or_lower()
{
   OSVERSIONINFOEX osvi;
   DWORDLONG dwlConditionMask = 0;
   int op=VER_LESS_EQUAL;

   // Initialize the OSVERSIONINFOEX structure.

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
   osvi.dwMajorVersion = 5;
   osvi.dwMinorVersion = 1;
   osvi.wServicePackMajor = 3;
   osvi.wServicePackMinor = 0;

   // Initialize the condition mask.

   VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, op );
   VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, op );
   VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMAJOR, op );
   VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMINOR, op );

   // Perform the test.

   return VerifyVersionInfo(
      &osvi,
      VER_MAJORVERSION | VER_MINORVERSION |
      VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR,
      dwlConditionMask);
}

982
/** Gets our SID
983
 * @param sid points to sid buffer, need to be freed with LocalFree()
984
 * @param process_id the process id for which the sid should be returned (use 0 for current process)
985 986
 * @returns process sid
 */
Ralf Habacker's avatar
Ralf Habacker committed
987
dbus_bool_t
988
_dbus_getsid(char **sid, dbus_pid_t process_id)
989
{
990
  HANDLE process_token = INVALID_HANDLE_VALUE;
991 992 993 994
  TOKEN_USER *token_user = NULL;
  DWORD n;
  PSID psid;
  int retval = FALSE;
995

996 997 998 999 1000 1001 1002
  HANDLE process_handle;
  if (process_id == 0)
    process_handle = GetCurrentProcess();
  else if (is_winxp_sp3_or_lower())
    process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, process_id);
  else
    process_handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id);
1003 1004

  if (!OpenProcessToken (process_handle, TOKEN_QUERY, &process_token))
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    {
      _dbus_win_warn_win_error ("OpenProcessToken failed", GetLastError ());
      goto failed;
    }
  if ((!GetTokenInformation (process_token, TokenUser, NULL, 0, &n)
            && GetLastError () != ERROR_INSUFFICIENT_BUFFER)
           || (token_user = alloca (n)) == NULL
           || !GetTokenInformation (process_token, TokenUser, token_user, n, &n))
    {
      _dbus_win_warn_win_error ("GetTokenInformation failed", GetLastError ());
      goto failed;
    }
  psid = token_user->User.Sid;
  if (!IsValidSid (psid))
    {
      _dbus_verbose("%s invalid sid\n",__FUNCTION__);
      goto failed;
    }
  if (!ConvertSidToStringSidA (psid, sid))
    {
      _dbus_verbose("%s invalid sid\n",__FUNCTION__);
      goto failed;
    }
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1028
//okay:
1029
  retval = TRUE;
Ralf Habacker's avatar
Ralf Habacker committed
1030

1031
failed:
1032
  CloseHandle (process_handle);
1033
  if (process_token != INVALID_HANDLE_VALUE)
1034 1035
    CloseHandle (process_token);

1036
  _dbus_verbose("_dbus_getsid() got '%s' and returns %d\n", *sid, retval);
1037 1038
  return retval;
}
1039
#endif
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
/************************************************************************
 
 pipes
 
 ************************************************************************/

/**
 * Creates a full-duplex pipe (as in socketpair()).
 * Sets both ends of the pipe nonblocking.
 *
 * @param fd1 return location for one end
 * @param fd2 return location for the other end
 * @param blocking #TRUE if pipe should be blocking
 * @param error error return
 * @returns #FALSE on failure (if error is set)
 */
dbus_bool_t
_dbus_full_duplex_pipe (int        *fd1,
                        int        *fd2,
                        dbus_bool_t blocking,
                        DBusError  *error)
{
  SOCKET temp, socket1 = -1, socket2 = -1;
  struct sockaddr_in saddr;
  int len;
  u_long arg;

1068 1069 1070 1071 1072
  if (!_dbus_win_startup_winsock ())
    {
      _DBUS_SET_OOM (error);
      return FALSE;
    }
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085

  temp = socket (AF_INET, SOCK_STREAM, 0);
  if (temp == INVALID_SOCKET)
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

  _DBUS_ZERO (saddr);
  saddr.sin_family = AF_INET;
  saddr.sin_port = 0;
  saddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);

1086
  if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)) == SOCKET_ERROR)
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

  if (listen (temp, 1) == SOCKET_ERROR)
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

  len = sizeof (saddr);
1099
  if (getsockname (temp, (struct sockaddr *)&saddr, &len) == SOCKET_ERROR)
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

  socket1 = socket (AF_INET, SOCK_STREAM, 0);
  if (socket1 == INVALID_SOCKET)
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

1112
  if (connect (socket1, (struct sockaddr  *)&saddr, len) == SOCKET_ERROR)
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out1;
    }

  socket2 = accept (temp, (struct sockaddr *) &saddr, &len);
  if (socket2 == INVALID_SOCKET)
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out1;
    }

1125
  if (!blocking)
1126
    {
1127
      arg = 1;
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
      if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
        {
          DBUS_SOCKET_SET_ERRNO ();
          goto out2;
        }

      arg = 1;
      if (ioctlsocket (socket2, FIONBIO, &arg) == SOCKET_ERROR)
        {
          DBUS_SOCKET_SET_ERRNO ();
          goto out2;
        }
    }

1142 1143
  *fd1 = socket1;
  *fd2 = socket2;
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

  _dbus_verbose ("full-duplex pipe %d:%d <-> %d:%d\n",
                 *fd1, socket1, *fd2, socket2);

  closesocket (temp);

  return TRUE;

out2:
  closesocket (socket2);
out1:
  closesocket (socket1);
out0:
  closesocket (temp);

  dbus_set_error (error, _dbus_error_from_errno (errno),
                  "Could not setup socket pair: %s",
1161
                  _dbus_strerror_from_errno ());
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

  return FALSE;
}

/**
 * Wrapper for poll().
 *
 * @param fds the file descriptors to poll
 * @param n_fds number of descriptors in the array
 * @param timeout_milliseconds timeout or -1 for infinite
 * @returns numbers of fds with revents, or <0 on error
 */
int
_dbus_poll (DBusPollFD *fds,
            int         n_fds,
            int         timeout_milliseconds)
{
1179 1180 1181 1182
#define USE_CHRIS_IMPL 0

#if USE_CHRIS_IMPL

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
#define DBUS_POLL_CHAR_BUFFER_SIZE 2000
  char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
  char *msgp;

  int ret = 0;
  int i;
  struct timeval tv;
  int ready;

#define DBUS_STACK_WSAEVENTS 256
  WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS];
  WSAEVENT *pEvents = NULL;
  if (n_fds > DBUS_STACK_WSAEVENTS)
    pEvents = calloc(sizeof(WSAEVENT), n_fds);
  else
    pEvents = eventsOnStack;


#ifdef DBUS_ENABLE_VERBOSE_MODE
  msgp = msg;
  msgp += sprintf (msgp, "WSAEventSelect: to=%d\n\t", timeout_milliseconds);
  for (i = 0; i < n_fds; i++)
    {
      DBusPollFD *fdp = &fds[i];


      if (fdp->events & _DBUS_POLLIN)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1210
        msgp += sprintf (msgp, "R:%d ", fdp->fd);
1211 1212

      if (fdp->events & _DBUS_POLLOUT)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1213
        msgp += sprintf (msgp, "W:%d ", fdp->fd);
1214

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1215
      msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

      // FIXME: more robust code for long  msg
      //        create on heap when msg[] becomes too small
      if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
        {
          _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
        }
    }

  msgp += sprintf (msgp, "\n");
  _dbus_verbose ("%s",msg);
#endif
  for (i = 0; i < n_fds; i++)
    {
      DBusPollFD *fdp = &fds[i];
      WSAEVENT ev;
      long lNetworkEvents = FD_OOB;

      ev = WSACreateEvent();

      if (fdp->events & _DBUS_POLLIN)
        lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE;

      if (fdp->events & _DBUS_POLLOUT)
        lNetworkEvents |= FD_WRITE | FD_CONNECT;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1242
      WSAEventSelect(fdp->fd, ev, lNetworkEvents);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

      pEvents[i] = ev;
    }


  ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE);

  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
    {
      DBUS_SOCKET_SET_ERRNO ();
1253
      if (errno != WSAEWOULDBLOCK)
1254
        _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", _dbus_strerror_from_errno ());
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
      ret = -1;
    }
  else if (ready == WSA_WAIT_TIMEOUT)
    {
      _dbus_verbose ("WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n");
      ret = 0;
    }
  else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds))
    {
      msgp = msg;
      msgp += sprintf (msgp, "WSAWaitForMultipleEvents: =%d\n\t", ready);

      for (i = 0; i < n_fds; i++)
        {
          DBusPollFD *fdp = &fds[i];
          WSANETWORKEVENTS ne;

          fdp->revents = 0;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1274
          WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

          if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
            fdp->revents |= _DBUS_POLLIN;

          if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
            fdp->revents |= _DBUS_POLLOUT;

          if (ne.lNetworkEvents & (FD_OOB))
            fdp->revents |= _DBUS_POLLERR;

          if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE))
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1286
              msgp += sprintf (msgp, "R:%d ", fdp->fd);
1287 1288

          if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT))
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1289
              msgp += sprintf (msgp, "W:%d ", fdp->fd);
1290 1291

          if (ne.lNetworkEvents & (FD_OOB))
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1292
              msgp += sprintf (msgp, "E:%d ", fdp->fd);
1293 1294 1295 1296 1297 1298

          msgp += sprintf (msgp, "lNetworkEvents:%d ", ne.lNetworkEvents);

          if(ne.lNetworkEvents)
            ret++;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1299
          WSAEventSelect(fdp->fd, pEvents[i], 0);
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
        }

      msgp += sprintf (msgp, "\n");
      _dbus_verbose ("%s",msg);
    }
  else
    {
      _dbus_verbose ("WSAWaitForMultipleEvents: failed for unknown reason!");
      ret = -1;
    }

  for(i = 0; i < n_fds; i++)
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1313 1314
      WSACloseEvent(pEvents[i]);
    }
1315

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1316 1317
  if (n_fds > DBUS_STACK_WSAEVENTS)
    free(pEvents);
1318

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1319 1320
  return ret;

1321
#else   /* USE_CHRIS_IMPL */
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

#define DBUS_POLL_CHAR_BUFFER_SIZE 2000
  char msg[DBUS_POLL_CHAR_BUFFER_SIZE];
  char *msgp;

  fd_set read_set, write_set, err_set;
  int max_fd = 0;
  int i;
  struct timeval tv;
  int ready;

  FD_ZERO (&read_set);
  FD_ZERO (&write_set);
  FD_ZERO (&err_set);


#ifdef DBUS_ENABLE_VERBOSE_MODE
  msgp = msg;
  msgp += sprintf (msgp, "select: to=%d\n\t", timeout_milliseconds);
  for (i = 0; i < n_fds; i++)
    {
      DBusPollFD *fdp = &fds[i];


      if (fdp->events & _DBUS_POLLIN)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1347
        msgp += sprintf (msgp, "R:%d ", fdp->fd);
1348 1349

      if (fdp->events & _DBUS_POLLOUT)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1350
        msgp += sprintf (msgp, "W:%d ", fdp->fd);
1351

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1352
      msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

      // FIXME: more robust code for long  msg
      //        create on heap when msg[] becomes too small
      if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE)
        {
          _dbus_assert_not_reached ("buffer overflow in _dbus_poll");
        }
    }

  msgp += sprintf (msgp, "\n");
  _dbus_verbose ("%s",msg);
#endif
  for (i = 0; i < n_fds; i++)
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1367
      DBusPollFD *fdp = &fds[i]; 
1368 1369

      if (fdp->events & _DBUS_POLLIN)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1370
        FD_SET (fdp->fd, &read_set);
1371 1372

      if (fdp->events & _DBUS_POLLOUT)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1373
        FD_SET (fdp->fd, &write_set);
1374

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1375
      FD_SET (fdp->fd, &err_set);
1376

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1377
      max_fd = MAX (max_fd, fdp->fd);
1378 1379
    }

1380 1381 1382
  // Avoid random lockups with send(), for lack of a better solution so far
  tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000;
  tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000;
1383

1384
  ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv);
1385 1386 1387 1388

  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
    {
      DBUS_SOCKET_SET_ERRNO ();
1389
      if (errno != WSAEWOULDBLOCK)
1390
        _dbus_verbose ("select: failed: %s\n", _dbus_strerror_from_errno ());
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    }
  else if (ready == 0)
    _dbus_verbose ("select: = 0\n");
  else
    if (ready > 0)
      {
#ifdef DBUS_ENABLE_VERBOSE_MODE
        msgp = msg;
        msgp += sprintf (msgp, "select: = %d:\n\t", ready);

        for (i = 0; i < n_fds; i++)
          {
            DBusPollFD *fdp = &fds[i];

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1405 1406
            if (FD_ISSET (fdp->fd, &read_set))
              msgp += sprintf (msgp, "R:%d ", fdp->fd);
1407

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1408 1409
            if (FD_ISSET (fdp->fd, &write_set))
              msgp += sprintf (msgp, "W:%d ", fdp->fd);
1410

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1411 1412
            if (FD_ISSET (fdp->fd, &err_set))
              msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
          }
        msgp += sprintf (msgp, "\n");
        _dbus_verbose ("%s",msg);
#endif

        for (i = 0; i < n_fds; i++)
          {
            DBusPollFD *fdp = &fds[i];

            fdp->revents = 0;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1424
            if (FD_ISSET (fdp->fd, &read_set))
1425 1426
              fdp->revents |= _DBUS_POLLIN;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1427
            if (FD_ISSET (fdp->fd, &write_set))
1428 1429
              fdp->revents |= _DBUS_POLLOUT;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1430
            if (FD_ISSET (fdp->fd, &err_set))
1431 1432 1433 1434
              fdp->revents |= _DBUS_POLLERR;
          }
      }
  return ready;
1435
#endif  /* USE_CHRIS_IMPL */
1436 1437
}

1438 1439 1440 1441 1442 1443 1444 1445



/******************************************************************************
 
Original CVS version of dbus-sysdeps.c
 
******************************************************************************/
1446
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
/* dbus-sysdeps.c Wrappers around system/libc features (internal to D-Bus implementation)
 * 
 * Copyright (C) 2002, 2003  Red Hat, Inc.
 * Copyright (C) 2003 CodeFactory AB
 * Copyright (C) 2005 Novell, Inc.
 *
 * Licensed under the Academic Free License version 2.1
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
1467
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
 *
 */


/**
 * Exit the process, returning the given value.
 *
 * @param code the exit code
 */
void
_dbus_exit (int code)
{
  _exit (code);
}

/**
 * Creates a socket and connects to a socket at the given host 
 * and port. The connection fd is returned, and is set up as
 * nonblocking.
 *
1488 1489 1490
 * @param host the host name to connect to
 * @param port the port to connect to
 * @param family the address family to listen on, NULL for all
1491 1492 1493 1494 1495
 * @param error return location for error code
 * @returns connection file descriptor or -1 on error
 */
int
_dbus_connect_tcp_socket (const char     *host,
1496 1497
                          const char     *port,
                          const char     *family,
1498
                          DBusError      *error)
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
{
  return _dbus_connect_tcp_socket_with_nonce (host, port, family, (const char*)NULL, error);
}

int
_dbus_connect_tcp_socket_with_nonce (const char     *host,
                                     const char     *port,
                                     const char     *family,
                                     const char     *noncefile,
                                     DBusError      *error)
1509
{
1510 1511 1512
  int fd = -1, res;
  struct addrinfo hints;
  struct addrinfo *ai, *tmp;
1513 1514 1515

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

1516 1517 1518 1519 1520
  if (!_dbus_win_startup_winsock ())
    {
      _DBUS_SET_OOM (error);
      return -1;
    }
1521

1522 1523 1524 1525 1526 1527 1528 1529 1530
  _DBUS_ZERO (hints);

  if (!family)
    hints.ai_family = AF_UNSPEC;
  else if (!strcmp(family, "ipv4"))
    hints.ai_family = AF_INET;
  else if (!strcmp(family, "ipv6"))
    hints.ai_family = AF_INET6;
  else
1531
    {
1532
      dbus_set_error (error,
1533
                      DBUS_ERROR_INVALID_ARGS,
1534 1535
                      "Unknown address family %s", family);
      return -1;
1536
    }
1537 1538 1539 1540 1541 1542 1543
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_socktype = SOCK_STREAM;
#ifdef AI_ADDRCONFIG
  hints.ai_flags = AI_ADDRCONFIG;
#else
  hints.ai_flags = 0;
#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 1552 1553
      return -1;
    }

1554 1555
  tmp = ai;
  while (tmp)
1556
    {
1557
      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) == INVALID_SOCKET)
1558
        {
1559 1560 1561 1562 1563
          DBUS_SOCKET_SET_ERRNO ();
          dbus_set_error (error,
                          _dbus_error_from_errno (errno),
                          "Failed to open socket: %s",
                          _dbus_strerror_from_errno ());
1564 1565 1566 1567
          freeaddrinfo(ai);
          return -1;
        }
      _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1568

1569
      if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
1570
        {
1571
          DBUS_SOCKET_SET_ERRNO ();
1572
          closesocket(fd);
1573
          fd = -1;
1574 1575 1576 1577 1578 1579 1580
          tmp = tmp->ai_next;
          continue;
        }

      break;
    }
  freeaddrinfo(ai);
1581

1582 1583 1584 1585 1586
  if (fd == -1)
    {
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to connect to socket \"%s:%s\" %s",
1587
                      host, port, _dbus_strerror_from_errno ());
1588 1589 1590
      return -1;
    }

1591
  if (noncefile != NULL)
1592 1593 1594 1595 1596 1597 1598 1599 1600
    {
      DBusString noncefileStr;
      dbus_bool_t ret;
      if (!_dbus_string_init (&noncefileStr) ||
          !_dbus_string_append(&noncefileStr, noncefile))
        {
          closesocket (fd);
          dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
          return -1;
1601
        }
1602 1603

      ret = _dbus_send_nonce (fd, &noncefileStr, error);
1604

1605 1606 1607
      _dbus_string_free (&noncefileStr);

      if (!ret)
1608 1609
        {
          closesocket (fd);
1610 1611 1612
          return -1;
        }
    }
1613

1614 1615
  /* Every SOCKET is also a HANDLE. */
  _dbus_win_handle_set_close_on_exec ((HANDLE) fd);