Bug 556186 – gpoll.h breaks gmain.h inclusion
[platform/upstream/glib.git] / glib / giowin32.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * giowin32.c: IO Channels for Win32.
5  * 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  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * 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  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /*
26  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
27  * file for a list of people on the GLib Team.  See the ChangeLog
28  * files for a list of changes.  These files are distributed with
29  * GLib at ftp://ftp.gtk.org/pub/gtk/.
30  */
31
32 /*
33  * Bugs that are related to the code in this file:
34  *
35  * Bug 137968 - Sometimes a GIOFunc on Win32 is called with zero condition
36  * http://bugzilla.gnome.org/show_bug.cgi?id=137968
37  *
38  * Bug 324234 - Using g_io_add_watch_full() to wait for connect() to return on a non-blocking socket returns prematurely
39  * http://bugzilla.gnome.org/show_bug.cgi?id=324234
40  *
41  * Bug 331214 - g_io_channel async socket io stalls
42  * http://bugzilla.gnome.org/show_bug.cgi?id=331214
43  *
44  * Bug 338943 - Multiple watches on the same socket
45  * http://bugzilla.gnome.org/show_bug.cgi?id=338943
46  *
47  * Bug 357674 - 2 serious bugs in giowin32.c making glib iochannels useless
48  * http://bugzilla.gnome.org/show_bug.cgi?id=357674
49  *
50  * Bug 425156 - GIOChannel deadlocks on a win32 socket
51  * http://bugzilla.gnome.org/show_bug.cgi?id=425156
52  *
53  * Bug 468910 - giofunc condition=0
54  * http://bugzilla.gnome.org/show_bug.cgi?id=468910
55  *
56  * Bug 500246 - Bug fixes for giowin32
57  * http://bugzilla.gnome.org/show_bug.cgi?id=500246
58  *
59  * Bug 548278 - Async GETs connections are always terminated unexpectedly on windows
60  * http://bugzilla.gnome.org/show_bug.cgi?id=548278
61  *
62  * Bug 548536 - giowin32 problem when adding and removing watches
63  * http://bugzilla.gnome.org/show_bug.cgi?id=548536
64  *
65  * When fixing bugs related to the code in this file, either the above
66  * bugs or others, make sure that the test programs attached to the
67  * above bugs continue to work.
68  */
69
70 #include "config.h"
71
72 #include "glib.h"
73
74 #include <stdlib.h>
75 #include <winsock2.h>
76 #include <windows.h>
77 #include <conio.h>
78 #include <fcntl.h>
79 #include <io.h>
80 #include <process.h>
81 #include <errno.h>
82 #include <sys/stat.h>
83
84 #include "gstdio.h"
85 #include "glibintl.h"
86
87 #include "galias.h"
88
89 typedef struct _GIOWin32Channel GIOWin32Channel;
90 typedef struct _GIOWin32Watch GIOWin32Watch;
91
92 #define BUFFER_SIZE 4096
93
94 typedef enum {
95   G_IO_WIN32_WINDOWS_MESSAGES,  /* Windows messages */
96
97   G_IO_WIN32_FILE_DESC,         /* Unix-like file descriptors from
98                                  * _open() or _pipe(), except for
99                                  * console IO. Separate thread to read
100                                  * or write.
101                                  */
102
103   G_IO_WIN32_CONSOLE,           /* Console IO (usually stdin, stdout, stderr) */
104
105   G_IO_WIN32_SOCKET             /* Sockets. No separate thread. */
106 } GIOWin32ChannelType;
107
108 struct _GIOWin32Channel {
109   GIOChannel channel;
110   gint fd;                      /* Either a Unix-like file handle as provided
111                                  * by the Microsoft C runtime, or a SOCKET
112                                  * as provided by WinSock.
113                                  */
114   GIOWin32ChannelType type;
115   
116   gboolean debug;
117
118   /* Field used by G_IO_WIN32_WINDOWS_MESSAGES channels */
119   HWND hwnd;                    /* Handle of window, or NULL */
120   
121   /* Fields used by G_IO_WIN32_FILE_DESC channels. */
122   CRITICAL_SECTION mutex;
123
124   int direction;                /* 0 means we read from it,
125                                  * 1 means we write to it.
126                                  */
127
128   gboolean running;             /* Is reader or writer thread
129                                  * running. FALSE if EOF has been
130                                  * reached by the reader thread.
131                                  */
132
133   gboolean needs_close;         /* If the channel has been closed while
134                                  * the reader thread was still running.
135                                  */
136
137   guint thread_id;              /* If non-NULL the channel has or has
138                                  * had a reader or writer thread.
139                                  */
140   HANDLE data_avail_event;
141
142   gushort revents;
143
144   /* Data is kept in a circular buffer. To be able to distinguish between
145    * empty and full buffers, we cannot fill it completely, but have to
146    * leave a one character gap.
147    *
148    * Data available is between indexes rdp and wrp-1 (modulo BUFFER_SIZE).
149    *
150    * Empty:    wrp == rdp
151    * Full:     (wrp + 1) % BUFFER_SIZE == rdp
152    * Partial:  otherwise
153    */
154   guchar *buffer;               /* (Circular) buffer */
155   gint wrp, rdp;                /* Buffer indices for writing and reading */
156   HANDLE space_avail_event;
157
158   /* Fields used by G_IO_WIN32_SOCKET channels */
159   int event_mask;
160   int last_events;
161   HANDLE event;
162   gboolean write_would_have_blocked;
163   gboolean ever_writable;
164 };
165
166 struct _GIOWin32Watch {
167   GSource       source;
168   GPollFD       pollfd;
169   GIOChannel   *channel;
170   GIOCondition  condition;
171 };
172
173 static void
174 g_win32_print_access_mode (int flags)
175 {
176   g_print ("%s%s%s%s%s%s%s%s%s%s",
177            ((flags & 0x3) == _O_RDWR ? "O_RDWR" :
178             ((flags & 0x3) == _O_RDONLY ? "O_RDONLY" :
179              ((flags & 0x3) == _O_WRONLY ? "O_WRONLY" : "0"))),
180            (flags & _O_APPEND ? "|O_APPEND" : ""),
181            (flags & _O_RANDOM ? "|O_RANDOM" : ""),
182            (flags & _O_SEQUENTIAL ? "|O_SEQUENTIAL" : ""),
183            (flags & _O_TEMPORARY ? "|O_TEMPORARY" : ""),
184            (flags & _O_CREAT ? "|O_CREAT" : ""),
185            (flags & _O_TRUNC ? "|O_TRUNC" : ""),
186            (flags & _O_EXCL ? "|O_EXCL" : ""),
187            (flags & _O_TEXT ? "|O_TEXT" : ""),
188            (flags & _O_BINARY ? "|O_BINARY" : ""));
189 }
190
191 static void
192 g_win32_print_gioflags (GIOFlags flags)
193 {
194   char *bar = "";
195
196   if (flags & G_IO_FLAG_APPEND)
197     bar = "|", g_print ("APPEND");
198   if (flags & G_IO_FLAG_NONBLOCK)
199     g_print ("%sNONBLOCK", bar), bar = "|";
200   if (flags & G_IO_FLAG_IS_READABLE)
201     g_print ("%sREADABLE", bar), bar = "|";
202   if (flags & G_IO_FLAG_IS_WRITEABLE)
203     g_print ("%sWRITEABLE", bar), bar = "|";
204   if (flags & G_IO_FLAG_IS_SEEKABLE)
205     g_print ("%sSEEKABLE", bar), bar = "|";
206 }
207
208 static const char *
209 event_mask_to_string (int mask)
210 {
211   char buf[100];
212   int checked_bits = 0;
213   char *bufp = buf;
214
215   if (mask == 0)
216     return "";
217
218 #define BIT(n) checked_bits |= FD_##n; if (mask & FD_##n) bufp += sprintf (bufp, "%s" #n, (bufp>buf ? "|" : ""))
219
220   BIT (READ);
221   BIT (WRITE);
222   BIT (OOB);
223   BIT (ACCEPT);
224   BIT (CONNECT);
225   BIT (CLOSE);
226   BIT (QOS);
227   BIT (GROUP_QOS);
228   BIT (ROUTING_INTERFACE_CHANGE);
229   BIT (ADDRESS_LIST_CHANGE);
230   
231 #undef BIT
232
233   if ((mask & ~checked_bits) != 0)
234           bufp += sprintf (bufp, "|%#x", mask & ~checked_bits);
235   
236   return g_quark_to_string (g_quark_from_string (buf));
237 }
238
239 static const char *
240 condition_to_string (GIOCondition condition)
241 {
242   char buf[100];
243   int checked_bits = 0;
244   char *bufp = buf;
245
246   if (condition == 0)
247     return "";
248
249 #define BIT(n) checked_bits |= G_IO_##n; if (condition & G_IO_##n) bufp += sprintf (bufp, "%s" #n, (bufp>buf ? "|" : ""))
250
251   BIT (IN);
252   BIT (OUT);
253   BIT (PRI);
254   BIT (ERR);
255   BIT (HUP);
256   BIT (NVAL);
257   
258 #undef BIT
259
260   if ((condition & ~checked_bits) != 0)
261           bufp += sprintf (bufp, "|%#x", condition & ~checked_bits);
262   
263   return g_quark_to_string (g_quark_from_string (buf));
264 }
265
266 static gboolean
267 g_io_win32_get_debug_flag (void)
268 {
269   return (getenv ("G_IO_WIN32_DEBUG") != NULL);
270 }
271
272 static void
273 g_io_channel_win32_init (GIOWin32Channel *channel)
274 {
275   channel->debug = g_io_win32_get_debug_flag ();
276
277   InitializeCriticalSection (&channel->mutex);
278   channel->running = FALSE;
279   channel->needs_close = FALSE;
280   channel->thread_id = 0;
281   channel->data_avail_event = NULL;
282   channel->revents = 0;
283   channel->buffer = NULL;
284   channel->space_avail_event = NULL;
285
286   channel->event_mask = 0;
287   channel->last_events = 0;
288   channel->event = NULL;
289   channel->write_would_have_blocked = FALSE;
290   channel->ever_writable = FALSE;
291 }
292
293 static void
294 create_events (GIOWin32Channel *channel)
295 {
296   SECURITY_ATTRIBUTES sec_attrs;
297   
298   sec_attrs.nLength = sizeof (SECURITY_ATTRIBUTES);
299   sec_attrs.lpSecurityDescriptor = NULL;
300   sec_attrs.bInheritHandle = FALSE;
301
302   /* The data available event is manual reset, the space available event
303    * is automatic reset.
304    */
305   if (!(channel->data_avail_event = CreateEvent (&sec_attrs, TRUE, FALSE, NULL))
306       || !(channel->space_avail_event = CreateEvent (&sec_attrs, FALSE, FALSE, NULL)))
307     {
308       gchar *emsg = g_win32_error_message (GetLastError ());
309
310       g_error ("Error creating event: %s", emsg);
311       g_free (emsg);
312     }
313 }
314
315 static unsigned __stdcall
316 read_thread (void *parameter)
317 {
318   GIOWin32Channel *channel = parameter;
319   guchar *buffer;
320   gint nbytes;
321
322   g_io_channel_ref ((GIOChannel *)channel);
323
324   if (channel->debug)
325     g_print ("read_thread %#x: start fd=%d, data_avail=%p space_avail=%p\n",
326              channel->thread_id,
327              channel->fd,
328              channel->data_avail_event,
329              channel->space_avail_event);
330
331   channel->direction = 0;
332   channel->buffer = g_malloc (BUFFER_SIZE);
333   channel->rdp = channel->wrp = 0;
334   channel->running = TRUE;
335
336   SetEvent (channel->space_avail_event);
337   
338   EnterCriticalSection (&channel->mutex);
339   while (channel->running)
340     {
341       if (channel->debug)
342         g_print ("read_thread %#x: rdp=%d, wrp=%d\n",
343                  channel->thread_id, channel->rdp, channel->wrp);
344       if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
345         {
346           /* Buffer is full */
347           if (channel->debug)
348             g_print ("read_thread %#x: resetting space_avail\n",
349                      channel->thread_id);
350           ResetEvent (channel->space_avail_event);
351           if (channel->debug)
352             g_print ("read_thread %#x: waiting for space\n",
353                      channel->thread_id);
354           LeaveCriticalSection (&channel->mutex);
355           WaitForSingleObject (channel->space_avail_event, INFINITE);
356           EnterCriticalSection (&channel->mutex);
357           if (channel->debug)
358             g_print ("read_thread %#x: rdp=%d, wrp=%d\n",
359                      channel->thread_id, channel->rdp, channel->wrp);
360         }
361       
362       buffer = channel->buffer + channel->wrp;
363       
364       /* Always leave at least one byte unused gap to be able to
365        * distinguish between the full and empty condition...
366        */
367       nbytes = MIN ((channel->rdp + BUFFER_SIZE - channel->wrp - 1) % BUFFER_SIZE,
368                     BUFFER_SIZE - channel->wrp);
369
370       if (channel->debug)
371         g_print ("read_thread %#x: calling read() for %d bytes\n",
372                  channel->thread_id, nbytes);
373
374       LeaveCriticalSection (&channel->mutex);
375
376       nbytes = read (channel->fd, buffer, nbytes);
377       
378       EnterCriticalSection (&channel->mutex);
379
380       channel->revents = G_IO_IN;
381       if (nbytes == 0)
382         channel->revents |= G_IO_HUP;
383       else if (nbytes < 0)
384         channel->revents |= G_IO_ERR;
385
386       if (channel->debug)
387         g_print ("read_thread %#x: read() returned %d, rdp=%d, wrp=%d\n",
388                  channel->thread_id, nbytes, channel->rdp, channel->wrp);
389
390       if (nbytes <= 0)
391         break;
392
393       channel->wrp = (channel->wrp + nbytes) % BUFFER_SIZE;
394       if (channel->debug)
395         g_print ("read_thread %#x: rdp=%d, wrp=%d, setting data_avail\n",
396                  channel->thread_id, channel->rdp, channel->wrp);
397       SetEvent (channel->data_avail_event);
398     }
399   
400   channel->running = FALSE;
401   if (channel->needs_close)
402     {
403       if (channel->debug)
404         g_print ("read_thread %#x: channel fd %d needs closing\n",
405                  channel->thread_id, channel->fd);
406       close (channel->fd);
407       channel->fd = -1;
408     }
409
410   if (channel->debug)
411     g_print ("read_thread %#x: EOF, rdp=%d, wrp=%d, setting data_avail\n",
412              channel->thread_id, channel->rdp, channel->wrp);
413   SetEvent (channel->data_avail_event);
414   LeaveCriticalSection (&channel->mutex);
415   
416   g_io_channel_unref ((GIOChannel *)channel);
417   
418   /* No need to call _endthreadex(), the actual thread starter routine
419    * in MSVCRT (see crt/src/threadex.c:_threadstartex) calls
420    * _endthreadex() for us.
421    */
422
423   return 0;
424 }
425
426 static unsigned __stdcall
427 write_thread (void *parameter)
428 {
429   GIOWin32Channel *channel = parameter;
430   guchar *buffer;
431   gint nbytes;
432
433   g_io_channel_ref ((GIOChannel *)channel);
434
435   if (channel->debug)
436     g_print ("write_thread %#x: start fd=%d, data_avail=%p space_avail=%p\n",
437              channel->thread_id,
438              channel->fd,
439              channel->data_avail_event,
440              channel->space_avail_event);
441   
442   channel->direction = 1;
443   channel->buffer = g_malloc (BUFFER_SIZE);
444   channel->rdp = channel->wrp = 0;
445   channel->running = TRUE;
446
447   SetEvent (channel->space_avail_event);
448
449   /* We use the same event objects as for a reader thread, but with
450    * reversed meaning. So, space_avail is used if data is available
451    * for writing, and data_avail is used if space is available in the
452    * write buffer.
453    */
454
455   EnterCriticalSection (&channel->mutex);
456   while (channel->running || channel->rdp != channel->wrp)
457     {
458       if (channel->debug)
459         g_print ("write_thread %#x: rdp=%d, wrp=%d\n",
460                  channel->thread_id, channel->rdp, channel->wrp);
461       if (channel->wrp == channel->rdp)
462         {
463           /* Buffer is empty. */
464           if (channel->debug)
465             g_print ("write_thread %#x: resetting space_avail\n",
466                      channel->thread_id);
467           ResetEvent (channel->space_avail_event);
468           if (channel->debug)
469             g_print ("write_thread %#x: waiting for data\n",
470                      channel->thread_id);
471           channel->revents = G_IO_OUT;
472           SetEvent (channel->data_avail_event);
473           LeaveCriticalSection (&channel->mutex);
474           WaitForSingleObject (channel->space_avail_event, INFINITE);
475
476           EnterCriticalSection (&channel->mutex);
477           if (channel->rdp == channel->wrp)
478             break;
479
480           if (channel->debug)
481             g_print ("write_thread %#x: rdp=%d, wrp=%d\n",
482                      channel->thread_id, channel->rdp, channel->wrp);
483         }
484       
485       buffer = channel->buffer + channel->rdp;
486       if (channel->rdp < channel->wrp)
487         nbytes = channel->wrp - channel->rdp;
488       else
489         nbytes = BUFFER_SIZE - channel->rdp;
490
491       if (channel->debug)
492         g_print ("write_thread %#x: calling write() for %d bytes\n",
493                  channel->thread_id, nbytes);
494
495       LeaveCriticalSection (&channel->mutex);
496       nbytes = write (channel->fd, buffer, nbytes);
497       EnterCriticalSection (&channel->mutex);
498
499       if (channel->debug)
500         g_print ("write_thread %#x: write(%i) returned %d, rdp=%d, wrp=%d\n",
501                  channel->thread_id, channel->fd, nbytes, channel->rdp, channel->wrp);
502
503       channel->revents = 0;
504       if (nbytes > 0)
505         channel->revents |= G_IO_OUT;
506       else if (nbytes <= 0)
507         channel->revents |= G_IO_ERR;
508
509       channel->rdp = (channel->rdp + nbytes) % BUFFER_SIZE;
510
511       if (nbytes <= 0)
512         break;
513
514       if (channel->debug)
515         g_print ("write_thread: setting data_avail for thread %#x\n",
516                  channel->thread_id);
517       SetEvent (channel->data_avail_event);
518     }
519   
520   channel->running = FALSE;
521   if (channel->needs_close)
522     {
523       if (channel->debug)
524         g_print ("write_thread %#x: channel fd %d needs closing\n",
525                  channel->thread_id, channel->fd);
526       close (channel->fd);
527       channel->fd = -1;
528     }
529
530   LeaveCriticalSection (&channel->mutex);
531   
532   g_io_channel_unref ((GIOChannel *)channel);
533   
534   return 0;
535 }
536
537 static void
538 create_thread (GIOWin32Channel     *channel,
539                GIOCondition         condition,
540                unsigned (__stdcall *thread) (void *parameter))
541 {
542   HANDLE thread_handle;
543
544   thread_handle = (HANDLE) _beginthreadex (NULL, 0, thread, channel, 0,
545                                            &channel->thread_id);
546   if (thread_handle == 0)
547     g_warning ("Error creating thread: %s.",
548                g_strerror (errno));
549   else if (!CloseHandle (thread_handle))
550     {
551       gchar *emsg = g_win32_error_message (GetLastError ());
552
553       g_warning ("Error closing thread handle: %s.", emsg);
554       g_free (emsg);
555     }
556
557   WaitForSingleObject (channel->space_avail_event, INFINITE);
558 }
559
560 static GIOStatus
561 buffer_read (GIOWin32Channel *channel,
562              gchar           *dest,
563              gsize            count,
564              gsize           *bytes_read,
565              GError         **err)
566 {
567   guint nbytes;
568   guint left = count;
569   
570   EnterCriticalSection (&channel->mutex);
571   if (channel->debug)
572     g_print ("reading from thread %#x %" G_GSIZE_FORMAT " bytes, rdp=%d, wrp=%d\n",
573              channel->thread_id, count, channel->rdp, channel->wrp);
574   
575   if (channel->wrp == channel->rdp)
576     {
577       LeaveCriticalSection (&channel->mutex);
578       if (channel->debug)
579         g_print ("waiting for data from thread %#x\n", channel->thread_id);
580       WaitForSingleObject (channel->data_avail_event, INFINITE);
581       if (channel->debug)
582         g_print ("done waiting for data from thread %#x\n", channel->thread_id);
583       EnterCriticalSection (&channel->mutex);
584       if (channel->wrp == channel->rdp && !channel->running)
585         {
586           if (channel->debug)
587             g_print ("wrp==rdp, !running\n");
588           LeaveCriticalSection (&channel->mutex);
589           *bytes_read = 0;
590           return G_IO_STATUS_EOF;
591         }
592     }
593   
594   if (channel->rdp < channel->wrp)
595     nbytes = channel->wrp - channel->rdp;
596   else
597     nbytes = BUFFER_SIZE - channel->rdp;
598   LeaveCriticalSection (&channel->mutex);
599   nbytes = MIN (left, nbytes);
600   if (channel->debug)
601     g_print ("moving %d bytes from thread %#x\n",
602              nbytes, channel->thread_id);
603   memcpy (dest, channel->buffer + channel->rdp, nbytes);
604   dest += nbytes;
605   left -= nbytes;
606   EnterCriticalSection (&channel->mutex);
607   channel->rdp = (channel->rdp + nbytes) % BUFFER_SIZE;
608   if (channel->debug)
609     g_print ("setting space_avail for thread %#x\n", channel->thread_id);
610   SetEvent (channel->space_avail_event);
611   if (channel->debug)
612     g_print ("for thread %#x: rdp=%d, wrp=%d\n",
613              channel->thread_id, channel->rdp, channel->wrp);
614   if (channel->running && channel->wrp == channel->rdp)
615     {
616       if (channel->debug)
617         g_print ("resetting data_avail of thread %#x\n",
618                  channel->thread_id);
619       ResetEvent (channel->data_avail_event);
620     };
621   LeaveCriticalSection (&channel->mutex);
622   
623   /* We have no way to indicate any errors form the actual
624    * read() or recv() call in the reader thread. Should we have?
625    */
626   *bytes_read = count - left;
627   return (*bytes_read > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
628 }
629
630
631 static GIOStatus
632 buffer_write (GIOWin32Channel *channel,
633               const gchar     *dest,
634               gsize            count,
635               gsize           *bytes_written,
636               GError         **err)
637 {
638   guint nbytes;
639   guint left = count;
640   
641   EnterCriticalSection (&channel->mutex);
642   if (channel->debug)
643     g_print ("buffer_write: writing to thread %#x %" G_GSIZE_FORMAT " bytes, rdp=%d, wrp=%d\n",
644              channel->thread_id, count, channel->rdp, channel->wrp);
645   
646   if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
647     {
648       /* Buffer is full */
649       if (channel->debug)
650         g_print ("buffer_write: tid %#x: resetting data_avail\n",
651                  channel->thread_id);
652       ResetEvent (channel->data_avail_event);
653       if (channel->debug)
654         g_print ("buffer_write: tid %#x: waiting for space\n",
655                  channel->thread_id);
656       LeaveCriticalSection (&channel->mutex);
657       WaitForSingleObject (channel->data_avail_event, INFINITE);
658       EnterCriticalSection (&channel->mutex);
659       if (channel->debug)
660         g_print ("buffer_write: tid %#x: rdp=%d, wrp=%d\n",
661                  channel->thread_id, channel->rdp, channel->wrp);
662     }
663    
664   nbytes = MIN ((channel->rdp + BUFFER_SIZE - channel->wrp - 1) % BUFFER_SIZE,
665                 BUFFER_SIZE - channel->wrp);
666
667   LeaveCriticalSection (&channel->mutex);
668   nbytes = MIN (left, nbytes);
669   if (channel->debug)
670     g_print ("buffer_write: tid %#x: writing %d bytes\n",
671              channel->thread_id, nbytes);
672   memcpy (channel->buffer + channel->wrp, dest, nbytes);
673   dest += nbytes;
674   left -= nbytes;
675   EnterCriticalSection (&channel->mutex);
676
677   channel->wrp = (channel->wrp + nbytes) % BUFFER_SIZE;
678   if (channel->debug)
679     g_print ("buffer_write: tid %#x: rdp=%d, wrp=%d, setting space_avail\n",
680              channel->thread_id, channel->rdp, channel->wrp);
681   SetEvent (channel->space_avail_event);
682
683   if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
684     {
685       /* Buffer is full */
686       if (channel->debug)
687         g_print ("buffer_write: tid %#x: resetting data_avail\n",
688                  channel->thread_id);
689       ResetEvent (channel->data_avail_event);
690     }
691
692   LeaveCriticalSection (&channel->mutex);
693   
694   /* We have no way to indicate any errors form the actual
695    * write() call in the writer thread. Should we have?
696    */
697   *bytes_written = count - left;
698   return (*bytes_written > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
699 }
700
701
702 static gboolean
703 g_io_win32_prepare (GSource *source,
704                     gint    *timeout)
705 {
706   GIOWin32Watch *watch = (GIOWin32Watch *)source;
707   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
708   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
709   int event_mask;
710   
711   *timeout = -1;
712   
713   if (channel->debug)
714     g_print ("g_io_win32_prepare: source=%p channel=%p", source, channel);
715
716   switch (channel->type)
717     {
718     case G_IO_WIN32_WINDOWS_MESSAGES:
719       if (channel->debug)
720         g_print (" MSG");
721       break;
722
723     case G_IO_WIN32_CONSOLE:
724       if (channel->debug)
725         g_print (" CON");
726       break;
727
728     case G_IO_WIN32_FILE_DESC:
729       if (channel->debug)
730         g_print (" FD thread=%#x buffer_condition:{%s}"
731                  "\n  watch->pollfd.events:{%s} watch->pollfd.revents:{%s} channel->revents:{%s}",
732                  channel->thread_id, condition_to_string (buffer_condition),
733                  condition_to_string (watch->pollfd.events),
734                  condition_to_string (watch->pollfd.revents),
735                  condition_to_string (channel->revents));
736       
737       EnterCriticalSection (&channel->mutex);
738       if (channel->running)
739         {
740           if (channel->direction == 0 && channel->wrp == channel->rdp)
741             {
742               if (channel->debug)
743                 g_print ("\n  setting revents=0");
744               channel->revents = 0;
745             }
746         }
747       else
748         {
749           if (channel->direction == 1
750               && (channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
751             {
752               if (channel->debug)
753                 g_print ("\n setting revents=0");
754               channel->revents = 0;
755             }
756         }         
757       LeaveCriticalSection (&channel->mutex);
758       break;
759
760     case G_IO_WIN32_SOCKET:
761       if (channel->debug)
762         g_print (" SOCK");
763       event_mask = 0;
764       if (watch->condition & G_IO_IN)
765         event_mask |= (FD_READ | FD_ACCEPT);
766       if (watch->condition & G_IO_OUT)
767         event_mask |= (FD_WRITE | FD_CONNECT);
768       event_mask |= FD_CLOSE;
769
770       if (channel->event_mask != event_mask)
771         {
772           if (channel->debug)
773             g_print ("\n  WSAEventSelect(%d,%p,{%s})",
774                      channel->fd, (HANDLE) watch->pollfd.fd,
775                      event_mask_to_string (event_mask));
776           if (WSAEventSelect (channel->fd, (HANDLE) watch->pollfd.fd,
777                               event_mask) == SOCKET_ERROR)
778             if (channel->debug)
779               {
780                 gchar *emsg = g_win32_error_message (WSAGetLastError ());
781
782                 g_print (" failed: %s", emsg);
783                 g_free (emsg);
784               }
785           channel->event_mask = event_mask;
786
787           if (channel->debug)
788             g_print ("\n  setting last_events=0");
789           channel->last_events = 0;
790
791           if ((event_mask & FD_WRITE) &&
792               channel->ever_writable &&
793               !channel->write_would_have_blocked)
794             {
795               if (channel->debug)
796                 g_print (" WSASetEvent(%p)", (WSAEVENT) watch->pollfd.fd);
797               WSASetEvent ((WSAEVENT) watch->pollfd.fd);
798             }
799         }
800       break;
801
802     default:
803       g_assert_not_reached ();
804       abort ();
805     }
806   if (channel->debug)
807     g_print ("\n");
808
809   return ((watch->condition & buffer_condition) == watch->condition);
810 }
811
812 static gboolean
813 g_io_win32_check (GSource *source)
814 {
815   MSG msg;
816   GIOWin32Watch *watch = (GIOWin32Watch *)source;
817   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
818   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
819   WSANETWORKEVENTS events;
820
821   if (channel->debug)
822     g_print ("g_io_win32_check: source=%p channel=%p", source, channel);
823
824   switch (channel->type)
825     {
826     case G_IO_WIN32_WINDOWS_MESSAGES:
827       if (channel->debug)
828         g_print (" MSG\n");
829       return (PeekMessage (&msg, channel->hwnd, 0, 0, PM_NOREMOVE));
830
831     case G_IO_WIN32_FILE_DESC:
832       if (channel->debug)
833         g_print (" FD thread=%#x buffer_condition=%s\n"
834                  "  watch->pollfd.events={%s} watch->pollfd.revents={%s} channel->revents={%s}\n",
835                  channel->thread_id, condition_to_string (buffer_condition),
836                  condition_to_string (watch->pollfd.events),
837                  condition_to_string (watch->pollfd.revents),
838                  condition_to_string (channel->revents));
839       
840       watch->pollfd.revents = (watch->pollfd.events & channel->revents);
841
842       return ((watch->pollfd.revents | buffer_condition) & watch->condition);
843
844     case G_IO_WIN32_CONSOLE:
845       if (channel->debug)
846         g_print (" CON\n");
847       if (watch->channel->is_writeable)
848         return TRUE;
849       else if (watch->channel->is_readable)
850         {
851           INPUT_RECORD buffer;
852           DWORD n;
853           if (PeekConsoleInput ((HANDLE) watch->pollfd.fd, &buffer, 1, &n) &&
854               n == 1)
855             {
856               /* _kbhit() does quite complex processing to find out
857                * whether at least one of the key events pending corresponds
858                * to a "real" character that can be read.
859                */
860               if (_kbhit ())
861                 return TRUE;
862               
863               /* Discard all other kinds of events */
864               ReadConsoleInput ((HANDLE) watch->pollfd.fd, &buffer, 1, &n);
865             }
866         }
867       return FALSE;
868
869     case G_IO_WIN32_SOCKET:
870       if (channel->debug)
871         g_print (" SOCK");
872       if (channel->last_events & FD_WRITE)
873         {
874           if (channel->debug)
875             g_print (" sock=%d event=%p last_events has FD_WRITE",
876                      channel->fd, (HANDLE) watch->pollfd.fd);
877         }
878       else
879         {
880           WSAEnumNetworkEvents (channel->fd, 0, &events);
881
882           if (channel->debug)
883             g_print ("\n  revents={%s} condition={%s}"
884                      "\n  WSAEnumNetworkEvents(%d,0) sets events={%s}",
885                      condition_to_string (watch->pollfd.revents),
886                      condition_to_string (watch->condition),
887                      channel->fd, 
888                      event_mask_to_string (events.lNetworkEvents));
889           
890           if (watch->pollfd.revents != 0 &&
891               events.lNetworkEvents == 0 &&
892               !(channel->event_mask & FD_WRITE))
893             {
894               channel->event_mask = 0;
895               if (channel->debug)
896                 g_print ("\n  WSAEventSelect(%d,%p,{})",
897                          channel->fd, (HANDLE) watch->pollfd.fd);
898               WSAEventSelect (channel->fd, (HANDLE) watch->pollfd.fd, 0);
899               if (channel->debug)
900                 g_print ("  ResetEvent(%p)",
901                          (HANDLE) watch->pollfd.fd);
902               ResetEvent ((HANDLE) watch->pollfd.fd);
903             }
904           else if (events.lNetworkEvents & FD_WRITE)
905             channel->ever_writable = TRUE;
906           channel->last_events = events.lNetworkEvents;
907         }
908
909       watch->pollfd.revents = 0;
910       if (channel->last_events & (FD_READ | FD_ACCEPT))
911         watch->pollfd.revents |= G_IO_IN;
912
913       if (channel->last_events & FD_WRITE)
914         watch->pollfd.revents |= G_IO_OUT;
915       else
916         {
917           /* We have called WSAEnumNetworkEvents() above but it didn't
918            * set FD_WRITE.
919            */
920           if (events.lNetworkEvents & FD_CONNECT)
921             {
922               if (events.iErrorCode[FD_CONNECT_BIT] == 0)
923                 watch->pollfd.revents |= G_IO_OUT;
924               else
925                 watch->pollfd.revents |= (G_IO_HUP | G_IO_ERR);
926             }
927           if (watch->pollfd.revents == 0 && (channel->last_events & (FD_CLOSE)))
928             watch->pollfd.revents |= G_IO_HUP;
929         }
930
931       /* Regardless of WSAEnumNetworkEvents() result, if watching for
932        * writability, and if we have ever got a FD_WRITE event, and
933        * unless last write would have blocked, set G_IO_OUT. But never
934        * set both G_IO_OUT and G_IO_HUP.
935        */
936       if (!(watch->pollfd.revents & G_IO_HUP) &&
937           channel->ever_writable &&
938           !channel->write_would_have_blocked &&
939           (channel->event_mask & FD_WRITE))
940         watch->pollfd.revents |= G_IO_OUT;
941
942       if (channel->debug)
943         g_print ("\n  revents={%s} retval={%s}\n",
944                  condition_to_string (watch->pollfd.revents),
945                  condition_to_string ((watch->pollfd.revents | buffer_condition) & watch->condition));
946
947       return ((watch->pollfd.revents | buffer_condition) & watch->condition);
948
949     default:
950       g_assert_not_reached ();
951       abort ();
952     }
953 }
954
955 static gboolean
956 g_io_win32_dispatch (GSource     *source,
957                      GSourceFunc  callback,
958                      gpointer     user_data)
959 {
960   GIOFunc func = (GIOFunc)callback;
961   GIOWin32Watch *watch = (GIOWin32Watch *)source;
962   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
963   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
964   
965   if (!func)
966     {
967       g_warning ("IO Watch dispatched without callback\n"
968                  "You must call g_source_connect().");
969       return FALSE;
970     }
971   
972   if (channel->debug)
973     g_print ("g_io_win32_dispatch: pollfd.revents=%s condition=%s result=%s\n",
974              condition_to_string (watch->pollfd.revents),
975              condition_to_string (watch->condition),
976              condition_to_string ((watch->pollfd.revents | buffer_condition) & watch->condition));
977
978   return (*func) (watch->channel,
979                   (watch->pollfd.revents | buffer_condition) & watch->condition,
980                   user_data);
981 }
982
983 static void
984 g_io_win32_finalize (GSource *source)
985 {
986   GIOWin32Watch *watch = (GIOWin32Watch *)source;
987   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
988   
989   if (channel->debug)
990     g_print ("g_io_win32_finalize: source=%p channel=%p", source, channel);
991
992   switch (channel->type)
993     {
994     case G_IO_WIN32_WINDOWS_MESSAGES:
995       if (channel->debug)
996         g_print (" MSG");
997       break;
998
999     case G_IO_WIN32_CONSOLE:
1000       if (channel->debug)
1001         g_print (" CON");
1002       break;
1003
1004     case G_IO_WIN32_FILE_DESC:
1005       if (channel->debug)
1006         g_print (" FD thread=%#x", channel->thread_id);
1007       break;
1008
1009     case G_IO_WIN32_SOCKET:
1010       if (channel->debug)
1011         g_print (" SOCK sock=%d", channel->fd);
1012       break;
1013
1014     default:
1015       g_assert_not_reached ();
1016       abort ();
1017     }
1018   if (channel->debug)
1019     g_print ("\n");
1020   g_io_channel_unref (watch->channel);
1021 }
1022
1023 GSourceFuncs g_io_watch_funcs = {
1024   g_io_win32_prepare,
1025   g_io_win32_check,
1026   g_io_win32_dispatch,
1027   g_io_win32_finalize
1028 };
1029
1030 static GIOStatus
1031 g_io_win32_msg_read (GIOChannel *channel,
1032                      gchar      *buf,
1033                      gsize       count,
1034                      gsize      *bytes_read,
1035                      GError    **err)
1036 {
1037   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1038   MSG msg;               /* In case of alignment problems */
1039   
1040   if (count < sizeof (MSG))
1041     {
1042       g_set_error_literal (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_INVAL,
1043                            "Incorrect message size"); /* Informative enough error message? */
1044       return G_IO_STATUS_ERROR;
1045     }
1046   
1047   if (win32_channel->debug)
1048     g_print ("g_io_win32_msg_read: channel=%p hwnd=%p\n",
1049              channel, win32_channel->hwnd);
1050   if (!PeekMessage (&msg, win32_channel->hwnd, 0, 0, PM_REMOVE))
1051     return G_IO_STATUS_AGAIN;
1052
1053   memmove (buf, &msg, sizeof (MSG));
1054   *bytes_read = sizeof (MSG);
1055
1056   return G_IO_STATUS_NORMAL;
1057 }
1058
1059 static GIOStatus
1060 g_io_win32_msg_write (GIOChannel  *channel,
1061                       const gchar *buf,
1062                       gsize        count,
1063                       gsize       *bytes_written,
1064                       GError     **err)
1065 {
1066   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1067   MSG msg;
1068   
1069   if (count != sizeof (MSG))
1070     {
1071       g_set_error_literal (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_INVAL,
1072                            "Incorrect message size"); /* Informative enough error message? */
1073       return G_IO_STATUS_ERROR;
1074     }
1075   
1076   /* In case of alignment problems */
1077   memmove (&msg, buf, sizeof (MSG));
1078   if (!PostMessage (win32_channel->hwnd, msg.message, msg.wParam, msg.lParam))
1079     {
1080       gchar *emsg = g_win32_error_message (GetLastError ());
1081
1082       g_set_error_literal (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED, emsg);
1083       g_free (emsg);
1084
1085       return G_IO_STATUS_ERROR;
1086     }
1087
1088   *bytes_written = sizeof (MSG);
1089
1090   return G_IO_STATUS_NORMAL;
1091 }
1092
1093 static GIOStatus
1094 g_io_win32_msg_close (GIOChannel *channel,
1095                       GError    **err)
1096 {
1097   /* Nothing to be done. Or should we set hwnd to some invalid value? */
1098
1099   return G_IO_STATUS_NORMAL;
1100 }
1101
1102 static void
1103 g_io_win32_free (GIOChannel *channel)
1104 {
1105   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1106   
1107   if (win32_channel->debug)
1108     g_print ("g_io_win32_free channel=%p fd=%d\n", channel, win32_channel->fd);
1109
1110   DeleteCriticalSection (&win32_channel->mutex);
1111
1112   if (win32_channel->data_avail_event)
1113     if (!CloseHandle (win32_channel->data_avail_event))
1114       if (win32_channel->debug)
1115         {
1116           gchar *emsg = g_win32_error_message (GetLastError ());
1117
1118           g_print ("  CloseHandle(%p) failed: %s\n",
1119                    win32_channel->data_avail_event, emsg);
1120           g_free (emsg);
1121         }
1122
1123   g_free (win32_channel->buffer);
1124
1125   if (win32_channel->space_avail_event)
1126     if (!CloseHandle (win32_channel->space_avail_event))
1127       if (win32_channel->debug)
1128         {
1129           gchar *emsg = g_win32_error_message (GetLastError ());
1130
1131           g_print ("  CloseHandle(%p) failed: %s\n",
1132                    win32_channel->space_avail_event, emsg);
1133           g_free (emsg);
1134         }
1135
1136   if (win32_channel->type == G_IO_WIN32_SOCKET)
1137     if (WSAEventSelect (win32_channel->fd, NULL, 0) == SOCKET_ERROR)
1138       if (win32_channel->debug)
1139         {
1140           gchar *emsg = g_win32_error_message (WSAGetLastError ());
1141
1142           g_print ("  WSAEventSelect(%d,NULL,{}) failed: %s\n",
1143                    win32_channel->fd, emsg);
1144           g_free (emsg);
1145         }
1146
1147   if (win32_channel->event)
1148     if (!WSACloseEvent (win32_channel->event))
1149       if (win32_channel->debug)
1150         {
1151           gchar *emsg = g_win32_error_message (WSAGetLastError ());
1152
1153           g_print ("  WSACloseEvent(%p) failed: %s\n",
1154                    win32_channel->event, emsg);
1155           g_free (emsg);
1156         }
1157
1158   g_free (win32_channel);
1159 }
1160
1161 static GSource *
1162 g_io_win32_msg_create_watch (GIOChannel   *channel,
1163                              GIOCondition  condition)
1164 {
1165   GIOWin32Watch *watch;
1166   GSource *source;
1167
1168   source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
1169   watch = (GIOWin32Watch *)source;
1170   
1171   watch->channel = channel;
1172   g_io_channel_ref (channel);
1173   
1174   watch->condition = condition;
1175   
1176   watch->pollfd.fd = (gintptr) G_WIN32_MSG_HANDLE;
1177   watch->pollfd.events = condition;
1178   
1179   g_source_add_poll (source, &watch->pollfd);
1180   
1181   return source;
1182 }
1183
1184 static GIOStatus
1185 g_io_win32_fd_and_console_read (GIOChannel *channel,
1186                                 gchar      *buf,
1187                                 gsize       count,
1188                                 gsize      *bytes_read,
1189                                 GError    **err)
1190 {
1191   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1192   gint result;
1193   
1194   if (win32_channel->debug)
1195     g_print ("g_io_win32_fd_read: fd=%d count=%" G_GSIZE_FORMAT "\n",
1196              win32_channel->fd, count);
1197   
1198   if (win32_channel->thread_id)
1199     {
1200       return buffer_read (win32_channel, buf, count, bytes_read, err);
1201     }
1202
1203   result = read (win32_channel->fd, buf, count);
1204
1205   if (win32_channel->debug)
1206     g_print ("g_io_win32_fd_read: read() => %d\n", result);
1207
1208   if (result < 0)
1209     {
1210       *bytes_read = 0;
1211
1212       switch (errno)
1213         {
1214 #ifdef EAGAIN
1215         case EAGAIN:
1216           return G_IO_STATUS_AGAIN;
1217 #endif
1218         default:
1219           g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1220                                g_io_channel_error_from_errno (errno),
1221                                g_strerror (errno));
1222           return G_IO_STATUS_ERROR;
1223         }
1224     }
1225
1226   *bytes_read = result;
1227
1228   return (result > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
1229 }
1230
1231 static GIOStatus
1232 g_io_win32_fd_and_console_write (GIOChannel  *channel,
1233                                  const gchar *buf,
1234                                  gsize        count,
1235                                  gsize       *bytes_written,
1236                                  GError     **err)
1237 {
1238   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1239   gint result;
1240
1241   if (win32_channel->thread_id)
1242     {
1243       return buffer_write (win32_channel, buf, count, bytes_written, err);
1244     }
1245   
1246   result = write (win32_channel->fd, buf, count);
1247   if (win32_channel->debug)
1248     g_print ("g_io_win32_fd_write: fd=%d count=%" G_GSIZE_FORMAT " => %d\n",
1249              win32_channel->fd, count, result);
1250
1251   if (result < 0)
1252     {
1253       *bytes_written = 0;
1254
1255       switch (errno)
1256         {
1257 #ifdef EAGAIN
1258         case EAGAIN:
1259           return G_IO_STATUS_AGAIN;
1260 #endif
1261         default:
1262           g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1263                                g_io_channel_error_from_errno (errno),
1264                                g_strerror (errno));
1265           return G_IO_STATUS_ERROR;
1266         }
1267     }
1268
1269   *bytes_written = result;
1270
1271   return G_IO_STATUS_NORMAL;
1272 }
1273
1274 static GIOStatus
1275 g_io_win32_fd_seek (GIOChannel *channel,
1276                     gint64      offset,
1277                     GSeekType   type,
1278                     GError    **err)
1279 {
1280   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1281   int whence;
1282   off_t tmp_offset;
1283   off_t result;
1284   
1285   switch (type)
1286     {
1287     case G_SEEK_SET:
1288       whence = SEEK_SET;
1289       break;
1290     case G_SEEK_CUR:
1291       whence = SEEK_CUR;
1292       break;
1293     case G_SEEK_END:
1294       whence = SEEK_END;
1295       break;
1296     default:
1297       whence = -1; /* Keep the compiler quiet */
1298       g_assert_not_reached ();
1299       abort ();
1300     }
1301
1302   tmp_offset = offset;
1303   if (tmp_offset != offset)
1304     {
1305       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1306                            g_io_channel_error_from_errno (EINVAL),
1307                            g_strerror (EINVAL));
1308       return G_IO_STATUS_ERROR;
1309     }
1310   
1311   result = lseek (win32_channel->fd, tmp_offset, whence);
1312   
1313   if (result < 0)
1314     {
1315       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1316                            g_io_channel_error_from_errno (errno),
1317                            g_strerror (errno));
1318       return G_IO_STATUS_ERROR;
1319     }
1320
1321   return G_IO_STATUS_NORMAL;
1322 }
1323
1324 static GIOStatus
1325 g_io_win32_fd_close (GIOChannel *channel,
1326                      GError    **err)
1327 {
1328   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1329   
1330   if (win32_channel->debug)
1331     g_print ("g_io_win32_fd_close: thread=%#x: fd=%d\n",
1332              win32_channel->thread_id,
1333              win32_channel->fd);
1334   EnterCriticalSection (&win32_channel->mutex);
1335   if (win32_channel->running)
1336     {
1337       if (win32_channel->debug)
1338         g_print ("thread %#x: running, marking fd %d for later close\n",
1339                  win32_channel->thread_id, win32_channel->fd);
1340       win32_channel->running = FALSE;
1341       win32_channel->needs_close = TRUE;
1342       if (win32_channel->direction == 0)
1343         SetEvent (win32_channel->data_avail_event);
1344       else
1345         SetEvent (win32_channel->space_avail_event);
1346     }
1347   else
1348     {
1349       if (win32_channel->debug)
1350         g_print ("closing fd %d\n", win32_channel->fd);
1351       close (win32_channel->fd);
1352       if (win32_channel->debug)
1353         g_print ("closed fd %d, setting to -1\n",
1354                  win32_channel->fd);
1355       win32_channel->fd = -1;
1356     }
1357   LeaveCriticalSection (&win32_channel->mutex);
1358
1359   /* FIXME error detection? */
1360
1361   return G_IO_STATUS_NORMAL;
1362 }
1363
1364 static GSource *
1365 g_io_win32_fd_create_watch (GIOChannel    *channel,
1366                             GIOCondition   condition)
1367 {
1368   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1369   GSource *source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
1370   GIOWin32Watch *watch = (GIOWin32Watch *)source;
1371
1372   watch->channel = channel;
1373   g_io_channel_ref (channel);
1374   
1375   watch->condition = condition;
1376   
1377   if (win32_channel->data_avail_event == NULL)
1378     create_events (win32_channel);
1379
1380   watch->pollfd.fd = (gintptr) win32_channel->data_avail_event;
1381   watch->pollfd.events = condition;
1382   
1383   if (win32_channel->debug)
1384     g_print ("g_io_win32_fd_create_watch: channel=%p fd=%d condition={%s} event=%p\n",
1385              channel, win32_channel->fd,
1386              condition_to_string (condition), (HANDLE) watch->pollfd.fd);
1387
1388   EnterCriticalSection (&win32_channel->mutex);
1389   if (win32_channel->thread_id == 0)
1390     {
1391       if (condition & G_IO_IN)
1392         create_thread (win32_channel, condition, read_thread);
1393       else if (condition & G_IO_OUT)
1394         create_thread (win32_channel, condition, write_thread);
1395     }
1396
1397   g_source_add_poll (source, &watch->pollfd);
1398   LeaveCriticalSection (&win32_channel->mutex);
1399
1400   return source;
1401 }
1402
1403 static GIOStatus
1404 g_io_win32_console_close (GIOChannel *channel,
1405                           GError    **err)
1406 {
1407   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1408   
1409   if (close (win32_channel->fd) < 0)
1410     {
1411       g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1412                            g_io_channel_error_from_errno (errno),
1413                            g_strerror (errno));
1414       return G_IO_STATUS_ERROR;
1415     }
1416
1417   return G_IO_STATUS_NORMAL;
1418 }
1419
1420 static GSource *
1421 g_io_win32_console_create_watch (GIOChannel    *channel,
1422                                  GIOCondition   condition)
1423 {
1424   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1425   GSource *source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
1426   GIOWin32Watch *watch = (GIOWin32Watch *)source;
1427
1428   watch->channel = channel;
1429   g_io_channel_ref (channel);
1430   
1431   watch->condition = condition;
1432   
1433   watch->pollfd.fd = _get_osfhandle (win32_channel->fd);
1434   watch->pollfd.events = condition;
1435   
1436   g_source_add_poll (source, &watch->pollfd);
1437
1438   return source;
1439 }
1440
1441 static GIOStatus
1442 g_io_win32_sock_read (GIOChannel *channel,
1443                       gchar      *buf,
1444                       gsize       count,
1445                       gsize      *bytes_read,
1446                       GError    **err)
1447 {
1448   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1449   gint result;
1450   GIOChannelError error;
1451   int winsock_error;
1452
1453   if (win32_channel->debug)
1454     g_print ("g_io_win32_sock_read: channel=%p sock=%d count=%" G_GSIZE_FORMAT,
1455              channel, win32_channel->fd, count);
1456
1457   result = recv (win32_channel->fd, buf, count, 0);
1458   if (result == SOCKET_ERROR)
1459     winsock_error = WSAGetLastError ();
1460
1461   if (win32_channel->debug)
1462     g_print (" recv=%d", result);
1463   
1464   if (result == SOCKET_ERROR)
1465     {
1466       gchar *emsg = g_win32_error_message (winsock_error);
1467
1468       if (win32_channel->debug)
1469         g_print (" %s\n", emsg);
1470
1471       *bytes_read = 0;
1472
1473       switch (winsock_error)
1474         {
1475         case WSAEINVAL:
1476           error = G_IO_CHANNEL_ERROR_INVAL;
1477           break;
1478         case WSAEWOULDBLOCK:
1479           g_free (emsg);
1480           return G_IO_STATUS_AGAIN;
1481         default:
1482           error = G_IO_CHANNEL_ERROR_FAILED;
1483           break;
1484         }
1485       g_set_error_literal (err, G_IO_CHANNEL_ERROR, error, emsg);
1486       g_free (emsg);
1487
1488       return G_IO_STATUS_ERROR;
1489     }
1490   else
1491     {
1492       if (win32_channel->debug)
1493         g_print ("\n");
1494       *bytes_read = result;
1495       if (result == 0)
1496         return G_IO_STATUS_EOF;
1497       else
1498         return G_IO_STATUS_NORMAL;
1499     }
1500 }
1501
1502 static GIOStatus
1503 g_io_win32_sock_write (GIOChannel  *channel,
1504                        const gchar *buf,
1505                        gsize        count,
1506                        gsize       *bytes_written,
1507                        GError     **err)
1508 {
1509   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1510   gint result;
1511   GIOChannelError error;
1512   int winsock_error;
1513   
1514   if (win32_channel->debug)
1515     g_print ("g_io_win32_sock_write: channel=%p sock=%d count=%" G_GSIZE_FORMAT,
1516              channel, win32_channel->fd, count);
1517
1518   result = send (win32_channel->fd, buf, count, 0);
1519   if (result == SOCKET_ERROR)
1520     winsock_error = WSAGetLastError ();
1521
1522   if (win32_channel->debug)
1523     g_print (" send=%d", result);
1524   
1525   if (result == SOCKET_ERROR)
1526     {
1527       gchar *emsg = g_win32_error_message (winsock_error);
1528
1529       if (win32_channel->debug)
1530         g_print (" %s\n", emsg);
1531
1532       *bytes_written = 0;
1533
1534       switch (winsock_error)
1535         {
1536         case WSAEINVAL:
1537           error = G_IO_CHANNEL_ERROR_INVAL;
1538           break;
1539         case WSAEWOULDBLOCK:
1540           win32_channel->write_would_have_blocked = TRUE;
1541           win32_channel->last_events = 0;
1542           g_free (emsg);
1543           return G_IO_STATUS_AGAIN;
1544         default:
1545           error = G_IO_CHANNEL_ERROR_FAILED;
1546           break;
1547         }
1548       g_set_error_literal (err, G_IO_CHANNEL_ERROR, error, emsg);
1549       g_free (emsg);
1550
1551       return G_IO_STATUS_ERROR;
1552     }
1553   else
1554     {
1555       if (win32_channel->debug)
1556         g_print ("\n");
1557       *bytes_written = result;
1558       win32_channel->write_would_have_blocked = FALSE;
1559
1560       return G_IO_STATUS_NORMAL;
1561     }
1562 }
1563
1564 static GIOStatus
1565 g_io_win32_sock_close (GIOChannel *channel,
1566                        GError    **err)
1567 {
1568   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1569
1570   if (win32_channel->fd != -1)
1571     {
1572       if (win32_channel->debug)
1573         g_print ("g_io_win32_sock_close: channel=%p sock=%d\n",
1574                  channel, win32_channel->fd);
1575       
1576       closesocket (win32_channel->fd);
1577       win32_channel->fd = -1;
1578     }
1579
1580   /* FIXME error detection? */
1581
1582   return G_IO_STATUS_NORMAL;
1583 }
1584
1585 static GSource *
1586 g_io_win32_sock_create_watch (GIOChannel    *channel,
1587                               GIOCondition   condition)
1588 {
1589   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1590   GSource *source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
1591   GIOWin32Watch *watch = (GIOWin32Watch *)source;
1592   
1593   watch->channel = channel;
1594   g_io_channel_ref (channel);
1595   
1596   watch->condition = condition;
1597
1598   if (win32_channel->event == 0)
1599     win32_channel->event = WSACreateEvent ();
1600
1601   watch->pollfd.fd = (gintptr) win32_channel->event;
1602   watch->pollfd.events = condition;
1603   
1604   if (win32_channel->debug)
1605     g_print ("g_io_win32_sock_create_watch: channel=%p sock=%d event=%p condition={%s}\n",
1606              channel, win32_channel->fd, (HANDLE) watch->pollfd.fd,
1607              condition_to_string (watch->condition));
1608
1609   g_source_add_poll (source, &watch->pollfd);
1610
1611   return source;
1612 }
1613
1614 GIOChannel *
1615 g_io_channel_new_file (const gchar  *filename,
1616                        const gchar  *mode,
1617                        GError      **error)
1618 {
1619   int fid, flags, pmode;
1620   GIOChannel *channel;
1621
1622   enum { /* Cheesy hack */
1623     MODE_R = 1 << 0,
1624     MODE_W = 1 << 1,
1625     MODE_A = 1 << 2,
1626     MODE_PLUS = 1 << 3,
1627   } mode_num;
1628
1629   g_return_val_if_fail (filename != NULL, NULL);
1630   g_return_val_if_fail (mode != NULL, NULL);
1631   g_return_val_if_fail ((error == NULL) || (*error == NULL), NULL);
1632
1633   switch (mode[0])
1634     {
1635       case 'r':
1636         mode_num = MODE_R;
1637         break;
1638       case 'w':
1639         mode_num = MODE_W;
1640         break;
1641       case 'a':
1642         mode_num = MODE_A;
1643         break;
1644       default:
1645         g_warning ("Invalid GIOFileMode %s.", mode);
1646         return NULL;
1647     }
1648
1649   switch (mode[1])
1650     {
1651       case '\0':
1652         break;
1653       case '+':
1654         if (mode[2] == '\0')
1655           {
1656             mode_num |= MODE_PLUS;
1657             break;
1658           }
1659         /* Fall through */
1660       default:
1661         g_warning ("Invalid GIOFileMode %s.", mode);
1662         return NULL;
1663     }
1664
1665   switch (mode_num)
1666     {
1667       case MODE_R:
1668         flags = O_RDONLY;
1669         pmode = _S_IREAD;
1670         break;
1671       case MODE_W:
1672         flags = O_WRONLY | O_TRUNC | O_CREAT;
1673         pmode = _S_IWRITE;
1674         break;
1675       case MODE_A:
1676         flags = O_WRONLY | O_APPEND | O_CREAT;
1677         pmode = _S_IWRITE;
1678         break;
1679       case MODE_R | MODE_PLUS:
1680         flags = O_RDWR;
1681         pmode = _S_IREAD | _S_IWRITE;
1682         break;
1683       case MODE_W | MODE_PLUS:
1684         flags = O_RDWR | O_TRUNC | O_CREAT;
1685         pmode = _S_IREAD | _S_IWRITE;
1686         break;
1687       case MODE_A | MODE_PLUS:
1688         flags = O_RDWR | O_APPEND | O_CREAT;
1689         pmode = _S_IREAD | _S_IWRITE;
1690         break;
1691       default:
1692         g_assert_not_reached ();
1693         abort ();
1694     }
1695
1696   /* always open 'untranslated' */
1697   fid = g_open (filename, flags | _O_BINARY, pmode);
1698
1699   if (g_io_win32_get_debug_flag ())
1700     {
1701       g_print ("g_io_channel_win32_new_file: open(\"%s\",", filename);
1702       g_win32_print_access_mode (flags|_O_BINARY);
1703       g_print (",%#o)=%d\n", pmode, fid);
1704     }
1705
1706   if (fid < 0)
1707     {
1708       g_set_error_literal (error, G_FILE_ERROR,
1709                            g_file_error_from_errno (errno),
1710                            g_strerror (errno));
1711       return (GIOChannel *)NULL;
1712     }
1713
1714   channel = g_io_channel_win32_new_fd (fid);
1715
1716   /* XXX: move this to g_io_channel_win32_new_fd () */
1717   channel->close_on_unref = TRUE;
1718   channel->is_seekable = TRUE;
1719
1720   /* g_io_channel_win32_new_fd sets is_readable and is_writeable to
1721    * correspond to actual readability/writeability. Set to FALSE those
1722    * that mode doesn't allow
1723    */
1724   switch (mode_num)
1725     {
1726       case MODE_R:
1727         channel->is_writeable = FALSE;
1728         break;
1729       case MODE_W:
1730       case MODE_A:
1731         channel->is_readable = FALSE;
1732         break;
1733       case MODE_R | MODE_PLUS:
1734       case MODE_W | MODE_PLUS:
1735       case MODE_A | MODE_PLUS:
1736         break;
1737       default:
1738         g_assert_not_reached ();
1739         abort ();
1740     }
1741
1742   return channel;
1743 }
1744
1745 #if !defined (_WIN64)
1746
1747 #undef g_io_channel_new_file
1748
1749 /* Binary compatibility version. Not for newly compiled code. */
1750
1751 GIOChannel *
1752 g_io_channel_new_file (const gchar  *filename,
1753                        const gchar  *mode,
1754                        GError      **error)
1755 {
1756   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1757   GIOChannel *retval;
1758
1759   if (utf8_filename == NULL)
1760     return NULL;
1761
1762   retval = g_io_channel_new_file_utf8 (utf8_filename, mode, error);
1763
1764   g_free (utf8_filename);
1765
1766   return retval;
1767 }
1768
1769 #endif
1770
1771 static GIOStatus
1772 g_io_win32_unimpl_set_flags (GIOChannel *channel,
1773                              GIOFlags    flags,
1774                              GError    **err)
1775 {
1776   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1777
1778   if (win32_channel->debug)
1779     {
1780       g_print ("g_io_win32_unimpl_set_flags: ");
1781       g_win32_print_gioflags (flags);
1782       g_print ("\n");
1783     }
1784
1785   g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1786                        G_IO_CHANNEL_ERROR_FAILED,
1787                        "Not implemented on Win32");
1788
1789   return G_IO_STATUS_ERROR;
1790 }
1791
1792 static GIOFlags
1793 g_io_win32_fd_get_flags_internal (GIOChannel  *channel,
1794                                   struct stat *st)
1795 {
1796   GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
1797   gchar c;
1798   DWORD count;
1799
1800   if (st->st_mode & _S_IFIFO)
1801     {
1802       channel->is_readable =
1803         (PeekNamedPipe ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL, NULL) != 0) || GetLastError () == ERROR_BROKEN_PIPE;
1804       channel->is_writeable =
1805         (WriteFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1806       channel->is_seekable  = FALSE;
1807     }
1808   else
1809     {
1810       channel->is_readable =
1811         (ReadFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1812       channel->is_writeable =
1813         (WriteFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1814       channel->is_seekable = TRUE;
1815     }
1816
1817   /* XXX: G_IO_FLAG_APPEND */
1818   /* XXX: G_IO_FLAG_NONBLOCK */
1819
1820   return 0;
1821 }
1822
1823 static GIOFlags
1824 g_io_win32_fd_get_flags (GIOChannel *channel)
1825 {
1826   struct stat st;
1827   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1828
1829   g_return_val_if_fail (win32_channel != NULL, 0);
1830   g_return_val_if_fail (win32_channel->type == G_IO_WIN32_FILE_DESC, 0);
1831
1832   if (0 == fstat (win32_channel->fd, &st))
1833     return g_io_win32_fd_get_flags_internal (channel, &st);
1834   else
1835     return 0;
1836 }
1837
1838 static GIOFlags
1839 g_io_win32_console_get_flags_internal (GIOChannel  *channel)
1840 {
1841   GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
1842   HANDLE handle = (HANDLE) _get_osfhandle (win32_channel->fd);
1843   gchar c;
1844   DWORD count;
1845   INPUT_RECORD record;
1846
1847   channel->is_readable = PeekConsoleInput (handle, &record, 1, &count);
1848   channel->is_writeable = WriteFile (handle, &c, 0, &count, NULL);
1849   channel->is_seekable = FALSE;
1850
1851   return 0;
1852 }
1853
1854 static GIOFlags
1855 g_io_win32_console_get_flags (GIOChannel *channel)
1856 {
1857   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1858
1859   g_return_val_if_fail (win32_channel != NULL, 0);
1860   g_return_val_if_fail (win32_channel->type == G_IO_WIN32_CONSOLE, 0);
1861
1862   return g_io_win32_console_get_flags_internal (channel);
1863 }
1864
1865 static GIOFlags
1866 g_io_win32_msg_get_flags (GIOChannel *channel)
1867 {
1868   return 0;
1869 }
1870
1871 static GIOStatus
1872 g_io_win32_sock_set_flags (GIOChannel *channel,
1873                            GIOFlags    flags,
1874                            GError    **err)
1875 {
1876   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1877   u_long arg;
1878
1879   if (win32_channel->debug)
1880     {
1881       g_print ("g_io_win32_sock_set_flags: ");
1882       g_win32_print_gioflags (flags);
1883       g_print ("\n");
1884     }
1885
1886   if (flags & G_IO_FLAG_NONBLOCK)
1887     {
1888       arg = 1;
1889       if (ioctlsocket (win32_channel->fd, FIONBIO, &arg) == SOCKET_ERROR)
1890         {
1891           gchar *emsg = g_win32_error_message (WSAGetLastError ());
1892
1893           g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1894                                G_IO_CHANNEL_ERROR_FAILED,
1895                                emsg);
1896           g_free (emsg);
1897
1898           return G_IO_STATUS_ERROR;
1899         }
1900     }
1901   else
1902     {
1903       arg = 0;
1904       if (ioctlsocket (win32_channel->fd, FIONBIO, &arg) == SOCKET_ERROR)
1905         {
1906           gchar *emsg = g_win32_error_message (WSAGetLastError ());
1907
1908           g_set_error_literal (err, G_IO_CHANNEL_ERROR,
1909                                G_IO_CHANNEL_ERROR_FAILED,
1910                                emsg);
1911           g_free (emsg);
1912
1913           return G_IO_STATUS_ERROR;
1914         }
1915     }
1916
1917   return G_IO_STATUS_NORMAL;
1918 }
1919
1920 static GIOFlags
1921 g_io_win32_sock_get_flags (GIOChannel *channel)
1922 {
1923   /* Could we do something here? */
1924   return 0;
1925 }
1926
1927 static GIOFuncs win32_channel_msg_funcs = {
1928   g_io_win32_msg_read,
1929   g_io_win32_msg_write,
1930   NULL,
1931   g_io_win32_msg_close,
1932   g_io_win32_msg_create_watch,
1933   g_io_win32_free,
1934   g_io_win32_unimpl_set_flags,
1935   g_io_win32_msg_get_flags,
1936 };
1937
1938 static GIOFuncs win32_channel_fd_funcs = {
1939   g_io_win32_fd_and_console_read,
1940   g_io_win32_fd_and_console_write,
1941   g_io_win32_fd_seek,
1942   g_io_win32_fd_close,
1943   g_io_win32_fd_create_watch,
1944   g_io_win32_free,
1945   g_io_win32_unimpl_set_flags,
1946   g_io_win32_fd_get_flags,
1947 };
1948
1949 static GIOFuncs win32_channel_console_funcs = {
1950   g_io_win32_fd_and_console_read,
1951   g_io_win32_fd_and_console_write,
1952   NULL,
1953   g_io_win32_console_close,
1954   g_io_win32_console_create_watch,
1955   g_io_win32_free,
1956   g_io_win32_unimpl_set_flags,
1957   g_io_win32_console_get_flags,
1958 };
1959
1960 static GIOFuncs win32_channel_sock_funcs = {
1961   g_io_win32_sock_read,
1962   g_io_win32_sock_write,
1963   NULL,
1964   g_io_win32_sock_close,
1965   g_io_win32_sock_create_watch,
1966   g_io_win32_free,
1967   g_io_win32_sock_set_flags,
1968   g_io_win32_sock_get_flags,
1969 };
1970
1971 GIOChannel *
1972 #if GLIB_SIZEOF_VOID_P == 8
1973 g_io_channel_win32_new_messages (gsize hwnd)
1974 #else
1975 g_io_channel_win32_new_messages (guint hwnd)
1976 #endif
1977 {
1978   GIOWin32Channel *win32_channel = g_new (GIOWin32Channel, 1);
1979   GIOChannel *channel = (GIOChannel *)win32_channel;
1980
1981   g_io_channel_init (channel);
1982   g_io_channel_win32_init (win32_channel);
1983   if (win32_channel->debug)
1984     g_print ("g_io_channel_win32_new_messages: channel=%p hwnd=%p\n",
1985              channel, (HWND) hwnd);
1986   channel->funcs = &win32_channel_msg_funcs;
1987   win32_channel->type = G_IO_WIN32_WINDOWS_MESSAGES;
1988   win32_channel->hwnd = (HWND) hwnd;
1989
1990   /* XXX: check this. */
1991   channel->is_readable = IsWindow (win32_channel->hwnd);
1992   channel->is_writeable = IsWindow (win32_channel->hwnd);
1993
1994   channel->is_seekable = FALSE;
1995
1996   return channel;
1997 }
1998
1999 static GIOChannel *
2000 g_io_channel_win32_new_fd_internal (gint         fd,
2001                                     struct stat *st)
2002 {
2003   GIOWin32Channel *win32_channel;
2004   GIOChannel *channel;
2005
2006   win32_channel = g_new (GIOWin32Channel, 1);
2007   channel = (GIOChannel *)win32_channel;
2008
2009   g_io_channel_init (channel);
2010   g_io_channel_win32_init (win32_channel);
2011
2012   win32_channel->fd = fd;
2013
2014   if (win32_channel->debug)
2015     g_print ("g_io_channel_win32_new_fd: channel=%p fd=%u\n",
2016              channel, fd);
2017
2018   if (st->st_mode & _S_IFCHR) /* console */
2019     {
2020       channel->funcs = &win32_channel_console_funcs;
2021       win32_channel->type = G_IO_WIN32_CONSOLE;
2022       g_io_win32_console_get_flags_internal (channel);
2023     }
2024   else
2025     {
2026       channel->funcs = &win32_channel_fd_funcs;
2027       win32_channel->type = G_IO_WIN32_FILE_DESC;
2028       g_io_win32_fd_get_flags_internal (channel, st);
2029     }
2030   
2031   return channel;
2032 }
2033
2034 GIOChannel *
2035 g_io_channel_win32_new_fd (gint fd)
2036 {
2037   struct stat st;
2038
2039   if (fstat (fd, &st) == -1)
2040     {
2041       g_warning ("g_io_channel_win32_new_fd: %d isn't an open file descriptor in the C library GLib uses.", fd);
2042       return NULL;
2043     }
2044
2045   return g_io_channel_win32_new_fd_internal (fd, &st);
2046 }
2047
2048 gint
2049 g_io_channel_win32_get_fd (GIOChannel *channel)
2050 {
2051   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
2052
2053   return win32_channel->fd;
2054 }
2055
2056 GIOChannel *
2057 g_io_channel_win32_new_socket (int socket)
2058 {
2059   GIOWin32Channel *win32_channel = g_new (GIOWin32Channel, 1);
2060   GIOChannel *channel = (GIOChannel *)win32_channel;
2061
2062   g_io_channel_init (channel);
2063   g_io_channel_win32_init (win32_channel);
2064   if (win32_channel->debug)
2065     g_print ("g_io_channel_win32_new_socket: channel=%p sock=%d\n",
2066              channel, socket);
2067   channel->funcs = &win32_channel_sock_funcs;
2068   win32_channel->type = G_IO_WIN32_SOCKET;
2069   win32_channel->fd = socket;
2070
2071   channel->is_readable = TRUE;
2072   channel->is_writeable = TRUE;
2073   channel->is_seekable = FALSE;
2074
2075   return channel;
2076 }
2077
2078 GIOChannel *
2079 g_io_channel_unix_new (gint fd)
2080 {
2081   gboolean is_fd, is_socket;
2082   struct stat st;
2083   int optval, optlen;
2084
2085   is_fd = (fstat (fd, &st) == 0);
2086
2087   optlen = sizeof (optval);
2088   is_socket = (getsockopt (fd, SOL_SOCKET, SO_TYPE, (char *) &optval, &optlen) != SOCKET_ERROR);
2089
2090   if (is_fd && is_socket)
2091     g_warning ("g_io_channel_unix_new: %d is both a file descriptor and a socket. File descriptor interpretation assumed. To avoid ambiguity, call either g_io_channel_win32_new_fd() or g_io_channel_win32_new_socket() instead.", fd);
2092
2093   if (is_fd)
2094     return g_io_channel_win32_new_fd_internal (fd, &st);
2095
2096   if (is_socket)
2097     return g_io_channel_win32_new_socket(fd);
2098
2099   g_warning ("g_io_channel_unix_new: %d is neither a file descriptor or a socket.", fd);
2100
2101   return NULL;
2102 }
2103
2104 gint
2105 g_io_channel_unix_get_fd (GIOChannel *channel)
2106 {
2107   return g_io_channel_win32_get_fd (channel);
2108 }
2109
2110 void
2111 g_io_channel_win32_set_debug (GIOChannel *channel,
2112                               gboolean    flag)
2113 {
2114   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
2115
2116   win32_channel->debug = flag;
2117 }
2118
2119 gint
2120 g_io_channel_win32_poll (GPollFD *fds,
2121                          gint     n_fds,
2122                          gint     timeout)
2123 {
2124   g_return_val_if_fail (n_fds >= 0, 0);
2125
2126   return g_poll (fds, n_fds, timeout);
2127 }
2128
2129 void
2130 g_io_channel_win32_make_pollfd (GIOChannel   *channel,
2131                                 GIOCondition  condition,
2132                                 GPollFD      *fd)
2133 {
2134   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
2135
2136   switch (win32_channel->type)
2137     {
2138     case G_IO_WIN32_FILE_DESC:
2139       if (win32_channel->data_avail_event == NULL)
2140         create_events (win32_channel);
2141
2142       fd->fd = (gintptr) win32_channel->data_avail_event;
2143
2144       if (win32_channel->thread_id == 0)
2145         {
2146           /* Is it meaningful for a file descriptor to be polled for
2147            * both IN and OUT? For what kind of file descriptor would
2148            * that be? Doesn't seem to make sense, in practise the file
2149            * descriptors handled here are always read or write ends of
2150            * pipes surely, and thus unidirectional.
2151            */
2152           if (condition & G_IO_IN)
2153             create_thread (win32_channel, condition, read_thread);
2154           else if (condition & G_IO_OUT)
2155             create_thread (win32_channel, condition, write_thread);
2156         }
2157       break;
2158
2159     case G_IO_WIN32_CONSOLE:
2160       fd->fd = _get_osfhandle (win32_channel->fd);
2161       break;
2162
2163     case G_IO_WIN32_SOCKET:
2164       fd->fd = (gintptr) WSACreateEvent ();
2165       break;
2166       
2167     case G_IO_WIN32_WINDOWS_MESSAGES:
2168       fd->fd = G_WIN32_MSG_HANDLE;
2169       break;
2170
2171     default:
2172       g_assert_not_reached ();
2173       abort ();
2174     }
2175   
2176   fd->events = condition;
2177 }
2178
2179 #ifndef _WIN64
2180
2181 /* Binary compatibility */
2182 GIOChannel *
2183 g_io_channel_win32_new_stream_socket (int socket)
2184 {
2185   return g_io_channel_win32_new_socket (socket);
2186 }
2187
2188 #endif
2189
2190 #define __G_IO_WIN32_C__
2191 #include "galiasdef.c"