giowin32.c 52.6 KB
Newer Older
1 2 3 4 5
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * giowin32.c: IO Channels for Win32.
 * Copyright 1998 Owen Taylor and Tor Lillqvist
6
 * Copyright 1999-2000 Tor Lillqvist and Craig Setera
7
 * Copyright 2001-2003 Andrew Lanoix
8 9
 *
 * This library is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11 12 13 14 15
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public
20 21 22 23 24
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

25
/*
26
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
27 28
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
29
 * GLib at ftp://ftp.gtk.org/pub/gtk/.
30 31
 */

Owen Taylor's avatar
Owen Taylor committed
32 33
#include "config.h"

34
#include "glib.h"
35 36

#include <stdlib.h>
37
#include <winsock2.h>
38
#include <windows.h>
39 40
#include <fcntl.h>
#include <io.h>
41
#include <process.h>
42
#include <errno.h>
43
#include <sys/stat.h>
44

45
#include "gstdio.h"
46 47
#include "glibintl.h"

48 49
#include "galias.h"

50 51 52
typedef struct _GIOWin32Channel GIOWin32Channel;
typedef struct _GIOWin32Watch GIOWin32Watch;

53
#define BUFFER_SIZE 4096
54 55

typedef enum {
56 57
  G_IO_WIN32_WINDOWS_MESSAGES,	/* Windows messages */
  G_IO_WIN32_FILE_DESC,		/* Unix-like file descriptors from
58 59 60
				 * _open() or _pipe(). Read with read().
				 * Have to create separate thread to read.
				 */
61
  G_IO_WIN32_SOCKET		/* Sockets. No separate thread */
62 63 64 65 66 67 68 69 70
} GIOWin32ChannelType;

struct _GIOWin32Channel {
  GIOChannel channel;
  gint fd;			/* Either a Unix-like file handle as provided
				 * by the Microsoft C runtime, or a SOCKET
				 * as provided by WinSock.
				 */
  GIOWin32ChannelType type;
71
  
72 73
  gboolean debug;

74
  /* This is used by G_IO_WIN32_WINDOWS_MESSAGES channels */
75
  HWND hwnd;			/* handle of window, or NULL */
76
  
77 78 79
  /* Following fields are used by fd channels. */
  CRITICAL_SECTION mutex;

80 81 82 83
  int direction;		/* 0 means we read from it,
				 * 1 means we write to it.
				 */

84 85 86 87 88 89 90 91 92 93 94 95 96
  gboolean running;		/* Is reader thread running. FALSE if
				 * EOF has been reached.
				 */
  gboolean needs_close;		/* If the channel has been closed while
				 * the reader thread was still running.
				 */
  guint thread_id;		/* If non-NULL has a reader thread, or has
				 * had.*/
  HANDLE data_avail_event;

  gushort revents;

  /* Following fields used by fd channels for input */
97 98 99 100 101 102 103 104 105 106 107 108 109 110
  
  /* Data is kept in a circular buffer. To be able to distinguish between
   * empty and full buffer, we cannot fill it completely, but have to
   * leave a one character gap.
   *
   * Data available is between indexes rdp and wrp-1 (modulo BUFFER_SIZE).
   *
   * Empty:    wrp == rdp
   * Full:     (wrp + 1) % BUFFER_SIZE == rdp
   * Partial:  otherwise
   */
  guchar *buffer;		/* (Circular) buffer */
  gint wrp, rdp;		/* Buffer indices for writing and reading */
  HANDLE space_avail_event;
111 112

  /* Following fields used by socket channels */
113 114 115 116
  int event_mask;
  int last_events;
  int event;
  gboolean write_would_have_blocked;
117 118
};

119 120 121
#define LOCK(mutex) EnterCriticalSection (&mutex)
#define UNLOCK(mutex) LeaveCriticalSection (&mutex)

122
struct _GIOWin32Watch {
123
  GSource       source;
124 125 126 127 128
  GPollFD       pollfd;
  GIOChannel   *channel;
  GIOCondition  condition;
};

129
static void
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
g_win32_print_access_mode (int flags)
{
  g_print ("%s%s%s%s%s%s%s%s%s%s",
	   ((flags & 0x3) == _O_RDWR ? "O_RDWR" :
	    ((flags & 0x3) == _O_RDONLY ? "O_RDONLY" :
	     ((flags & 0x3) == _O_WRONLY ? "O_WRONLY" : "0"))),
	   (flags & _O_APPEND ? "|O_APPEND" : ""),
	   (flags & _O_RANDOM ? "|O_RANDOM" : ""),
	   (flags & _O_SEQUENTIAL ? "|O_SEQUENTIAL" : ""),
	   (flags & _O_TEMPORARY ? "|O_TEMPORARY" : ""),
	   (flags & _O_CREAT ? "|O_CREAT" : ""),
	   (flags & _O_TRUNC ? "|O_TRUNC" : ""),
	   (flags & _O_EXCL ? "|O_EXCL" : ""),
	   (flags & _O_TEXT ? "|O_TEXT" : ""),
	   (flags & _O_BINARY ? "|O_BINARY" : ""));
}

static void
g_win32_print_gioflags (GIOFlags flags)
{
  char *bar = "";

  if (flags & G_IO_FLAG_APPEND)
    bar = "|", g_print ("APPEND");
  if (flags & G_IO_FLAG_NONBLOCK)
    g_print ("%sNONBLOCK", bar), bar = "|";
  if (flags & G_IO_FLAG_IS_READABLE)
    g_print ("%sREADABLE", bar), bar = "|";
  if (flags & G_IO_FLAG_IS_WRITEABLE)
    g_print ("%sWRITEABLE", bar), bar = "|";
  if (flags & G_IO_FLAG_IS_SEEKABLE)
    g_print ("%sSEEKABLE", bar), bar = "|";
}

164 165 166 167 168 169 170 171 172 173 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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
static const char *
event_mask_to_string (int mask)
{
  char buf[100];
  int checked_bits = 0;
  char *bufp = buf;

  if (mask == 0)
    return "";

#define BIT(n) checked_bits |= FD_##n; if (mask & FD_##n) bufp += sprintf (bufp, "%s" #n, (bufp>buf ? "|" : ""))

  BIT (READ);
  BIT (WRITE);
  BIT (OOB);
  BIT (ACCEPT);
  BIT (CONNECT);
  BIT (CLOSE);
  BIT (QOS);
  BIT (GROUP_QOS);
  BIT (ROUTING_INTERFACE_CHANGE);
  BIT (ADDRESS_LIST_CHANGE);
  
#undef BIT

  if ((mask & ~checked_bits) != 0)
	  bufp += sprintf (bufp, "|%#x", mask & ~checked_bits);
  
  return g_quark_to_string (g_quark_from_string (buf));
}

static const char *
condition_to_string (GIOCondition condition)
{
  char buf[100];
  int checked_bits = 0;
  char *bufp = buf;

  if (condition == 0)
    return "";

#define BIT(n) checked_bits |= G_IO_##n; if (condition & G_IO_##n) bufp += sprintf (bufp, "%s" #n, (bufp>buf ? "|" : ""))

  BIT (IN);
  BIT (OUT);
  BIT (PRI);
  BIT (ERR);
  BIT (HUP);
  BIT (NVAL);
  
#undef BIT

  if ((condition & ~checked_bits) != 0)
	  bufp += sprintf (bufp, "|%#x", condition & ~checked_bits);
  
  return g_quark_to_string (g_quark_from_string (buf));
}

222 223
static gboolean
g_io_win32_get_debug_flag (void)
224
{
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 292 293 294 295 296 297 298 299 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 333 334 335 336 337 338 339 340 341 342
  return (getenv ("G_IO_WIN32_DEBUG") != NULL);
}

static char *
winsock_error_message (int number)
{
  static char unk[100];

  switch (number) {
  case WSAEINTR:
    return "Interrupted function call";
  case WSAEACCES:
    return "Permission denied";
  case WSAEFAULT:
    return "Bad address";
  case WSAEINVAL:
    return "Invalid argument";
  case WSAEMFILE:
    return "Too many open sockets";
  case WSAEWOULDBLOCK:
    return "Resource temporarily unavailable";
  case WSAEINPROGRESS:
    return "Operation now in progress";
  case WSAEALREADY:
    return "Operation already in progress";
  case WSAENOTSOCK:
    return "Socket operation on nonsocket";
  case WSAEDESTADDRREQ:
    return "Destination address required";
  case WSAEMSGSIZE:
    return "Message too long";
  case WSAEPROTOTYPE:
    return "Protocol wrong type for socket";
  case WSAENOPROTOOPT:
    return "Bad protocol option";
  case WSAEPROTONOSUPPORT:
    return "Protocol not supported";
  case WSAESOCKTNOSUPPORT:
    return "Socket type not supported";
  case WSAEOPNOTSUPP:
    return "Operation not supported on transport endpoint";
  case WSAEPFNOSUPPORT:
    return "Protocol family not supported";
  case WSAEAFNOSUPPORT:
    return "Address family not supported by protocol family";
  case WSAEADDRINUSE:
    return "Address already in use";
  case WSAEADDRNOTAVAIL:
    return "Address not available";
  case WSAENETDOWN:
    return "Network interface is not configured";
  case WSAENETUNREACH:
    return "Network is unreachable";
  case WSAENETRESET:
    return "Network dropped connection on reset";
  case WSAECONNABORTED:
    return "Software caused connection abort";
  case WSAECONNRESET:
    return "Connection reset by peer";
  case WSAENOBUFS:
    return "No buffer space available";
  case WSAEISCONN:
    return "Socket is already connected";
  case WSAENOTCONN:
    return "Socket is not connected";
  case WSAESHUTDOWN:
    return "Can't send after socket shutdown";
  case WSAETIMEDOUT:
    return "Connection timed out";
  case WSAECONNREFUSED:
    return "Connection refused";
  case WSAEHOSTDOWN:
    return "Host is down";
  case WSAEHOSTUNREACH:
    return "Host is unreachable";
  case WSAEPROCLIM:
    return "Too many processes";
  case WSASYSNOTREADY:
    return "Network subsystem is unavailable";
  case WSAVERNOTSUPPORTED:
    return "Winsock.dll version out of range";
  case WSANOTINITIALISED:
    return "Successful WSAStartup not yet performed";
  case WSAEDISCON:
    return "Graceful shutdown in progress";
  case WSATYPE_NOT_FOUND:
    return "Class type not found";
  case WSAHOST_NOT_FOUND:
    return "Host not found";
  case WSATRY_AGAIN:
    return "Nonauthoritative host not found";
  case WSANO_RECOVERY:
    return "This is a nonrecoverable error";
  case WSANO_DATA:
    return "Valid name, no data record of requested type";
  case WSA_INVALID_HANDLE:
    return "Specified event object handle is invalid";
  case WSA_INVALID_PARAMETER:
    return "One or more parameters are invalid";
  case WSA_IO_INCOMPLETE:
    return "Overlapped I/O event object not in signaled state";
  case WSA_NOT_ENOUGH_MEMORY:
    return "Insufficient memory available";
  case WSA_OPERATION_ABORTED:
    return "Overlapped operation aborted";
  case WSAEINVALIDPROCTABLE:
    return "Invalid procedure table from service provider";
  case WSAEINVALIDPROVIDER:
    return "Invalid service provider version number";
  case WSAEPROVIDERFAILEDINIT:
    return "Unable to initialize a service provider";
  case WSASYSCALLFAILURE:
    return "System call failure";
  default:
    sprintf (unk, "Unknown WinSock error %d", number);
    return unk;
  }
}
343 344 345 346 347

static void
g_io_channel_win32_init (GIOWin32Channel *channel)
{
  channel->debug = g_io_win32_get_debug_flag ();
348 349
  channel->buffer = NULL;
  channel->running = FALSE;
350
  channel->needs_close = FALSE;
351
  channel->thread_id = 0;
352
  channel->data_avail_event = NULL;
353
  channel->revents = 0;
354
  channel->space_avail_event = NULL;
355 356 357 358
  channel->event_mask = 0;
  channel->last_events = 0;
  channel->event = 0;
  channel->write_would_have_blocked = FALSE;
359
  InitializeCriticalSection (&channel->mutex);
360 361
}

362 363 364 365 366
static void
create_events (GIOWin32Channel *channel)
{
  SECURITY_ATTRIBUTES sec_attrs;
  
367
  sec_attrs.nLength = sizeof (SECURITY_ATTRIBUTES);
368 369
  sec_attrs.lpSecurityDescriptor = NULL;
  sec_attrs.bInheritHandle = FALSE;
370

371 372 373 374
  /* The data available event is manual reset, the space available event
   * is automatic reset.
   */
  if (!(channel->data_avail_event = CreateEvent (&sec_attrs, TRUE, FALSE, NULL))
375
      || !(channel->space_avail_event = CreateEvent (&sec_attrs, FALSE, FALSE, NULL)))
376
    {
377 378 379
      gchar *emsg = g_win32_error_message (GetLastError ());
      g_error ("Error creating event: %s", emsg);
      g_free (emsg);
380 381
    }
}
382

383
static unsigned __stdcall
384
read_thread (void *parameter)
385 386 387 388
{
  GIOWin32Channel *channel = parameter;
  guchar *buffer;
  guint nbytes;
389

390
  g_io_channel_ref ((GIOChannel *)channel);
391

392
  if (channel->debug)
393
    g_print ("read_thread %#x: start fd=%d, data_avail=%#x space_avail=%#x\n",
394 395 396 397
	     channel->thread_id,
	     channel->fd,
	     (guint) channel->data_avail_event,
	     (guint) channel->space_avail_event);
398 399

  channel->direction = 0;
400 401 402
  channel->buffer = g_malloc (BUFFER_SIZE);
  channel->rdp = channel->wrp = 0;
  channel->running = TRUE;
403

404 405
  SetEvent (channel->space_avail_event);
  
406
  LOCK (channel->mutex);
407 408
  while (channel->running)
    {
409
      if (channel->debug)
410
	g_print ("read_thread %#x: rdp=%d, wrp=%d\n",
411
		 channel->thread_id, channel->rdp, channel->wrp);
412 413 414
      if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
	{
	  /* Buffer is full */
415
	  if (channel->debug)
416
	    g_print ("read_thread %#x: resetting space_avail\n",
417
		     channel->thread_id);
418
	  ResetEvent (channel->space_avail_event);
419
	  if (channel->debug)
420 421
	    g_print ("read_thread %#x: waiting for space\n",
		     channel->thread_id);
422 423 424
	  UNLOCK (channel->mutex);
	  WaitForSingleObject (channel->space_avail_event, INFINITE);
	  LOCK (channel->mutex);
425
	  if (channel->debug)
426
	    g_print ("read_thread %#x: rdp=%d, wrp=%d\n",
427
		     channel->thread_id, channel->rdp, channel->wrp);
428 429 430 431 432 433 434 435 436
	}
      
      buffer = channel->buffer + channel->wrp;
      
      /* Always leave at least one byte unused gap to be able to
       * distinguish between the full and empty condition...
       */
      nbytes = MIN ((channel->rdp + BUFFER_SIZE - channel->wrp - 1) % BUFFER_SIZE,
		    BUFFER_SIZE - channel->wrp);
437

438
      if (channel->debug)
439
	g_print ("read_thread %#x: calling read() for %d bytes\n",
440 441
		 channel->thread_id, nbytes);

442
      UNLOCK (channel->mutex);
443

444
      nbytes = read (channel->fd, buffer, nbytes);
445 446
      
      LOCK (channel->mutex);
447

448 449 450 451 452 453
      channel->revents = G_IO_IN;
      if (nbytes == 0)
	channel->revents |= G_IO_HUP;
      else if (nbytes < 0)
	channel->revents |= G_IO_ERR;

454
      if (channel->debug)
455
	g_print ("read_thread %#x: read() returned %d, rdp=%d, wrp=%d\n",
456
		 channel->thread_id, nbytes, channel->rdp, channel->wrp);
457 458 459 460

      if (nbytes <= 0)
	break;

461
      channel->wrp = (channel->wrp + nbytes) % BUFFER_SIZE;
462
      if (channel->debug)
463
	g_print ("read_thread %#x: rdp=%d, wrp=%d, setting data_avail\n",
464
		 channel->thread_id, channel->rdp, channel->wrp);
465 466 467 468
      SetEvent (channel->data_avail_event);
    }
  
  channel->running = FALSE;
469 470 471
  if (channel->needs_close)
    {
      if (channel->debug)
472
	g_print ("read_thread %#x: channel fd %d needs closing\n",
473
		 channel->thread_id, channel->fd);
474
      close (channel->fd);
475 476 477
      channel->fd = -1;
    }

478 479 480
  if (channel->debug)
    g_print ("read_thread %#x: EOF, rdp=%d, wrp=%d, setting data_avail\n",
	     channel->thread_id, channel->rdp, channel->wrp);
481 482 483
  SetEvent (channel->data_avail_event);
  UNLOCK (channel->mutex);
  
484
  g_io_channel_unref ((GIOChannel *)channel);
485
  
486 487 488
  /* No need to call _endthreadex(), the actual thread starter routine
   * in MSVCRT (see crt/src/threadex.c:_threadstartex) calls
   * _endthreadex() for us.
489
   */
490

491 492
  return 0;
}
493

494 495 496 497 498 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
static unsigned __stdcall
write_thread (void *parameter)
{
  GIOWin32Channel *channel = parameter;
  guchar *buffer;
  guint nbytes;

  g_io_channel_ref ((GIOChannel *)channel);

  if (channel->debug)
    g_print ("write_thread %#x: start fd=%d, data_avail=%#x space_avail=%#x\n",
	     channel->thread_id,
	     channel->fd,
	     (guint) channel->data_avail_event,
	     (guint) channel->space_avail_event);
  
  channel->direction = 1;
  channel->buffer = g_malloc (BUFFER_SIZE);
  channel->rdp = channel->wrp = 0;
  channel->running = TRUE;

  SetEvent (channel->space_avail_event);

  /* We use the same event objects as for a reader thread, but with
   * reversed meaning. So, space_avail is used if data is available
   * for writing, and data_avail is used if space is available in the
   * write buffer.
   */

  LOCK (channel->mutex);
  while (channel->running || channel->rdp != channel->wrp)
    {
      if (channel->debug)
	g_print ("write_thread %#x: rdp=%d, wrp=%d\n",
		 channel->thread_id, channel->rdp, channel->wrp);
      if (channel->wrp == channel->rdp)
	{
	  /* Buffer is empty. */
	  if (channel->debug)
	    g_print ("write_thread %#x: resetting space_avail\n",
		     channel->thread_id);
	  ResetEvent (channel->space_avail_event);
	  if (channel->debug)
	    g_print ("write_thread %#x: waiting for data\n",
		     channel->thread_id);
	  channel->revents = G_IO_OUT;
	  SetEvent (channel->data_avail_event);
	  UNLOCK (channel->mutex);
	  WaitForSingleObject (channel->space_avail_event, INFINITE);

	  LOCK (channel->mutex);
	  if (channel->rdp == channel->wrp)
	    break;

	  if (channel->debug)
	    g_print ("write_thread %#x: rdp=%d, wrp=%d\n",
		     channel->thread_id, channel->rdp, channel->wrp);
	}
      
      buffer = channel->buffer + channel->rdp;
      if (channel->rdp < channel->wrp)
	nbytes = channel->wrp - channel->rdp;
      else
	nbytes = BUFFER_SIZE - channel->rdp;

      if (channel->debug)
	g_print ("write_thread %#x: calling write() for %d bytes\n",
		 channel->thread_id, nbytes);

      UNLOCK (channel->mutex);
      nbytes = write (channel->fd, buffer, nbytes);
      LOCK (channel->mutex);

      if (channel->debug)
	g_print ("write_thread %#x: write(%i) returned %d, rdp=%d, wrp=%d\n",
		 channel->thread_id, channel->fd, nbytes, channel->rdp, channel->wrp);

      channel->revents = 0;
      if (nbytes > 0)
	channel->revents |= G_IO_OUT;
      else if (nbytes <= 0)
	channel->revents |= G_IO_ERR;

      channel->rdp = (channel->rdp + nbytes) % BUFFER_SIZE;

      if (nbytes <= 0)
	break;

      if (channel->debug)
	g_print ("write_thread: setting data_avail for thread %#x\n",
		 channel->thread_id);
      SetEvent (channel->data_avail_event);
    }
  
  channel->running = FALSE;
  if (channel->needs_close)
    {
      if (channel->debug)
	g_print ("write_thread %#x: channel fd %d needs closing\n",
		 channel->thread_id, channel->fd);
      close (channel->fd);
      channel->fd = -1;
    }

  UNLOCK (channel->mutex);
  
  g_io_channel_unref ((GIOChannel *)channel);
  
  return 0;
}

605
static void
606 607 608
create_thread (GIOWin32Channel     *channel,
	       GIOCondition         condition,
	       unsigned (__stdcall *thread) (void *parameter))
609
{
610 611 612 613 614
  HANDLE thread_handle;

  thread_handle = (HANDLE) _beginthreadex (NULL, 0, thread, channel, 0,
					   &channel->thread_id);
  if (thread_handle == 0)
615
    g_warning (G_STRLOC ": Error creating reader thread: %s",
Owen Taylor's avatar
Owen Taylor committed
616
	       g_strerror (errno));
617 618 619 620
  else if (!CloseHandle (thread_handle))
    g_warning (G_STRLOC ": Error closing thread handle: %s\n",
	       g_win32_error_message (GetLastError ()));

621 622
  WaitForSingleObject (channel->space_avail_event, INFINITE);
}
623

624
static GIOStatus
625 626
buffer_read (GIOWin32Channel *channel,
	     guchar          *dest,
627 628 629
	     gsize            count,
	     gsize           *bytes_read,
	     GError         **err)
630
{
631 632 633 634
  guint nbytes;
  guint left = count;
  
  LOCK (channel->mutex);
635 636 637
  if (channel->debug)
    g_print ("reading from thread %#x %d bytes, rdp=%d, wrp=%d\n",
	     channel->thread_id, count, channel->rdp, channel->wrp);
638
  
639
  if (channel->wrp == channel->rdp)
640 641
    {
      UNLOCK (channel->mutex);
642 643 644
      if (channel->debug)
	g_print ("waiting for data from thread %#x\n", channel->thread_id);
      WaitForSingleObject (channel->data_avail_event, INFINITE);
645 646
      if (channel->debug)
	g_print ("done waiting for data from thread %#x\n", channel->thread_id);
647
      LOCK (channel->mutex);
648
      if (channel->wrp == channel->rdp && !channel->running)
649
	{
650 651
	  if (channel->debug)
	    g_print ("wrp==rdp, !running\n");
652
	  UNLOCK (channel->mutex);
653
          *bytes_read = 0;
654
	  return G_IO_STATUS_EOF;
655
	}
656
    }
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
  
  if (channel->rdp < channel->wrp)
    nbytes = channel->wrp - channel->rdp;
  else
    nbytes = BUFFER_SIZE - channel->rdp;
  UNLOCK (channel->mutex);
  nbytes = MIN (left, nbytes);
  if (channel->debug)
    g_print ("moving %d bytes from thread %#x\n",
	     nbytes, channel->thread_id);
  memcpy (dest, channel->buffer + channel->rdp, nbytes);
  dest += nbytes;
  left -= nbytes;
  LOCK (channel->mutex);
  channel->rdp = (channel->rdp + nbytes) % BUFFER_SIZE;
  if (channel->debug)
673
    g_print ("setting space_avail for thread %#x\n", channel->thread_id);
674 675 676 677
  SetEvent (channel->space_avail_event);
  if (channel->debug)
    g_print ("for thread %#x: rdp=%d, wrp=%d\n",
	     channel->thread_id, channel->rdp, channel->wrp);
678
  if (channel->running && channel->wrp == channel->rdp)
679 680
    {
      if (channel->debug)
681
	g_print ("resetting data_avail of thread %#x\n",
682 683 684
		 channel->thread_id);
      ResetEvent (channel->data_avail_event);
    };
685 686
  UNLOCK (channel->mutex);
  
687 688 689
  /* We have no way to indicate any errors form the actual
   * read() or recv() call in the reader thread. Should we have?
   */
690 691
  *bytes_read = count - left;
  return (*bytes_read > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
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 719 720 721 722 723 724 725 726 727 728 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

static GIOStatus
buffer_write (GIOWin32Channel *channel,
	      const guchar    *dest,
	      gsize            count,
	      gsize           *bytes_written,
	      GError         **err)
{
  guint nbytes;
  guint left = count;
  
  LOCK (channel->mutex);
  if (channel->debug)
    g_print ("buffer_write: writing to thread %#x %d bytes, rdp=%d, wrp=%d\n",
	     channel->thread_id, count, channel->rdp, channel->wrp);
  
  if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
    {
      /* Buffer is full */
      if (channel->debug)
	g_print ("buffer_write: tid %#x: resetting data_avail\n",
		 channel->thread_id);
      ResetEvent (channel->data_avail_event);
      if (channel->debug)
	g_print ("buffer_write: tid %#x: waiting for space\n",
		 channel->thread_id);
      UNLOCK (channel->mutex);
      WaitForSingleObject (channel->data_avail_event, INFINITE);
      LOCK (channel->mutex);
      if (channel->debug)
	g_print ("buffer_write: tid %#x: rdp=%d, wrp=%d\n",
		 channel->thread_id, channel->rdp, channel->wrp);
    }
   
  nbytes = MIN ((channel->rdp + BUFFER_SIZE - channel->wrp - 1) % BUFFER_SIZE,
		BUFFER_SIZE - channel->wrp);

  UNLOCK (channel->mutex);
  nbytes = MIN (left, nbytes);
  if (channel->debug)
    g_print ("buffer_write: tid %#x: writing %d bytes\n",
	     channel->thread_id, nbytes);
  memcpy (channel->buffer + channel->wrp, dest, nbytes);
  dest += nbytes;
  left -= nbytes;
  LOCK (channel->mutex);

  channel->wrp = (channel->wrp + nbytes) % BUFFER_SIZE;
  if (channel->debug)
    g_print ("buffer_write: tid %#x: rdp=%d, wrp=%d, setting space_avail\n",
	     channel->thread_id, channel->rdp, channel->wrp);
  SetEvent (channel->space_avail_event);

  if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
    {
      /* Buffer is full */
      if (channel->debug)
	g_print ("buffer_write: tid %#x: resetting data_avail\n",
		 channel->thread_id);
      ResetEvent (channel->data_avail_event);
    }

  UNLOCK (channel->mutex);
  
  /* We have no way to indicate any errors form the actual
   * write() call in the writer thread. Should we have?
   */
  *bytes_written = count - left;
  return (*bytes_written > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
}


766
static gboolean
767 768
g_io_win32_prepare (GSource *source,
		    gint    *timeout)
769
{
770
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
771
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
772
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
773
  int event_mask;
774
  
775
  *timeout = -1;
776
  
777
  switch (channel->type)
778
    {
779 780 781 782 783 784 785 786 787 788 789 790
    case G_IO_WIN32_WINDOWS_MESSAGES:
      break;

    case G_IO_WIN32_FILE_DESC:
      if (channel->debug)
	g_print ("g_io_win32_prepare: for thread %#x buffer_condition:{%s}\n"
		 "  watch->pollfd.events:{%s} watch->pollfd.revents:{%s} channel->revents:{%s}\n",
		 channel->thread_id, condition_to_string (buffer_condition),
		 condition_to_string (watch->pollfd.events),
		 condition_to_string (watch->pollfd.revents),
		 condition_to_string (channel->revents));
      
791
      LOCK (channel->mutex);
792
      if (channel->running)
793
	{
794 795 796 797 798 799 800
	  if (channel->direction == 0 && channel->wrp == channel->rdp)
	    {
	      if (channel->debug)
		g_print ("g_io_win32_prepare: for thread %#x, setting channel->revents = 0\n",
			 channel->thread_id);
	      channel->revents = 0;
	    }
801
	}
802 803 804 805 806 807 808 809 810 811 812
      else
	{
	  if (channel->direction == 1
	      && (channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
	    {
	      if (channel->debug)
		g_print ("g_io_win32_prepare: for thread %#x, setting channel->revents = %i\n",
			 channel->thread_id, 0);
	      channel->revents = 0;
	    }
	}	  
813
      UNLOCK (channel->mutex);
814
      break;
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
    case G_IO_WIN32_SOCKET:
      event_mask = 0;
      if (watch->condition & G_IO_IN)
	event_mask |= (FD_READ | FD_ACCEPT);
      if (watch->condition & G_IO_OUT)
	event_mask |= (FD_WRITE | FD_CONNECT);
      if (watch->condition & G_IO_HUP)
	event_mask |= FD_CLOSE;

      if (channel->event_mask != event_mask /* || channel->event != watch->pollfd.fd*/)
	{
	  if (channel->debug)
	    g_print ("g_io_win32_prepare: WSAEventSelect(%d, %#x, {%s}\n",
		     channel->fd, watch->pollfd.fd,
		     event_mask_to_string (event_mask));
	  if (WSAEventSelect (channel->fd, (HANDLE) watch->pollfd.fd,
			      event_mask) == SOCKET_ERROR)
	    ;			/* What? */
	  channel->event_mask = event_mask;
#if 0
	  channel->event = watch->pollfd.fd;
#endif
	  channel->last_events = 0;
	}
      break;

    default:
      g_assert_not_reached ();
      abort ();
    }
846
  return ((watch->condition & buffer_condition) == watch->condition);
847 848
}

849
static gboolean
850
g_io_win32_check (GSource *source)
851
{
852
  MSG msg;
853
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
854
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
855
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
856
  WSANETWORKEVENTS events;
857

858
  switch (channel->type)
859
    {
860
    case G_IO_WIN32_WINDOWS_MESSAGES:
861
      return (PeekMessage (&msg, channel->hwnd, 0, 0, PM_NOREMOVE));
862 863

    case G_IO_WIN32_FILE_DESC:
864
      if (channel->debug)
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
	g_print ("g_io_win32_check: for thread %#x buffer_condition=%s\n"
		 "  watch->pollfd.events={%s} watch->pollfd.revents={%s} channel->revents={%s}\n",
		 channel->thread_id, condition_to_string (buffer_condition),
		 condition_to_string (watch->pollfd.events),
		 condition_to_string (watch->pollfd.revents),
		 condition_to_string (channel->revents));
      
      watch->pollfd.revents = (watch->pollfd.events & channel->revents);

      return ((watch->pollfd.revents | buffer_condition) & watch->condition);

    case G_IO_WIN32_SOCKET:
      if (channel->last_events & FD_WRITE)
	{
	  if (channel->debug)
	    g_print ("g_io_win32_check: sock=%d event=%#x last_events has FD_WRITE\n",
		     channel->fd, watch->pollfd.fd);
	}
      else
	{
	  WSAEnumNetworkEvents (channel->fd, 0, &events);

	  if (channel->debug)
	    g_print ("g_io_win32_check: WSAEnumNetworkEvents (%d, %#x) revents={%s} condition={%s} events={%s}\n",
		     channel->fd, watch->pollfd.fd,
		     condition_to_string (watch->pollfd.revents),
		     condition_to_string (watch->condition),
		     event_mask_to_string (events.lNetworkEvents));
	  
	  if (watch->pollfd.revents != 0 &&
	      events.lNetworkEvents == 0 &&
	      !(channel->event_mask & FD_WRITE))
	    {
	      channel->event_mask = 0;
	      if (channel->debug)
		g_print ("g_io_win32_check: WSAEventSelect(%d, %#x, {})\n",
			 channel->fd, watch->pollfd.fd);
	      WSAEventSelect (channel->fd, (HANDLE) watch->pollfd.fd, 0);
	      if (channel->debug)
		g_print ("g_io_win32_check: ResetEvent(%#x)\n",
			 watch->pollfd.fd);
	      ResetEvent ((HANDLE) watch->pollfd.fd);
	    }
	  channel->last_events = events.lNetworkEvents;
	}
      watch->pollfd.revents = 0;
      if (channel->last_events & (FD_READ | FD_ACCEPT))
	watch->pollfd.revents |= G_IO_IN;
      if (channel->last_events & (FD_WRITE | FD_CONNECT))
	watch->pollfd.revents |= G_IO_OUT;
      if (watch->pollfd.revents == 0 && (channel->last_events & (FD_CLOSE)))
	watch->pollfd.revents |= G_IO_HUP;
917

918 919 920 921 922 923 924 925 926
      if (!channel->write_would_have_blocked && (channel->event_mask & FD_WRITE))
	watch->pollfd.revents |= G_IO_OUT; /* This sucks but... */

      return ((watch->pollfd.revents | buffer_condition) & watch->condition);

    default:
      g_assert_not_reached ();
      abort ();
    }
927 928 929
}

static gboolean
930 931 932
g_io_win32_dispatch (GSource     *source,
		     GSourceFunc  callback,
		     gpointer     user_data)
933
{
934
  GIOFunc func = (GIOFunc)callback;
935
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
936
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
937
  GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
938
  
939 940
  if (!func)
    {
941
      g_warning (G_STRLOC ": GIOWin32Watch dispatched without callback\n"
942 943 944 945
		 "You must call g_source_connect().");
      return FALSE;
    }
  
946 947 948 949 950 951
  if (channel->debug)
    g_print ("g_io_win32_dispatch: pollfd.revents=%s condition=%s result=%s\n",
	     condition_to_string (watch->pollfd.revents),
	     condition_to_string (watch->condition),
	     condition_to_string ((watch->pollfd.revents | buffer_condition) & watch->condition));

952
  return (*func) (watch->channel,
953
		  (watch->pollfd.revents | buffer_condition) & watch->condition,
954
		  user_data);
955 956 957
}

static void
958
g_io_win32_finalize (GSource *source)
959
{
960
  GIOWin32Watch *watch = (GIOWin32Watch *)source;
961
  GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
962
  
963 964 965 966
  switch (channel->type)
    {
    case G_IO_WIN32_WINDOWS_MESSAGES:
      break;
967

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
    case G_IO_WIN32_FILE_DESC:
      LOCK (channel->mutex);
      if (channel->debug)
	g_print ("g_io_win32_finalize: channel with thread %#x\n",
		 channel->thread_id);
      UNLOCK (channel->mutex);
      break;

    case G_IO_WIN32_SOCKET:
      if (channel->debug)
	g_print ("g_io_win32_finalize: channel is for sock=%d\n", channel->fd);
#if 0
      CloseHandle ((HANDLE) watch->pollfd.fd);
      channel->event = 0;
      channel->event_mask = 0;
#endif
      break;

    default:
      g_assert_not_reached ();
      abort ();
    }
990
  g_io_channel_unref (watch->channel);
991 992
}

993
GSourceFuncs g_io_watch_funcs = {
994 995 996
  g_io_win32_prepare,
  g_io_win32_check,
  g_io_win32_dispatch,
997
  g_io_win32_finalize
998
};
999

1000
static GIOStatus
1001 1002
g_io_win32_msg_read (GIOChannel *channel,
		     gchar      *buf,
1003 1004 1005
		     gsize       count,
		     gsize      *bytes_read,
		     GError    **err)
1006
{
1007
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1008 1009
  MSG msg;               /* In case of alignment problems */
  
1010
  if (count < sizeof (MSG))
1011
    {
1012 1013
      g_set_error (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_INVAL,
		   "Incorrect message size"); /* Informative enough error message? */
1014 1015
      return G_IO_STATUS_ERROR;
    }
1016
  
1017 1018
  if (win32_channel->debug)
    g_print ("g_io_win32_msg_read: for %#x\n",
1019
	     (guint) win32_channel->hwnd);
1020
  if (!PeekMessage (&msg, win32_channel->hwnd, 0, 0, PM_REMOVE))
1021
    return G_IO_STATUS_AGAIN;
1022

1023 1024
  memmove (buf, &msg, sizeof (MSG));
  *bytes_read = sizeof (MSG);
1025

1026
  return G_IO_STATUS_NORMAL;
1027
}
1028

1029 1030 1031 1032 1033 1034
static GIOStatus
g_io_win32_msg_write (GIOChannel  *channel,
		      const gchar *buf,
		      gsize        count,
		      gsize       *bytes_written,
		      GError     **err)
1035
{
1036
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1037
  MSG msg;
1038
  
1039
  if (count != sizeof (MSG))
1040
    {
1041 1042
      g_set_error (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_INVAL,
		   "Incorrect message size"); /* Informative enough error message? */
1043 1044
      return G_IO_STATUS_ERROR;
    }
1045
  
1046 1047 1048
  /* In case of alignment problems */
  memmove (&msg, buf, sizeof (MSG));
  if (!PostMessage (win32_channel->hwnd, msg.message, msg.wParam, msg.lParam))
1049
    {
1050
      gchar *emsg = g_win32_error_message (GetLastError ());
1051
      g_set_error (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED, emsg);
1052
      g_free (emsg);
1053 1054 1055
      return G_IO_STATUS_ERROR;
    }

1056
  *bytes_written = sizeof (MSG);
1057 1058

  return G_IO_STATUS_NORMAL;
1059 1060
}

1061 1062 1063
static GIOStatus
g_io_win32_msg_close (GIOChannel *channel,
		      GError    **err)
1064 1065
{
  /* Nothing to be done. Or should we set hwnd to some invalid value? */
1066 1067

  return G_IO_STATUS_NORMAL;
1068 1069
}

1070
static void
1071 1072
g_io_win32_free (GIOChannel *channel)
{
1073
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1074
  
1075
  if (win32_channel->debug)
1076
    g_print ("g_io_win32_free channel fd=%d\n", win32_channel->fd);
1077

1078 1079 1080 1081
  if (win32_channel->data_avail_event)
    CloseHandle (win32_channel->data_avail_event);
  if (win32_channel->space_avail_event)
    CloseHandle (win32_channel->space_avail_event);
1082 1083
  if (win32_channel->type == G_IO_WIN32_SOCKET)
    WSAEventSelect (win32_channel->fd, NULL, 0);
1084
  DeleteCriticalSection (&win32_channel->mutex);
1085

1086
  g_free (win32_channel->buffer);
1087 1088 1089
  g_free (win32_channel);
}

1090
static GSource *
1091 1092
g_io_win32_msg_create_watch (GIOChannel   *channel,
			     GIOCondition  condition)
1093
{
1094 1095 1096
  GIOWin32Watch *watch;
  GSource *source;

1097
  source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
1098
  watch = (GIOWin32Watch *)source;
1099 1100 1101
  
  watch->channel = channel;
  g_io_channel_ref (channel);
1102
  
1103
  watch->condition = condition;
1104
  
1105 1106
  watch->pollfd.fd = G_WIN32_MSG_HANDLE;
  watch->pollfd.events = condition;
1107
  
1108
  g_source_add_poll (source, &watch->pollfd);
1109
  
1110
  return source;
1111 1112
}

1113
static GIOStatus
1114
g_io_win32_fd_read (GIOChannel *channel,
1115
		    gchar      *buf,
1116 1117 1118
		    gsize       count,
		    gsize      *bytes_read,
		    GError    **err)
1119
{
1120
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1121
  gint result;
1122
  
1123
  if (win32_channel->debug)
1124
    g_print ("g_io_win32_fd_read: fd=%d count=%d\n",
1125 1126
	     win32_channel->fd, count);
  
1127 1128
  if (win32_channel->thread_id)
    {
1129
      return buffer_read (win32_channel, buf, count, bytes_read, err);
1130
    }
1131 1132

  result = read (win32_channel->fd, buf, count);
1133

1134
  if (win32_channel->debug)
1135
    g_print ("g_io_win32_fd_read: read() => %d\n", result);
1136

1137 1138 1139
  if (result < 0)
    {
      *bytes_read = 0;
1140

1141
      switch (errno)
1142 1143
        {
#ifdef EAGAIN
1144 1145
	case EAGAIN:
	  return G_IO_STATUS_AGAIN;
1146
#endif
1147 1148 1149 1150 1151
	default:
	  g_set_error (err, G_IO_CHANNEL_ERROR,
		       g_io_channel_error_from_errno (errno),
		       g_strerror (errno));
	  return G_IO_STATUS_ERROR;
1152
        }
1153
    }
1154 1155 1156 1157

  *bytes_read = result;

  return (result > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
1158
}
1159

1160 1161 1162 1163 1164 1165
static GIOStatus
g_io_win32_fd_write (GIOChannel  *channel,
		     const gchar *buf,
		     gsize        count,
		     gsize       *bytes_written,
		     GError     **err)
1166
{
1167
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1168
  gint result;
1169 1170 1171 1172 1173

  if (win32_channel->thread_id)
    {
      return buffer_write (win32_channel, buf, count, bytes_written, err);
    }
1174
  
1175
  result = write (win32_channel->fd, buf, count);
1176
  if (win32_channel->debug)
1177
    g_print ("g_io_win32_fd_write: fd=%d count=%d => %d\n",
1178
	     win32_channel->fd, count, result);
1179

1180 1181 1182
  if (result < 0)
    {
      *bytes_written = 0;
1183

1184
      switch (errno)
1185 1186
        {
#ifdef EAGAIN
1187 1188
	case EAGAIN:
	  return G_IO_STATUS_AGAIN;
1189
#endif
1190 1191 1192 1193 1194
	default:
	  g_set_error (err, G_IO_CHANNEL_ERROR,
		       g_io_channel_error_from_errno (errno),
		       g_strerror (errno));
	  return G_IO_STATUS_ERROR;
1195
        }
1196
    }
1197 1198 1199 1200

  *bytes_written = result;

  return G_IO_STATUS_NORMAL;
1201 1202
}

1203
static GIOStatus
1204
g_io_win32_fd_seek (GIOChannel *channel,
Owen Taylor's avatar
Owen Taylor committed
1205
		    gint64      offset,
1206 1207
		    GSeekType   type,
		    GError    **err)
1208
{
1209
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1210
  int whence;
Owen Taylor's avatar
Owen Taylor committed
1211
  off_t tmp_offset;
1212
  off_t result;
1213
  
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
  switch (type)
    {
    case G_SEEK_SET:
      whence = SEEK_SET;
      break;
    case G_SEEK_CUR:
      whence = SEEK_CUR;
      break;
    case G_SEEK_END:
      whence = SEEK_END;
      break;
    default:
1226
      whence = -1; /* Keep the compiler quiet */
1227
      g_assert_not_reached ();
1228
      abort ();
1229
    }
Owen Taylor's avatar
Owen Taylor committed
1230 1231 1232 1233 1234 1235

  tmp_offset = offset;
  if (tmp_offset != offset)
    {
      g_set_error (err, G_IO_CHANNEL_ERROR,
		   g_io_channel_error_from_errno (EINVAL),
Owen Taylor's avatar
Owen Taylor committed
1236
		   g_strerror (EINVAL));
Owen Taylor's avatar
Owen Taylor committed
1237 1238
      return G_IO_STATUS_ERROR;
    }
1239
  
Owen Taylor's avatar
Owen Taylor committed
1240
  result = lseek (win32_channel->fd, tmp_offset, whence);
1241 1242 1243
  
  if (result < 0)
    {
1244
      g_set_error (err, G_IO_CHANNEL_ERROR,
1245
		   g_io_channel_error_from_errno (errno),
Owen Taylor's avatar
Owen Taylor committed
1246
		   g_strerror (errno));
1247
      return G_IO_STATUS_ERROR;
1248
    }
1249 1250

  return G_IO_STATUS_NORMAL;
1251 1252
}

1253 1254 1255
static GIOStatus
g_io_win32_fd_close (GIOChannel *channel,
	             GError    **err)
1256
{
1257
  GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1258
  
1259 1260 1261 1262 1263 1264 1265 1266
  if (win32_channel->debug)
    g_print ("thread %#x: closing fd %d\n",
	     win32_channel->thread_id,
	     win32_channel->fd);
  LOCK (win32_channel->mutex);
  if (win32_channel->running)
    {
      if (win32_channel->debug)
Tor Lillqvist's avatar