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