dbus-sysdeps-win.c 89.9 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 3 4 5 6 7
/* 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.
 * Copyright (C) 2006 Ralf Habacker <ralf.habacker@freenet.de>
8
 * Copyright (C) 2006 Peter Kümmel  <syntheticpp@gmx.net>
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Copyright (C) 2006 Christian Ehrlicher <ch.ehrlicher@gmx.de>
 *
 * 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 31
#define STRSAFE_NO_DEPRECATE

#ifndef DBUS_WINCE
32
#ifndef _WIN32_WINNT
33
#define _WIN32_WINNT 0x0501
34
#endif
35
#endif
36 37 38 39 40 41 42 43 44 45 46

#include "dbus-internals.h"
#include "dbus-sysdeps.h"
#include "dbus-threads.h"
#include "dbus-protocol.h"
#include "dbus-string.h"
#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
47
#include "dbus-nonce.h"
48
#include "dbus-credentials.h"
49 50

#include <windows.h>
51
#include <ws2tcpip.h>
52 53
#include <wincrypt.h>

54 55 56 57
/* Declarations missing in mingw's headers */
extern BOOL WINAPI ConvertStringSidToSidA (LPCSTR  StringSid, PSID *Sid);
extern BOOL WINAPI ConvertSidToStringSidA (PSID Sid, LPSTR *StringSid);

58 59 60
#include <fcntl.h>

#include <process.h>
61
#include <stdio.h>
62 63 64
#include <io.h>

#include <string.h>
65
#include <mbstring.h>
66
#include <errno.h>
67 68 69
#include <sys/stat.h>
#include <sys/types.h>

70 71 72 73 74 75 76 77 78 79
#ifdef HAVE_WSPIAPI_H
// needed for w2k compatibility (getaddrinfo/freeaddrinfo/getnameinfo)
#ifdef __GNUC__
#define _inline
#include "wspiapi.h"
#else
#include <wspiapi.h>
#endif
#endif // HAVE_WSPIAPI_H

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

84
typedef int socklen_t;
85

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
static char*
_dbus_win_error_string (int error_number)
{
  char *msg;

  FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER |
                 FORMAT_MESSAGE_IGNORE_INSERTS |
                 FORMAT_MESSAGE_FROM_SYSTEM,
                 NULL, error_number, 0,
                 (LPSTR) &msg, 0, NULL);

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

  return msg;
}

static void
_dbus_win_free_error_string (char *string)
{
  LocalFree (string);
}

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
/**
 * 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
 * _dbus_read() handles EINTR for you. _dbus_read() can
 * return ENOMEM, even though regular UNIX read doesn't.
 *
 * @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
 */
129

130
int
Ralf Habacker's avatar
*...  
Ralf Habacker committed
131
_dbus_read_socket (int               fd,
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
                   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))
    {
      errno = ENOMEM;
      return -1;
    }

  data = _dbus_string_get_data_len (buffer, start, count);

Ralf Habacker's avatar
*...  
Ralf Habacker committed
151 152 153 154 155 156 157 158
 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();
159
	  _dbus_verbose ("recv: failed: %s (%d)\n", _dbus_strerror (errno), errno);
Ralf Habacker's avatar
*...  
Ralf Habacker committed
160 161 162 163
	  bytes_read = -1;
	}
	else
	  _dbus_verbose ("recv: = %d\n", bytes_read);
164

Ralf Habacker's avatar
*...  
Ralf Habacker committed
165
  if (bytes_read < 0)
166
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
167 168 169
      if (errno == EINTR)
        goto again;
      else    	
170
        {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
171 172 173
          /* put length back (note that this doesn't actually realloc anything) */
          _dbus_string_set_length (buffer, start);
          return -1;
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        }
    }
  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
201
_dbus_write_socket (int               fd,
202 203 204 205 206 207 208 209 210
                    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
211
 again:
212

Ralf Habacker's avatar
*...  
Ralf Habacker committed
213 214 215 216
  _dbus_verbose ("send: len=%d fd=%d\n", len, fd);
  bytes_written = send (fd, data, len, 0);

  if (bytes_written == SOCKET_ERROR)
217
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
218 219 220
      DBUS_SOCKET_SET_ERRNO();
      _dbus_verbose ("send: failed: %s\n", _dbus_strerror (errno));
      bytes_written = -1;
221
    }
Ralf Habacker's avatar
*...  
Ralf Habacker committed
222 223
    else
      _dbus_verbose ("send: = %d\n", bytes_written);
224

Ralf Habacker's avatar
*...  
Ralf Habacker committed
225 226 227
  if (bytes_written < 0 && errno == EINTR)
    goto again;
    
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
#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
245
_dbus_close_socket (int        fd,
246 247
                    DBusError *error)
{
248 249
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

Ralf Habacker's avatar
*...  
Ralf Habacker committed
250 251
 again:
  if (closesocket (fd) == SOCKET_ERROR)
252
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
253 254 255 256 257 258 259 260 261
      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",
                      fd, _dbus_strerror (errno));
      return FALSE;
262
    }
Ralf Habacker's avatar
*...  
Ralf Habacker committed
263
  _dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
264 265

  return TRUE;
266 267 268 269 270 271 272 273 274 275 276 277
}

/**
 * Sets the file descriptor to be close
 * on exec. Should be called for all file
 * descriptors in D-Bus code.
 *
 * @param fd the file descriptor
 */
void
_dbus_fd_set_close_on_exec (int handle)
{
278 279 280 281 282 283
  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());
    }
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
}

/**
 * Sets a file descriptor to be nonblocking.
 *
 * @param fd the file descriptor.
 * @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
301
  if (ioctlsocket (handle, FIONBIO, &one) == SOCKET_ERROR)
302
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
303 304 305 306
      dbus_set_error (error, _dbus_error_from_errno (WSAGetLastError ()),
                      "Failed to set socket %d:%d to nonblocking: %s", handle,
                      _dbus_strerror (WSAGetLastError ()));
      return FALSE;
307 308
    }

309
  return TRUE;
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
}


/**
 * 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
334
_dbus_write_socket_two (int               fd,
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
                        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
366 367 368 369
  vectors[0].buf = (char*) data1;
  vectors[0].len = len1;
  vectors[1].buf = (char*) data2;
  vectors[1].len = len2;
370

Ralf Habacker's avatar
*...  
Ralf Habacker committed
371 372 373 374 375 376 377 378 379 380 381 382
 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);
                
  if (rc < 0)
383
    {
Ralf Habacker's avatar
*...  
Ralf Habacker committed
384 385 386
      DBUS_SOCKET_SET_ERRNO ();
      _dbus_verbose ("WSASend: failed: %s\n", _dbus_strerror (errno));
      bytes_written = -1;
387 388
    }
  else
Ralf Habacker's avatar
*...  
Ralf Habacker committed
389 390 391 392 393 394
    _dbus_verbose ("WSASend: = %ld\n", bytes_written);
    
  if (bytes_written < 0 && errno == EINTR)
    goto again;
      
  return bytes_written;
395 396
}

397 398 399 400 401 402
dbus_bool_t
_dbus_socket_is_invalid (int fd)
{
    return fd == INVALID_SOCKET ? TRUE : FALSE;
}

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 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 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
#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



void
_dbus_win_startup_winsock (void)
{
  /* Straight from MSDN, deuglified */

  static dbus_bool_t beenhere = FALSE;

  WORD wVersionRequested;
  WSADATA wsaData;
  int err;

  if (beenhere)
    return;

  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;
}









/************************************************************************
 
 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 */
483 484
  char buf[1024];
  int bufsize;
485
  int len;
486 487 488 489 490

  bufsize = sizeof (buf);
  len = _vsnprintf (buf, bufsize - 1, format, args);

  while (len == -1) /* try again */
491 492
    {
      char *p;
493 494 495 496 497 498

      bufsize *= 2;

      p = malloc (bufsize);
      len = _vsnprintf (p, bufsize - 1, format, args);
      free (p);
499
    }
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
  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 */


670 671 672 673 674 675 676 677 678 679 680 681
/**
 * 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 ();
}

682 683 684 685
/** Gets our SID
 * @param points to sid buffer, need to be freed with LocalFree()
 * @returns process sid
 */
Tor Lillqvist's avatar
Tor Lillqvist committed
686
static dbus_bool_t
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
_dbus_getsid(char **sid)
{
  HANDLE process_token = NULL;
  TOKEN_USER *token_user = NULL;
  DWORD n;
  PSID psid;
  int retval = FALSE;
  
  if (!OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &process_token)) 
    {
      _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
719
//okay:
720
  retval = TRUE;
Ralf Habacker's avatar
Ralf Habacker committed
721

722 723 724 725 726 727 728
failed:
  if (process_token != NULL)
    CloseHandle (process_token);

  _dbus_verbose("_dbus_getsid() returns %d\n",retval);
  return retval;
}
729

730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 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
/************************************************************************
 
 pipes
 
 ************************************************************************/

/**
 * Creates a full-duplex pipe (as in socketpair()).
 * Sets both ends of the pipe nonblocking.
 *
 * @todo libdbus only uses this for the debug-pipe server, so in
 * principle it could be in dbus-sysdeps-util.c, except that
 * dbus-sysdeps-util.c isn't in libdbus when tests are enabled and the
 * debug-pipe server is used.
 * 
 * @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;
  fd_set read_set, write_set;
  struct timeval tv;

  _dbus_win_startup_winsock ();

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

  arg = 1;
  if (ioctlsocket (temp, FIONBIO, &arg) == SOCKET_ERROR)
    {
      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);

  if (bind (temp, (struct sockaddr *)&saddr, sizeof (saddr)))
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

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

  len = sizeof (saddr);
  if (getsockname (temp, (struct sockaddr *)&saddr, &len))
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out0;
    }

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

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

  if (connect (socket1, (struct sockaddr  *)&saddr, len) != SOCKET_ERROR ||
      WSAGetLastError () != WSAEWOULDBLOCK)
    {
821
      DBUS_SOCKET_SET_ERRNO ();
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
      goto out1;
    }

  FD_ZERO (&read_set);
  FD_SET (temp, &read_set);

  tv.tv_sec = 0;
  tv.tv_usec = 0;

  if (select (0, &read_set, NULL, NULL, NULL) == SOCKET_ERROR)
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out1;
    }

  _dbus_assert (FD_ISSET (temp, &read_set));

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

  FD_ZERO (&write_set);
  FD_SET (socket1, &write_set);

  tv.tv_sec = 0;
  tv.tv_usec = 0;

  if (select (0, NULL, &write_set, NULL, NULL) == SOCKET_ERROR)
    {
      DBUS_SOCKET_SET_ERRNO ();
      goto out2;
    }

  _dbus_assert (FD_ISSET (socket1, &write_set));

  if (blocking)
    {
      arg = 0;
      if (ioctlsocket (socket1, FIONBIO, &arg) == SOCKET_ERROR)
        {
          DBUS_SOCKET_SET_ERRNO ();
          goto out2;
        }

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

886 887
  *fd1 = socket1;
  *fd2 = socket2;
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

  _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",
                  _dbus_strerror (errno));

  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)
{
923 924 925 926
#define USE_CHRIS_IMPL 0

#if USE_CHRIS_IMPL

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
#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++)
    {
      static dbus_bool_t warned = FALSE;
      DBusPollFD *fdp = &fds[i];


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

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

Ralf Habacker's avatar
*...  
Ralf Habacker committed
960
      msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

      // 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
987
      WSAEventSelect(fdp->fd, ev, lNetworkEvents);
988 989 990 991 992 993 994 995 996 997

      pEvents[i] = ev;
    }


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

  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
    {
      DBUS_SOCKET_SET_ERRNO ();
998
      if (errno != WSAEWOULDBLOCK)
999
        _dbus_verbose ("WSAWaitForMultipleEvents: failed: %s\n", strerror (errno));
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
      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
1019
          WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne);
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

          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
1031
              msgp += sprintf (msgp, "R:%d ", fdp->fd);
1032 1033

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

          if (ne.lNetworkEvents & (FD_OOB))
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1037
              msgp += sprintf (msgp, "E:%d ", fdp->fd);
1038 1039 1040 1041 1042 1043

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

          if(ne.lNetworkEvents)
            ret++;

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1044
          WSAEventSelect(fdp->fd, pEvents[i], 0);
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
        }

      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
1058 1059
      WSACloseEvent(pEvents[i]);
    }
1060

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1061 1062
  if (n_fds > DBUS_STACK_WSAEVENTS)
    free(pEvents);
1063

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1064 1065
  return ret;

1066
#else   /* USE_CHRIS_IMPL */
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

#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++)
    {
      static dbus_bool_t warned = FALSE;
      DBusPollFD *fdp = &fds[i];


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

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

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1098
      msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

      // 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
1113
      DBusPollFD *fdp = &fds[i]; 
1114 1115

      if (fdp->events & _DBUS_POLLIN)
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1116
        FD_SET (fdp->fd, &read_set);
1117 1118

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

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

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1123
      max_fd = MAX (max_fd, fdp->fd);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    }


  tv.tv_sec = timeout_milliseconds / 1000;
  tv.tv_usec = (timeout_milliseconds % 1000) * 1000;

  ready = select (max_fd + 1, &read_set, &write_set, &err_set,
                  timeout_milliseconds < 0 ? NULL : &tv);

  if (DBUS_SOCKET_API_RETURNS_ERROR (ready))
    {
      DBUS_SOCKET_SET_ERRNO ();
1136
      if (errno != WSAEWOULDBLOCK)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        _dbus_verbose ("select: failed: %s\n", _dbus_strerror (errno));
    }
  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
1152 1153
            if (FD_ISSET (fdp->fd, &read_set))
              msgp += sprintf (msgp, "R:%d ", fdp->fd);
1154

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

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1158 1159
            if (FD_ISSET (fdp->fd, &err_set))
              msgp += sprintf (msgp, "E:%d\n\t", fdp->fd);
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
          }
        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
1171
            if (FD_ISSET (fdp->fd, &read_set))
1172 1173
              fdp->revents |= _DBUS_POLLIN;

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

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1177
            if (FD_ISSET (fdp->fd, &err_set))
1178 1179 1180 1181
              fdp->revents |= _DBUS_POLLERR;
          }
      }
  return ready;
1182
#endif  /* USE_CHRIS_IMPL */
1183 1184
}

1185 1186 1187 1188 1189 1190 1191 1192



/******************************************************************************
 
Original CVS version of dbus-sysdeps.c
 
******************************************************************************/
1193
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
/* 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
1214
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
 *
 */


/**
 * 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.
 *
1235 1236 1237
 * @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
1238 1239 1240 1241 1242
 * @param error return location for error code
 * @returns connection file descriptor or -1 on error
 */
int
_dbus_connect_tcp_socket (const char     *host,
1243 1244
                          const char     *port,
                          const char     *family,
1245
                          DBusError      *error)
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
{
  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)
1256
{
1257 1258 1259
  int fd = -1, res;
  struct addrinfo hints;
  struct addrinfo *ai, *tmp;
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  _dbus_win_startup_winsock ();

  fd = socket (AF_INET, SOCK_STREAM, 0);

  if (DBUS_SOCKET_IS_INVALID (fd))
    {
      DBUS_SOCKET_SET_ERRNO ();
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to create socket: %s",
                      _dbus_strerror (errno));

      return -1;
    }

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  _DBUS_ASSERT_ERROR_IS_CLEAR(error);

  _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
1289
    {
1290 1291 1292 1293
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Unknown address family %s", family);
      return -1;
1294
    }
1295 1296 1297 1298 1299 1300 1301
  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_socktype = SOCK_STREAM;
#ifdef AI_ADDRCONFIG
  hints.ai_flags = AI_ADDRCONFIG;
#else
  hints.ai_flags = 0;
#endif
1302

1303
  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0)
1304 1305 1306
    {
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
1307 1308 1309
                      "Failed to lookup host/port: \"%s:%s\": %s (%d)",
                      host, port, gai_strerror(res), res);
      closesocket (fd);
1310 1311 1312
      return -1;
    }

1313 1314
  tmp = ai;
  while (tmp)
1315
    {
1316 1317 1318
      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
        {
          freeaddrinfo(ai);
1319 1320
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
1321 1322 1323 1324 1325
                         "Failed to open socket: %s",
                         _dbus_strerror (errno));
          return -1;
        }
      _DBUS_ASSERT_ERROR_IS_CLEAR(error);
1326

1327
      if (connect (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) != 0)
1328 1329
        {
          closesocket(fd);
1330
      fd = -1;
1331 1332 1333 1334 1335 1336 1337
          tmp = tmp->ai_next;
          continue;
        }

      break;
    }
  freeaddrinfo(ai);
1338

1339 1340 1341 1342 1343 1344
  if (fd == -1)
    {
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to connect to socket \"%s:%s\" %s",
                      host, port, _dbus_strerror(errno));
1345 1346 1347
      return -1;
    }

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
  if ( noncefile != NULL )
    {
      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;
       }

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

1362 1363 1364
      _dbus_string_free (&noncefileStr);

      if (!ret)
1365
    {
1366
      closesocket (fd);
1367 1368 1369
          return -1;
        }
    }
1370

1371 1372 1373
  if (!_dbus_set_fd_nonblocking (fd, error) )
    {
      closesocket (fd);
1374 1375 1376 1377
      return -1;
    }

  return fd;
1378 1379 1380
}

/**
1381 1382 1383 1384
 * Creates a socket and binds it to the given path, then listens on
 * the socket. The socket is set to be nonblocking.  In case of port=0
 * a random free port is used and returned in the port parameter.
 * If inaddr_any is specified, the hostname is ignored.
1385
 *
1386
 * @param host the host name to listen on
1387
 * @param port the port to listen on, if zero a free port will be used 
1388 1389 1390
 * @param family the address family to listen on, NULL for all
 * @param retport string to return the actual port listened on
 * @param fds_p location to store returned file descriptors
1391
 * @param error return location for errors
1392
 * @returns the number of listening file descriptors or -1 on error
1393 1394 1395 1396
 */

int
_dbus_listen_tcp_socket (const char     *host,
1397 1398 1399 1400
                         const char     *port,
                         const char     *family,
                         DBusString     *retport,
                         int           **fds_p,
1401 1402
                         DBusError      *error)
{
1403 1404 1405
  int nlisten_fd = 0, *listen_fd = NULL, res, i, port_num = -1;
  struct addrinfo hints;
  struct addrinfo *ai, *tmp;
1406

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
  // On Vista, sockaddr_gen must be a sockaddr_in6, and not a sockaddr_in6_old
  //That's required for family == IPv6(which is the default on Vista if family is not given)
  //So we use our own union instead of sockaddr_gen:

  typedef union {
	struct sockaddr Address;
	struct sockaddr_in AddressIn;
	struct sockaddr_in6 AddressIn6;
  } mysockaddr_gen;

1417
  *fds_p = NULL;
1418 1419 1420 1421
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  _dbus_win_startup_winsock ();

1422
  _DBUS_ZERO (hints);
1423

1424 1425 1426 1427 1428 1429 1430
  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
1431
    {
1432 1433 1434
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Unknown address family %s", family);
1435 1436
      return -1;
    }
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447

  hints.ai_protocol = IPPROTO_TCP;
  hints.ai_socktype = SOCK_STREAM;
#ifdef AI_ADDRCONFIG
  hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
#else
  hints.ai_flags = AI_PASSIVE;
#endif

 redo_lookup_with_port:
  if ((res = getaddrinfo(host, port, &hints, &ai)) != 0 || !ai)
1448
    {
1449 1450 1451 1452 1453
      dbus_set_error (error,
                      _dbus_error_from_errno (errno),
                      "Failed to lookup host/port: \"%s:%s\": %s (%d)",
                      host ? host : "*", port, gai_strerror(res), res);
      return -1;
1454
    }
1455 1456 1457

  tmp = ai;
  while (tmp)
1458
    {
1459 1460
      int fd = -1, *newlisten_fd;
      if ((fd = socket (tmp->ai_family, SOCK_STREAM, 0)) < 0)
1461 1462 1463
        {
          dbus_set_error (error,
                          _dbus_error_from_errno (errno),
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
                         "Failed to open socket: %s",
                         _dbus_strerror (errno));
          goto failed;
        }
      _DBUS_ASSERT_ERROR_IS_CLEAR(error);

      if (bind (fd, (struct sockaddr*) tmp->ai_addr, tmp->ai_addrlen) == SOCKET_ERROR)
        {
          closesocket (fd);
          dbus_set_error (error, _dbus_error_from_errno (errno),
                          "Failed to bind socket \"%s:%s\": %s",
                          host ? host : "*", port, _dbus_strerror (errno));
          goto failed;
    }

      if (listen (fd, 30 /* backlog */) == SOCKET_ERROR)
        {
          closesocket (fd);
          dbus_set_error (error, _dbus_error_from_errno (errno),
                          "Failed to listen on socket \"%s:%s\": %s",
                          host ? host : "*", port, _dbus_strerror (errno));
          goto failed;
1486 1487
        }

1488 1489 1490 1491 1492 1493 1494 1495
      newlisten_fd = dbus_realloc(listen_fd, sizeof(int)*(nlisten_fd+1));
      if (!newlisten_fd)
    {
          closesocket (fd);
      dbus_set_error (error, _dbus_error_from_errno (errno),
                          "Failed to allocate file handle array: %s",
                          _dbus_strerror (errno));
          goto failed;
1496
    }
1497 1498 1499
      listen_fd = newlisten_fd;
      listen_fd[nlisten_fd] = fd;
      nlisten_fd++;
1500

1501 1502 1503 1504 1505 1506 1507 1508
      if (!_dbus_string_get_length(retport))
        {
          /* If the user didn't specify a port, or used 0, then
             the kernel chooses a port. After the first address
             is bound to, we need to force all remaining addresses
             to use the same port */
          if (!port || !strcmp(port, "0"))
            {
1509
              mysockaddr_gen addr;
1510 1511
              socklen_t addrlen = sizeof(addr);
              char portbuf[10];
1512

1513
              if ((res = getsockname(fd, &addr.Address, &addrlen)) != 0)
1514 1515
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
                                  "Failed to resolve port \"%s:%s\": %s (%d)",
                                  host ? host : "*", port, gai_strerror(res), res);
                  goto failed;
                }
              snprintf( portbuf, sizeof( portbuf ) - 1, "%d", addr.AddressIn.sin_port );
              if (!_dbus_string_append(retport, portbuf))
                {
                  dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
                  goto failed;
    }

              /* Release current address list & redo lookup */
              port = _dbus_string_get_const_data(retport);
              freeaddrinfo(ai);
              goto redo_lookup_with_port;
            }
          else
            {
              if (!_dbus_string_append(retport, port))
                {
                    dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
                    goto failed;
                }
            }
        }
  
      tmp = tmp->ai_next;
1543
    }
1544 1545
  freeaddrinfo(ai);
  ai = NULL;
1546

1547
  if (!nlisten_fd)
1548
    {
1549
      errno = WSAEADDRINUSE;
1550
      dbus_set_error (error, _dbus_error_from_errno (errno),
1551 1552
                      "Failed to bind socket \"%s:%s\": %s",
                      host ? host : "*", port, _dbus_strerror (errno));
1553 1554 1555
      return -1;
    }

1556
  sscanf(_dbus_string_get_const_data(retport), "%d", &port_num);
1557

1558
  for (i = 0 ; i < nlisten_fd ; i++)
1559
    {
1560 1561 1562 1563
      if (!_dbus_set_fd_nonblocking (listen_fd[i], error))
        {
          goto failed;
        }
1564 1565
    }

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
  *fds_p = listen_fd;

  return nlisten_fd;

 failed:
  if (ai)
    freeaddrinfo(ai);
  for (i = 0 ; i < nlisten_fd ; i++)
    closesocket (listen_fd[i]);
  dbus_free(listen_fd);
  return -1;
1577 1578
}

1579

1580 1581 1582 1583 1584 1585 1586 1587
/**
 * Accepts a connection on a listening socket.
 * Handles EINTR for you.
 *
 * @param listen_fd the listen file descriptor
 * @returns the connection fd of the client, or -1 on error
 */
int
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1588
_dbus_accept  (int listen_fd)
1589
{
Ralf Habacker's avatar
*...  
Ralf Habacker committed
1590
  int client_fd;
1591

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1592
 retry:
1593
  client_fd = accept (listen_fd, NULL, NULL);
1594

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1595
  if (DBUS_SOCKET_IS_INVALID (client_fd))
1596 1597 1598 1599 1600 1601
    {
      DBUS_SOCKET_SET_ERRNO ();
      if (errno == EINTR)
        goto retry;
    }

Ralf Habacker's avatar
*...  
Ralf Habacker committed
1602 1603 1604
  _dbus_verbose ("client fd %d accepted\n", client_fd);
  
  return client_fd;
1605 1606 1607 1608
}



1609

1610
dbus_bool_t
1611
_dbus_send_credentials_socket (int            handle,
1612 1613
                        DBusError      *error)
{
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
/* FIXME: for the session bus credentials shouldn't matter (?), but
 * for the system bus they are presumably essential. A rough outline
 * of a way to implement the credential transfer would be this:
 *
 * client waits to *read* a byte.
 *
 * server creates a named pipe with a random name, sends a byte
 * contining its length, and its name.
 *
 * client reads the name, connects to it (using Win32 API).
 *
 * server waits for connection to the named pipe, then calls
 * ImpersonateNamedPipeClient(), notes its now-current credentials,
 * calls RevertToSelf(), closes its handles to the named pipe, and
 * is done. (Maybe there is some other way to get the SID of a named
 * pipe client without having to use impersonation?)
 *
 * client closes its handles and is done.
 * 
 * Ralf: Why not sending credentials over the given this connection ?
 * Using named pipes makes it impossible to be connected from a unix client.  
 *
 */
  int bytes_written;
  DBusString buf; 

  _dbus_string_init_const_len (&buf, "\0", 1);
again:
  bytes_written = _dbus_write_socket (handle, &buf, 0, 1 );
1643

1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
  if (bytes_written < 0 && errno == EINTR)
    goto again;

  if (bytes_written < 0)
    {
      dbus_set_error (error, _dbus_error_from_errno (errno),
                      "Failed to write credentials byte: %s",
                     _dbus_strerror (errno));
      return FALSE;
    }
  else if (bytes_written == 0)
    {
      dbus_set_error (error, DBUS_ERROR_IO_ERROR,
                      "wrote zero bytes writing credentials byte");
      return FALSE;
    }
  else
    {
      _dbus_assert (bytes_written == 1);
      _dbus_verbose ("wrote 1 zero byte, credential sending isn't implemented yet\n");
      return TRUE;
    }
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
  return TRUE;
}

/**
 * Reads a single byte which must be nul (an error occurs otherwise),
 * and reads unix credentials if available. Fills in pid/uid/gid with
 * -1 if no credentials are available. Return value indicates whether
 * a byte was read, not whether we got valid credentials. On some
 * systems, such as Linux, reading/writing the byte isn't actually
 * required, but we do it anyway just to avoid multiple codepaths.
 * 
 * Fails if no byte is available, so you must select() first.
 *
 * The point of the byte is that on some systems we have to
 * use sendmsg()/recvmsg() to transmit credentials.
 *
 * @param client_fd the client file descriptor
 * @param credentials struct to fill with credentials of client
 * @param error location to store error code
 * @returns #TRUE on success
 */
dbus_bool_t
1688
_dbus_read_credentials_socket  (int              handle,
Ralf Habacker's avatar
Ralf Habacker committed
1689 1690
                                DBusCredentials *credentials,
                                DBusError       *error)
1691
{
Ralf Habacker's avatar
Ralf Habacker committed
1692
  int bytes_read = 0;
1693
  DBusString buf;
Ralf Habacker's avatar
Ralf Habacker committed
1694 1695 1696
  
  // could fail due too OOM
  if (_dbus_string_init(&buf))
1697
    {
Ralf Habacker's avatar
Ralf Habacker committed
1698 1699 1700 1701 1702 1703
      bytes_read = _dbus_read_socket(handle, &buf, 1 );

      if (bytes_read > 0) 
        _dbus_verbose("got one zero byte from server");

      _dbus_string_free(&buf);
1704 1705
    }

1706
  _dbus_credentials_add_from_current_process (credentials);
1707
  _dbus_verbose("FIXME: get faked credentials from current process");
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774

  return TRUE;
}

/**
* Checks to make sure the given directory is 
* private to the user 
*
* @param dir the name of the directory
* @param error error return
* @returns #FALSE on failure
**/
dbus_bool_t
_dbus_check_dir_is_private_to_user (DBusString *dir, DBusError *error)
{
  const char *directory;
  struct stat sb;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  return TRUE;
}


/**
 * Appends the given filename to the given directory.
 *
 * @todo it might be cute to collapse multiple '/' such as "foo//"
 * concat "//bar"
 *
 * @param dir the directory name
 * @param next_component the filename
 * @returns #TRUE on success
 */
dbus_bool_t
_dbus_concat_dir_and_file (DBusString       *dir,
                           const DBusString *next_component)
{
  dbus_bool_t dir_ends_in_slash;
  dbus_bool_t file_starts_with_slash;

  if (_dbus_string_get_length (dir) == 0 ||
      _dbus_string_get_length (next_component) == 0)
    return TRUE;

  dir_ends_in_slash =
    ('/' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1) ||
     '\\' == _dbus_string_get_byte (dir, _dbus_string_get_length (dir) - 1));

  file_starts_with_slash =
    ('/' == _dbus_string_get_byte (next_component, 0) ||
     '\\' == _dbus_string_get_byte (next_component, 0));

  if (dir_ends_in_slash && file_starts_with_slash)
    {
      _dbus_string_shorten (dir, 1);
    }
  else if (!(dir_ends_in_slash || file_starts_with_slash))
    {
      if (!_dbus_string_append_byte (dir, '\\'))
        return FALSE;
    }

  return _dbus_string_copy (next_component, 0, dir,
                            _dbus_string_get_length (dir));
}

Tor Lillqvist's avatar
Tor Lillqvist committed
1775
/*---------------- DBusCredentials ----------------------------------*/
1776 1777

/**
1778
 * Adds the credentials corresponding to the given username.
1779
 *
1780 1781 1782
 * @param credentials credentials to fill in 
 * @param username the username
 * @returns #TRUE if the username existed and we got some credentials
1783 1784
 */
dbus_bool_t
1785 1786
_dbus_credentials_add_from_user (DBusCredentials  *credentials,
                                     const DBusString *username)
1787
{
1788 1789
  return _dbus_credentials_add_windows_sid (credentials,
                    _dbus_string_get_const_data(username));
1790 1791 1792
}

/**
1793 1794
 * Adds the credentials of the current process to the
 * passed-in credentials object.
1795
 *
1796 1797
 * @param credentials credentials to add to
 * @returns #FALSE if no memory; does not properly roll back on failure, so only some credentials may have been added
1798
 */
1799

1800
dbus_bool_t
1801
_dbus_credentials_add_from_current_process (DBusCredentials *credentials)
1802
{
1803 1804
  dbus_bool_t retval = FALSE;
  char *sid = NULL;
1805

1806 1807
  if (!_dbus_getsid(&sid))
    goto failed;
1808

1809 1810
  if (!_dbus_credentials_add_unix_pid(credentials, _dbus_getpid()))
    goto failed;
1811

1812 1813
  if (!_dbus_credentials_add_windows_sid (credentials,sid))
    goto failed;