f1ec3678a955f848036a45afdd1261cf5da48c1d
[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 /* Define this to get (very) verbose logging of all channels */
33 /* #define G_IO_WIN32_DEBUG */
34
35 #include "config.h"
36
37 #include "glib.h"
38
39 #include <stdlib.h>
40 #include <windows.h>
41 #include <winsock.h>          /* Not everybody has winsock2 */
42 #include <fcntl.h>
43 #include <io.h>
44 #include <process.h>
45 #include <errno.h>
46 #include <sys/stat.h>
47
48 #include "glibintl.h"
49
50 typedef struct _GIOWin32Channel GIOWin32Channel;
51 typedef struct _GIOWin32Watch GIOWin32Watch;
52
53 #define BUFFER_SIZE 4096
54
55 typedef enum {
56   G_IO_WIN32_WINDOWS_MESSAGES,  /* Windows messages */
57   G_IO_WIN32_FILE_DESC,         /* Unix-like file descriptors from
58                                  * _open() or _pipe(). Read with read().
59                                  * Have to create separate thread to read.
60                                  */
61   G_IO_WIN32_SOCKET             /* Sockets. A separate thread is blocked
62                                  * in select() most of the time.
63                                  */
64 } GIOWin32ChannelType;
65
66 struct _GIOWin32Channel {
67   GIOChannel channel;
68   gint fd;                      /* Either a Unix-like file handle as provided
69                                  * by the Microsoft C runtime, or a SOCKET
70                                  * as provided by WinSock.
71                                  */
72   GIOWin32ChannelType type;
73   
74   gboolean debug;
75
76   CRITICAL_SECTION mutex;
77
78   /* This is used by G_IO_WIN32_WINDOWS_MESSAGES channels */
79   HWND hwnd;                    /* handle of window, or NULL */
80   
81   /* Following fields are used by both fd and socket channels. */
82   gboolean running;             /* Is reader thread running. FALSE if
83                                  * EOF has been reached.
84                                  */
85   gboolean needs_close;         /* If the channel has been closed while
86                                  * the reader thread was still running.
87                                  */
88   guint thread_id;              /* If non-NULL has a reader thread, or has
89                                  * had.*/
90   HANDLE data_avail_event;
91
92   gushort revents;
93
94   /* Following fields used by fd channels for input */
95   
96   /* Data is kept in a circular buffer. To be able to distinguish between
97    * empty and full buffer, we cannot fill it completely, but have to
98    * leave a one character gap.
99    *
100    * Data available is between indexes rdp and wrp-1 (modulo BUFFER_SIZE).
101    *
102    * Empty:    wrp == rdp
103    * Full:     (wrp + 1) % BUFFER_SIZE == rdp
104    * Partial:  otherwise
105    */
106   guchar *buffer;               /* (Circular) buffer */
107   gint wrp, rdp;                /* Buffer indices for writing and reading */
108   HANDLE space_avail_event;
109
110   /* Following fields used by socket channels */
111   GSList *watches;
112   HANDLE data_avail_noticed_event;
113   gint reset_send; /* socket used to send data so select_thread() can reset/re-loop */
114   gint reset_recv; /* socket used to recv data so select_thread() can reset/re-loop */
115 };
116
117 #define LOCK(mutex) EnterCriticalSection (&mutex)
118 #define UNLOCK(mutex) LeaveCriticalSection (&mutex)
119
120 struct _GIOWin32Watch {
121   GSource       source;
122   GPollFD       pollfd;
123   GIOChannel   *channel;
124   GIOCondition  condition;
125 };
126
127 static void
128 g_win32_print_access_mode (int flags)
129 {
130   g_print ("%s%s%s%s%s%s%s%s%s%s",
131            ((flags & 0x3) == _O_RDWR ? "O_RDWR" :
132             ((flags & 0x3) == _O_RDONLY ? "O_RDONLY" :
133              ((flags & 0x3) == _O_WRONLY ? "O_WRONLY" : "0"))),
134            (flags & _O_APPEND ? "|O_APPEND" : ""),
135            (flags & _O_RANDOM ? "|O_RANDOM" : ""),
136            (flags & _O_SEQUENTIAL ? "|O_SEQUENTIAL" : ""),
137            (flags & _O_TEMPORARY ? "|O_TEMPORARY" : ""),
138            (flags & _O_CREAT ? "|O_CREAT" : ""),
139            (flags & _O_TRUNC ? "|O_TRUNC" : ""),
140            (flags & _O_EXCL ? "|O_EXCL" : ""),
141            (flags & _O_TEXT ? "|O_TEXT" : ""),
142            (flags & _O_BINARY ? "|O_BINARY" : ""));
143 }
144
145 static void
146 g_win32_print_gioflags (GIOFlags flags)
147 {
148   char *bar = "";
149
150   if (flags & G_IO_FLAG_APPEND)
151     bar = "|", g_print ("APPEND");
152   if (flags & G_IO_FLAG_NONBLOCK)
153     g_print ("%sNONBLOCK", bar), bar = "|";
154   if (flags & G_IO_FLAG_IS_READABLE)
155     g_print ("%sREADABLE", bar), bar = "|";
156   if (flags & G_IO_FLAG_IS_WRITEABLE)
157     g_print ("%sWRITEABLE", bar), bar = "|";
158   if (flags & G_IO_FLAG_IS_SEEKABLE)
159     g_print ("%sSEEKABLE", bar), bar = "|";
160 }
161
162 static gboolean
163 g_io_win32_get_debug_flag (void)
164 {
165 #ifdef G_IO_WIN32_DEBUG
166   return TRUE;
167 #else
168   if (getenv ("G_IO_WIN32_DEBUG") != NULL)
169     return TRUE;
170   else
171     return FALSE;
172 #endif
173 }  
174
175 static void
176 g_io_channel_win32_init (GIOWin32Channel *channel)
177 {
178   channel->debug = g_io_win32_get_debug_flag ();
179   channel->buffer = NULL;
180   channel->running = FALSE;
181   channel->needs_close = FALSE;
182   channel->thread_id = 0;
183   channel->data_avail_event = NULL;
184   channel->revents = 0;
185   channel->space_avail_event = NULL;
186   channel->data_avail_noticed_event = NULL;
187   channel->watches = NULL;
188   InitializeCriticalSection (&channel->mutex);
189 }
190
191 static void
192 create_events (GIOWin32Channel *channel)
193 {
194   SECURITY_ATTRIBUTES sec_attrs;
195   
196   sec_attrs.nLength = sizeof (SECURITY_ATTRIBUTES);
197   sec_attrs.lpSecurityDescriptor = NULL;
198   sec_attrs.bInheritHandle = FALSE;
199
200   /* The data available event is manual reset, the space available event
201    * is automatic reset.
202    */
203   if (!(channel->data_avail_event = CreateEvent (&sec_attrs, TRUE, FALSE, NULL))
204       || !(channel->space_avail_event = CreateEvent (&sec_attrs, FALSE, FALSE, NULL))
205       || !(channel->data_avail_noticed_event = CreateEvent (&sec_attrs, FALSE, FALSE, NULL)))
206     {
207       gchar *emsg = g_win32_error_message (GetLastError ());
208       g_error ("Error creating event: %s", emsg);
209       g_free (emsg);
210     }
211 }
212
213 static unsigned __stdcall
214 read_thread (void *parameter)
215 {
216   GIOWin32Channel *channel = parameter;
217   guchar *buffer;
218   guint nbytes;
219
220   g_io_channel_ref ((GIOChannel *)channel);
221
222   if (channel->debug)
223     g_print ("read_thread %#x: start fd:%d, data_avail:%#x space_avail:%#x\n",
224              channel->thread_id,
225              channel->fd,
226              (guint) channel->data_avail_event,
227              (guint) channel->space_avail_event);
228   
229   channel->buffer = g_malloc (BUFFER_SIZE);
230   channel->rdp = channel->wrp = 0;
231   channel->running = TRUE;
232
233   SetEvent (channel->space_avail_event);
234   
235   LOCK (channel->mutex);
236   while (channel->running)
237     {
238       if (channel->debug)
239         g_print ("read_thread %#x: rdp=%d, wrp=%d\n",
240                  channel->thread_id, channel->rdp, channel->wrp);
241       if ((channel->wrp + 1) % BUFFER_SIZE == channel->rdp)
242         {
243           /* Buffer is full */
244           if (channel->debug)
245             g_print ("read_thread %#x: resetting space_avail\n",
246                      channel->thread_id);
247           ResetEvent (channel->space_avail_event);
248           if (channel->debug)
249             g_print ("read_thread %#x: waiting for space\n",
250                      channel->thread_id);
251           UNLOCK (channel->mutex);
252           WaitForSingleObject (channel->space_avail_event, INFINITE);
253           LOCK (channel->mutex);
254           if (channel->debug)
255             g_print ("read_thread %#x: rdp=%d, wrp=%d\n",
256                      channel->thread_id, channel->rdp, channel->wrp);
257         }
258       
259       buffer = channel->buffer + channel->wrp;
260       
261       /* Always leave at least one byte unused gap to be able to
262        * distinguish between the full and empty condition...
263        */
264       nbytes = MIN ((channel->rdp + BUFFER_SIZE - channel->wrp - 1) % BUFFER_SIZE,
265                     BUFFER_SIZE - channel->wrp);
266
267       if (channel->debug)
268         g_print ("read_thread %#x: calling read() for %d bytes\n",
269                  channel->thread_id, nbytes);
270
271       UNLOCK (channel->mutex);
272
273       nbytes = read (channel->fd, buffer, nbytes);
274       
275       LOCK (channel->mutex);
276
277       channel->revents = G_IO_IN;
278       if (nbytes == 0)
279         channel->revents |= G_IO_HUP;
280       else if (nbytes < 0)
281         channel->revents |= G_IO_ERR;
282
283       if (channel->debug)
284         g_print ("read_thread %#x: read() returned %d, rdp=%d, wrp=%d\n",
285                  channel->thread_id, nbytes, channel->rdp, channel->wrp);
286
287       if (nbytes <= 0)
288         break;
289
290       channel->wrp = (channel->wrp + nbytes) % BUFFER_SIZE;
291       if (channel->debug)
292         g_print ("read_thread %#x: rdp=%d, wrp=%d, setting data_avail\n",
293                  channel->thread_id, channel->rdp, channel->wrp);
294       SetEvent (channel->data_avail_event);
295     }
296   
297   channel->running = FALSE;
298   if (channel->needs_close)
299     {
300       if (channel->debug)
301         g_print ("read_thread %#x: channel fd %d needs closing\n",
302                  channel->thread_id, channel->fd);
303       close (channel->fd);
304       channel->fd = -1;
305     }
306
307   if (channel->debug)
308     g_print ("read_thread %#x: EOF, rdp=%d, wrp=%d, setting data_avail\n",
309              channel->thread_id, channel->rdp, channel->wrp);
310   SetEvent (channel->data_avail_event);
311   UNLOCK (channel->mutex);
312   
313   g_io_channel_unref ((GIOChannel *)channel);
314   
315   /* No need to call _endthreadex(), the actual thread starter routine
316    * in MSVCRT (see crt/src/threadex.c:_threadstartex) calls
317    * _endthreadex() for us.
318    */
319
320   return 0;
321 }
322
323 static void
324 create_thread (GIOWin32Channel     *channel,
325                GIOCondition         condition,
326                unsigned (__stdcall *thread) (void *parameter))
327 {
328   HANDLE thread_handle;
329
330   thread_handle = (HANDLE) _beginthreadex (NULL, 0, thread, channel, 0,
331                                            &channel->thread_id);
332   if (thread_handle == 0)
333     g_warning (G_STRLOC ": Error creating reader thread: %s",
334                g_strerror (errno));
335   else if (!CloseHandle (thread_handle))
336     g_warning (G_STRLOC ": Error closing thread handle: %s\n",
337                g_win32_error_message (GetLastError ()));
338
339   WaitForSingleObject (channel->space_avail_event, INFINITE);
340 }
341
342 static void
343 init_reset_sockets (GIOWin32Channel *channel)
344 {
345   struct sockaddr_in local, local2, server;
346   int len;
347
348   channel->reset_send = (gint) socket (AF_INET, SOCK_DGRAM, 0);
349   if (channel->reset_send == INVALID_SOCKET)
350     {
351       g_warning (G_STRLOC ": Error creating reset_send socket: %s\n",
352                  g_win32_error_message (WSAGetLastError ()));
353     }
354
355   local.sin_family = AF_INET;
356   local.sin_port = 0;
357   local.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
358
359   if (bind (channel->reset_send, (struct sockaddr *)&local, sizeof (local)) == SOCKET_ERROR)
360     {
361       g_warning (G_STRLOC ": Error binding to reset_send socket: %s\n",
362                  g_win32_error_message (WSAGetLastError ()));
363   }
364
365   local2.sin_family = AF_INET;
366   local2.sin_port = 0;
367   local2.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
368
369   channel->reset_recv = (gint) socket (AF_INET, SOCK_DGRAM, 0);
370   if (channel->reset_recv == INVALID_SOCKET)
371     {
372       g_warning (G_STRLOC ": Error creating reset_recv socket: %s\n",
373                  g_win32_error_message (WSAGetLastError ()));
374   }
375
376   if (bind (channel->reset_recv, (struct sockaddr *)&local2, sizeof (local)) == SOCKET_ERROR)
377     {
378       g_warning (G_STRLOC ": Error binding to reset_recv socket: %s\n",
379                  g_win32_error_message (WSAGetLastError ()));
380     }
381   
382   len = sizeof (local2);
383   if (getsockname (channel->reset_recv, (struct sockaddr *)&local2, &len) == SOCKET_ERROR)
384     {
385       g_warning (G_STRLOC ": Error getsockname with reset_recv socket: %s\n",
386                  g_win32_error_message (WSAGetLastError ()));
387     }
388
389   memset (&server, 0, sizeof (server));
390   server.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
391   server.sin_family = AF_INET;
392   server.sin_port = local2.sin_port;
393
394   if (connect (channel->reset_send, (struct sockaddr  *)&server, sizeof (server)) == SOCKET_ERROR)
395     {
396       g_warning (G_STRLOC ": connect to reset_recv socket: %s\n",
397                  g_win32_error_message (WSAGetLastError ()));
398   }
399
400 }
401
402 static GIOStatus
403 buffer_read (GIOWin32Channel *channel,
404              guchar          *dest,
405              gsize            count,
406              gsize           *bytes_read,
407              GError         **err)
408 {
409   guint nbytes;
410   guint left = count;
411   
412   LOCK (channel->mutex);
413   if (channel->debug)
414     g_print ("reading from thread %#x %d bytes, rdp=%d, wrp=%d\n",
415              channel->thread_id, count, channel->rdp, channel->wrp);
416   
417   if (channel->wrp == channel->rdp)
418     {
419       UNLOCK (channel->mutex);
420       if (channel->debug)
421         g_print ("waiting for data from thread %#x\n", channel->thread_id);
422       WaitForSingleObject (channel->data_avail_event, INFINITE);
423       if (channel->debug)
424         g_print ("done waiting for data from thread %#x\n", channel->thread_id);
425       LOCK (channel->mutex);
426       if (channel->wrp == channel->rdp && !channel->running)
427         {
428           if (channel->debug)
429             g_print ("wrp==rdp, !running\n");
430           UNLOCK (channel->mutex);
431           *bytes_read = 0;
432           return G_IO_STATUS_EOF;
433         }
434     }
435   
436   if (channel->rdp < channel->wrp)
437     nbytes = channel->wrp - channel->rdp;
438   else
439     nbytes = BUFFER_SIZE - channel->rdp;
440   UNLOCK (channel->mutex);
441   nbytes = MIN (left, nbytes);
442   if (channel->debug)
443     g_print ("moving %d bytes from thread %#x\n",
444              nbytes, channel->thread_id);
445   memcpy (dest, channel->buffer + channel->rdp, nbytes);
446   dest += nbytes;
447   left -= nbytes;
448   LOCK (channel->mutex);
449   channel->rdp = (channel->rdp + nbytes) % BUFFER_SIZE;
450   if (channel->debug)
451     g_print ("setting space_avail for thread %#x\n", channel->thread_id);
452   SetEvent (channel->space_avail_event);
453   if (channel->debug)
454     g_print ("for thread %#x: rdp=%d, wrp=%d\n",
455              channel->thread_id, channel->rdp, channel->wrp);
456   if (channel->running && channel->wrp == channel->rdp)
457     {
458       if (channel->debug)
459         g_print ("resetting data_avail of thread %#x\n",
460                  channel->thread_id);
461       ResetEvent (channel->data_avail_event);
462     };
463   UNLOCK (channel->mutex);
464   
465   /* We have no way to indicate any errors form the actual
466    * read() or recv() call in the reader thread. Should we have?
467    */
468   *bytes_read = count - left;
469   return (*bytes_read > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
470 }
471
472 static unsigned __stdcall
473 select_thread (void *parameter)
474 {
475   GIOWin32Channel *channel = parameter;
476   fd_set read_fds, write_fds, except_fds;
477   GSList *tmp;
478   int n;
479   char buffer[8];
480
481   g_io_channel_ref ((GIOChannel *)channel);
482
483   if (channel->debug)
484     g_print ("select_thread %#x: start fd:%d data_avail:%#x data_avail_noticed:%#x\n",
485              channel->thread_id,
486              channel->fd,
487              (guint) channel->data_avail_event,
488              (guint) channel->data_avail_noticed_event);
489   
490   channel->rdp = channel->wrp = 0;
491   channel->running = TRUE;
492
493   SetEvent (channel->space_avail_event);
494   
495   while (channel->running)
496     {
497       FD_ZERO (&read_fds);
498       FD_ZERO (&write_fds);
499       FD_ZERO (&except_fds);
500       FD_SET (channel->reset_recv, &read_fds);
501
502       LOCK (channel->mutex);
503       tmp = channel->watches;
504       while (tmp)
505         {
506           GIOWin32Watch *watch = (GIOWin32Watch *)tmp->data;
507
508           if (watch->condition & (G_IO_IN | G_IO_HUP))
509             FD_SET (channel->fd, &read_fds);
510           if (watch->condition & G_IO_OUT)
511             FD_SET (channel->fd, &write_fds);
512           if (watch->condition & G_IO_ERR)
513             FD_SET (channel->fd, &except_fds);
514           
515           tmp = tmp->next;
516         }
517       UNLOCK (channel->mutex);
518
519       if (channel->debug)
520         g_print ("select_thread %#x: calling select() for%s%s%s\n",
521                  channel->thread_id,
522                  (FD_ISSET (channel->fd, &read_fds) ? " IN" : ""),
523                  (FD_ISSET (channel->fd, &write_fds) ? " OUT" : ""),
524                  (FD_ISSET (channel->fd, &except_fds) ? " ERR" : ""));
525       
526       n = select (1, &read_fds, &write_fds, &except_fds, NULL);
527       
528       LOCK (channel->mutex);
529       if (channel->needs_close)
530         {
531           UNLOCK (channel->mutex);
532           break;
533         }
534       UNLOCK (channel->mutex);
535
536       if (n == SOCKET_ERROR)
537         {
538           if (channel->debug)
539             g_print ("select_thread %#x: select returned SOCKET_ERROR\n",
540                      channel->thread_id);
541           break;
542         }
543
544     if (FD_ISSET (channel->reset_recv, &read_fds))
545     {
546       if (channel->debug)
547         g_print ("select_thread %#x: re-looping\n",
548             channel->thread_id);
549       recv (channel->reset_recv,  (char *)&buffer, (int) sizeof (buffer), 0);
550       continue;
551     }
552
553     if (channel->debug)
554       g_print ("select_thread %#x: got%s%s%s\n",
555                channel->thread_id,
556                (FD_ISSET (channel->fd, &read_fds) ? " IN" : ""),
557                (FD_ISSET (channel->fd, &write_fds) ? " OUT" : ""),
558                (FD_ISSET (channel->fd, &except_fds) ? " ERR" : ""));
559     
560     if (FD_ISSET (channel->fd, &read_fds))
561       channel->revents |= G_IO_IN;
562     if (FD_ISSET (channel->fd, &write_fds))
563       channel->revents |= G_IO_OUT;
564     if (FD_ISSET (channel->fd, &except_fds))
565       channel->revents |= G_IO_ERR;
566
567     if (channel->debug)
568       g_print ("select_thread %#x: resetting data_avail_noticed, setting data_avail\n",
569                channel->thread_id);
570
571     LOCK (channel->mutex);
572     ResetEvent (channel->data_avail_noticed_event);
573     SetEvent (channel->data_avail_event);
574     if (channel->needs_close)
575       {
576         UNLOCK (channel->mutex);
577         break;
578       }
579     UNLOCK (channel->mutex);
580
581     if (channel->debug)
582       g_print ("select_thread %#x: waiting for data_avail_noticed\n",
583         channel->thread_id);
584
585     WaitForSingleObject (channel->data_avail_noticed_event, INFINITE);
586     if (channel->debug)
587       g_print ("select_thread %#x: got data_avail_noticed\n",
588                  channel->thread_id);
589     }
590
591   LOCK (channel->mutex);
592   channel->running = FALSE;
593   if (channel->debug)
594     g_print ("select_thread %#x: got error, setting data_avail\n",
595              channel->thread_id);
596   SetEvent (channel->data_avail_event);
597   g_io_channel_unref ((GIOChannel *)channel);
598   UNLOCK (channel->mutex);
599
600   /* No need to call _endthreadex(), the actual thread starter routine
601    * in MSVCRT (see crt/src/threadex.c:_threadstartex) calls
602    * _endthreadex() for us.
603    */
604
605   return 0;
606 }
607
608 static gboolean
609 g_io_win32_prepare (GSource *source,
610                     gint    *timeout)
611 {
612   GIOWin32Watch *watch = (GIOWin32Watch *)source;
613   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
614   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
615   
616   *timeout = -1;
617   
618   if (channel->debug)
619     g_print ("g_io_win32_prepare: for thread %#x buffer_condition:%#x\n"
620              "  watch->pollfd.events:%#x watch->pollfd.revents:%#x channel->revents:%#x\n",
621              channel->thread_id, buffer_condition,
622              watch->pollfd.events, watch->pollfd.revents, channel->revents);
623
624   if (channel->type == G_IO_WIN32_FILE_DESC)
625     {
626       LOCK (channel->mutex);
627       if (channel->running && channel->wrp == channel->rdp)
628         {
629           if (channel->debug)
630             g_print ("g_io_win32_prepare: for thread %#x, setting channel->revents = 0\n",
631                      channel->thread_id);
632           channel->revents = 0;
633         }
634       UNLOCK (channel->mutex);
635     }
636   else if (channel->type == G_IO_WIN32_SOCKET)
637     {
638       LOCK (channel->mutex);
639       channel->revents = 0;
640       if (channel->debug)
641         g_print ("g_io_win32_prepare: for thread %#x, setting data_avail_noticed\n",
642                  channel->thread_id);
643       SetEvent (channel->data_avail_noticed_event);
644       if (channel->debug)
645         g_print ("g_io_win32_prepare: thread %#x, there.\n",
646                  channel->thread_id);
647       UNLOCK (channel->mutex);
648     }
649
650   return ((watch->condition & buffer_condition) == watch->condition);
651 }
652
653 static gboolean
654 g_io_win32_check (GSource *source)
655 {
656   MSG msg;
657   GIOWin32Watch *watch = (GIOWin32Watch *)source;
658   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
659   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
660
661   if (channel->debug)
662     g_print ("g_io_win32_check: for thread %#x buffer_condition:%#x\n"
663              "  watch->pollfd.events:%#x watch->pollfd.revents:%#x channel->revents:%#x\n",
664              channel->thread_id, buffer_condition,
665              watch->pollfd.events, watch->pollfd.revents, channel->revents);
666
667   if (channel->type != G_IO_WIN32_WINDOWS_MESSAGES)
668     {
669       watch->pollfd.revents = (watch->pollfd.events & channel->revents);
670     }
671   else
672     {
673       return (PeekMessage (&msg, channel->hwnd, 0, 0, PM_NOREMOVE));
674     }
675   
676   if (channel->type == G_IO_WIN32_SOCKET)
677     {
678       LOCK (channel->mutex);
679       if (channel->debug)
680         g_print ("g_io_win32_check: thread %#x, resetting data_avail\n",
681                  channel->thread_id);
682       ResetEvent (channel->data_avail_event);
683       if (channel->debug)
684         g_print ("g_io_win32_check: thread %#x, there.\n",
685                  channel->thread_id);
686       UNLOCK (channel->mutex);
687     }
688
689   return ((watch->pollfd.revents | buffer_condition) & watch->condition);
690 }
691
692 static gboolean
693 g_io_win32_dispatch (GSource     *source,
694                      GSourceFunc  callback,
695                      gpointer     user_data)
696 {
697   GIOFunc func = (GIOFunc)callback;
698   GIOWin32Watch *watch = (GIOWin32Watch *)source;
699   GIOCondition buffer_condition = g_io_channel_get_buffer_condition (watch->channel);
700   
701   if (!func)
702     {
703       g_warning (G_STRLOC ": GIOWin32Watch dispatched without callback\n"
704                  "You must call g_source_connect().");
705       return FALSE;
706     }
707   
708   return (*func) (watch->channel,
709                   (watch->pollfd.revents | buffer_condition) & watch->condition,
710                   user_data);
711 }
712
713 static void
714 g_io_win32_finalize (GSource *source)
715 {
716   GIOWin32Watch *watch = (GIOWin32Watch *)source;
717   GIOWin32Channel *channel = (GIOWin32Channel *)watch->channel;
718   char send_buffer[] = "f";
719   
720   LOCK (channel->mutex);
721   if (channel->debug)
722     g_print ("g_io_win32_finalize: channel with thread %#x\n",
723              channel->thread_id);
724
725   channel->watches = g_slist_remove (channel->watches, watch);
726
727   SetEvent (channel->data_avail_noticed_event);
728   if (channel->type == G_IO_WIN32_SOCKET)
729     send (channel->reset_send, send_buffer, sizeof (send_buffer), 0);
730
731   g_io_channel_unref (watch->channel);
732   UNLOCK (channel->mutex);
733 }
734
735 GSourceFuncs g_io_watch_funcs = {
736   g_io_win32_prepare,
737   g_io_win32_check,
738   g_io_win32_dispatch,
739   g_io_win32_finalize
740 };
741
742 static GSource *
743 g_io_win32_create_watch (GIOChannel    *channel,
744                          GIOCondition   condition,
745                          unsigned (__stdcall *thread) (void *parameter))
746 {
747   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
748   GIOWin32Watch *watch;
749   GSource *source;
750   char send_buffer[] = "c";
751
752   source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
753   watch = (GIOWin32Watch *)source;
754   
755   watch->channel = channel;
756   g_io_channel_ref (channel);
757   
758   watch->condition = condition;
759   
760   if (win32_channel->data_avail_event == NULL)
761     create_events (win32_channel);
762
763   watch->pollfd.fd = (gint) win32_channel->data_avail_event;
764   watch->pollfd.events = condition;
765   
766   if (win32_channel->debug)
767     g_print ("g_io_win32_create_watch: fd:%d condition:%#x handle:%#x\n",
768              win32_channel->fd, condition, watch->pollfd.fd);
769
770   LOCK (win32_channel->mutex);
771   win32_channel->watches = g_slist_append (win32_channel->watches, watch);
772
773   if (win32_channel->thread_id == 0)
774     create_thread (win32_channel, condition, thread);
775   else
776     send (win32_channel->reset_send, send_buffer, sizeof (send_buffer), 0);
777
778   g_source_add_poll (source, &watch->pollfd);
779   UNLOCK (win32_channel->mutex);
780
781   return source;
782 }
783
784 static GIOStatus
785 g_io_win32_msg_read (GIOChannel *channel,
786                      gchar      *buf,
787                      gsize       count,
788                      gsize      *bytes_read,
789                      GError    **err)
790 {
791   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
792   MSG msg;               /* In case of alignment problems */
793   
794   if (count < sizeof (MSG))
795     {
796       g_set_error (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_INVAL,
797                    "Incorrect message size"); /* Informative enough error message? */
798       return G_IO_STATUS_ERROR;
799     }
800   
801   if (win32_channel->debug)
802     g_print ("g_io_win32_msg_read: for %#x\n",
803              (guint) win32_channel->hwnd);
804   if (!PeekMessage (&msg, win32_channel->hwnd, 0, 0, PM_REMOVE))
805     return G_IO_STATUS_AGAIN;
806
807   memmove (buf, &msg, sizeof (MSG));
808   *bytes_read = sizeof (MSG);
809
810   return G_IO_STATUS_NORMAL;
811 }
812
813 static GIOStatus
814 g_io_win32_msg_write (GIOChannel  *channel,
815                       const gchar *buf,
816                       gsize        count,
817                       gsize       *bytes_written,
818                       GError     **err)
819 {
820   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
821   MSG msg;
822   
823   if (count != sizeof (MSG))
824     {
825       g_set_error (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_INVAL,
826                    "Incorrect message size"); /* Informative enough error message? */
827       return G_IO_STATUS_ERROR;
828     }
829   
830   /* In case of alignment problems */
831   memmove (&msg, buf, sizeof (MSG));
832   if (!PostMessage (win32_channel->hwnd, msg.message, msg.wParam, msg.lParam))
833     {
834       gchar *emsg = g_win32_error_message (GetLastError ());
835       g_set_error (err, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED, emsg);
836       g_free (emsg);
837       return G_IO_STATUS_ERROR;
838     }
839
840   *bytes_written = sizeof (MSG);
841
842   return G_IO_STATUS_NORMAL;
843 }
844
845 static GIOStatus
846 g_io_win32_msg_close (GIOChannel *channel,
847                       GError    **err)
848 {
849   /* Nothing to be done. Or should we set hwnd to some invalid value? */
850
851   return G_IO_STATUS_NORMAL;
852 }
853
854 static void
855 g_io_win32_free (GIOChannel *channel)
856 {
857   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
858   
859   if (win32_channel->debug)
860     g_print ("thread %#x: freeing channel, fd: %d\n",
861              win32_channel->thread_id,
862              win32_channel->fd);
863
864   if (win32_channel->reset_send)
865     closesocket (win32_channel->reset_send);
866   if (win32_channel->reset_recv)
867     closesocket (win32_channel->reset_recv);
868   if (win32_channel->data_avail_event)
869     CloseHandle (win32_channel->data_avail_event);
870   if (win32_channel->space_avail_event)
871     CloseHandle (win32_channel->space_avail_event);
872   if (win32_channel->data_avail_noticed_event)
873     CloseHandle (win32_channel->data_avail_noticed_event);
874   DeleteCriticalSection (&win32_channel->mutex);
875
876   g_free (win32_channel->buffer);
877   g_slist_free (win32_channel->watches);
878   g_free (win32_channel);
879 }
880
881 static GSource *
882 g_io_win32_msg_create_watch (GIOChannel    *channel,
883                              GIOCondition   condition)
884 {
885   GIOWin32Watch *watch;
886   GSource *source;
887
888   source = g_source_new (&g_io_watch_funcs, sizeof (GIOWin32Watch));
889   watch = (GIOWin32Watch *)source;
890   
891   watch->channel = channel;
892   g_io_channel_ref (channel);
893   
894   watch->condition = condition;
895   
896   watch->pollfd.fd = G_WIN32_MSG_HANDLE;
897   watch->pollfd.events = condition;
898   
899   g_source_add_poll (source, &watch->pollfd);
900   
901   return source;
902 }
903
904 static GIOStatus
905 g_io_win32_fd_read (GIOChannel *channel,
906                     gchar      *buf,
907                     gsize       count,
908                     gsize      *bytes_read,
909                     GError    **err)
910 {
911   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
912   gint result;
913   
914   if (win32_channel->debug)
915     g_print ("g_io_win32_fd_read: fd:%d count:%d\n",
916              win32_channel->fd, count);
917   
918   if (win32_channel->thread_id)
919     {
920       return buffer_read (win32_channel, buf, count, bytes_read, err);
921     }
922
923   result = read (win32_channel->fd, buf, count);
924
925   if (win32_channel->debug)
926     g_print ("g_io_win32_fd_read: read() = %d\n", result);
927
928   if (result < 0)
929     {
930       *bytes_read = 0;
931
932       switch (errno)
933         {
934 #ifdef EAGAIN
935         case EAGAIN:
936           return G_IO_STATUS_AGAIN;
937 #endif
938         default:
939           g_set_error (err, G_IO_CHANNEL_ERROR,
940                        g_io_channel_error_from_errno (errno),
941                        g_strerror (errno));
942           return G_IO_STATUS_ERROR;
943         }
944     }
945
946   *bytes_read = result;
947
948   return (result > 0) ? G_IO_STATUS_NORMAL : G_IO_STATUS_EOF;
949 }
950
951 static GIOStatus
952 g_io_win32_fd_write (GIOChannel  *channel,
953                      const gchar *buf,
954                      gsize        count,
955                      gsize       *bytes_written,
956                      GError     **err)
957 {
958   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
959   gint result;
960   
961   result = write (win32_channel->fd, buf, count);
962   if (win32_channel->debug)
963     g_print ("g_io_win32_fd_write: fd:%d count:%d = %d\n",
964              win32_channel->fd, count, result);
965
966   if (result < 0)
967     {
968       *bytes_written = 0;
969
970       switch (errno)
971         {
972 #ifdef EAGAIN
973         case EAGAIN:
974           return G_IO_STATUS_AGAIN;
975 #endif
976         default:
977           g_set_error (err, G_IO_CHANNEL_ERROR,
978                        g_io_channel_error_from_errno (errno),
979                        g_strerror (errno));
980           return G_IO_STATUS_ERROR;
981         }
982     }
983
984   *bytes_written = result;
985
986   return G_IO_STATUS_NORMAL;
987 }
988
989 static GIOStatus
990 g_io_win32_fd_seek (GIOChannel *channel,
991                     gint64      offset,
992                     GSeekType   type,
993                     GError    **err)
994 {
995   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
996   int whence;
997   off_t tmp_offset;
998   off_t result;
999   
1000   switch (type)
1001     {
1002     case G_SEEK_SET:
1003       whence = SEEK_SET;
1004       break;
1005     case G_SEEK_CUR:
1006       whence = SEEK_CUR;
1007       break;
1008     case G_SEEK_END:
1009       whence = SEEK_END;
1010       break;
1011     default:
1012       whence = -1; /* Keep the compiler quiet */
1013       g_assert_not_reached ();
1014     }
1015
1016   tmp_offset = offset;
1017   if (tmp_offset != offset)
1018     {
1019       g_set_error (err, G_IO_CHANNEL_ERROR,
1020                    g_io_channel_error_from_errno (EINVAL),
1021                    g_strerror (EINVAL));
1022       return G_IO_STATUS_ERROR;
1023     }
1024   
1025   result = lseek (win32_channel->fd, tmp_offset, whence);
1026   
1027   if (result < 0)
1028     {
1029       g_set_error (err, G_IO_CHANNEL_ERROR,
1030                    g_io_channel_error_from_errno (errno),
1031                    g_strerror (errno));
1032       return G_IO_STATUS_ERROR;
1033     }
1034
1035   return G_IO_STATUS_NORMAL;
1036 }
1037
1038 static GIOStatus
1039 g_io_win32_fd_close (GIOChannel *channel,
1040                      GError    **err)
1041 {
1042   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1043   
1044   if (win32_channel->debug)
1045     g_print ("thread %#x: closing fd %d\n",
1046              win32_channel->thread_id,
1047              win32_channel->fd);
1048   LOCK (win32_channel->mutex);
1049   if (win32_channel->running)
1050     {
1051       if (win32_channel->debug)
1052         g_print ("thread %#x: running, marking fd %d for later close\n",
1053                  win32_channel->thread_id, win32_channel->fd);
1054       win32_channel->running = FALSE;
1055       win32_channel->needs_close = TRUE;
1056       SetEvent (win32_channel->data_avail_event);
1057     }
1058   else
1059     {
1060       if (win32_channel->debug)
1061         g_print ("closing fd %d\n", win32_channel->fd);
1062       close (win32_channel->fd);
1063       if (win32_channel->debug)
1064         g_print ("closed fd %d, setting to -1\n",
1065                  win32_channel->fd);
1066       win32_channel->fd = -1;
1067     }
1068   UNLOCK (win32_channel->mutex);
1069
1070   /* FIXME error detection? */
1071
1072   return G_IO_STATUS_NORMAL;
1073 }
1074
1075 static GSource *
1076 g_io_win32_fd_create_watch (GIOChannel    *channel,
1077                             GIOCondition   condition)
1078 {
1079   return g_io_win32_create_watch (channel, condition, read_thread);
1080 }
1081
1082 static GIOStatus
1083 g_io_win32_sock_read (GIOChannel *channel,
1084                       gchar      *buf,
1085                       gsize       count,
1086                       gsize      *bytes_read,
1087                       GError    **err)
1088 {
1089   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1090   gint result;
1091   GIOChannelError error = G_IO_STATUS_NORMAL;
1092   GIOStatus internal_status = G_IO_STATUS_NORMAL;
1093   char send_buffer[] = "sr";
1094
1095   if (win32_channel->debug)
1096     g_print ("g_io_win32_sock_read: sockfd:%d count:%d\n",
1097              win32_channel->fd, count);
1098 #ifdef WE_NEED_TO_HANDLE_WSAEINTR
1099 repeat:
1100 #endif
1101   result = recv (win32_channel->fd, buf, count, 0);
1102
1103   if (win32_channel->debug)
1104     g_print ("g_io_win32_sock_read: recv:%d\n", result);
1105   
1106   if (result == SOCKET_ERROR)
1107     {
1108       *bytes_read = 0;
1109
1110       switch (WSAGetLastError ())
1111         {
1112         case WSAEINVAL:
1113           error = G_IO_CHANNEL_ERROR_INVAL;
1114           break;
1115         case WSAEWOULDBLOCK:
1116           return G_IO_STATUS_AGAIN;
1117 #ifdef WE_NEED_TO_HANDLE_WSAEINTR /* not anymore with wsock2 ? */
1118         case WSAEINTR:
1119           goto repeat;
1120 #endif
1121         default:
1122           error = G_IO_CHANNEL_ERROR_FAILED;
1123           break;
1124         }
1125       g_set_error (err, G_IO_CHANNEL_ERROR, error, "Socket read error");
1126       internal_status = G_IO_STATUS_ERROR;
1127       /* FIXME get all errors, better error messages */
1128     }
1129   else
1130     {
1131       *bytes_read = result;
1132       if (result == 0)
1133         internal_status = G_IO_STATUS_EOF;
1134     }
1135
1136   if ((internal_status == G_IO_STATUS_EOF) || 
1137       (internal_status == G_IO_STATUS_ERROR))
1138     {
1139       LOCK (win32_channel->mutex);
1140       SetEvent (win32_channel->data_avail_noticed_event);
1141       win32_channel->needs_close = 1;
1142       send (win32_channel->reset_send, send_buffer, sizeof (send_buffer), 0);
1143       UNLOCK (win32_channel->mutex);
1144     }
1145   return internal_status;
1146 }
1147
1148 static GIOStatus
1149 g_io_win32_sock_write (GIOChannel  *channel,
1150                        const gchar *buf,
1151                        gsize        count,
1152                        gsize       *bytes_written,
1153                        GError     **err)
1154 {
1155   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1156   gint result;
1157   GIOChannelError error = G_IO_STATUS_NORMAL;
1158   char send_buffer[] = "sw";
1159   
1160   if (win32_channel->debug)
1161     g_print ("g_io_win32_sock_write: sockfd:%d count:%d\n",
1162              win32_channel->fd, count);
1163 #ifdef WE_NEED_TO_HANDLE_WSAEINTR
1164 repeat:
1165 #endif
1166   result = send (win32_channel->fd, buf, count, 0);
1167   
1168   if (win32_channel->debug)
1169     g_print ("g_io_win32_sock_write: send:%d\n", result);
1170   
1171   if (result == SOCKET_ERROR)
1172     {
1173       *bytes_written = 0;
1174
1175       switch (WSAGetLastError ())
1176         {
1177         case WSAEINVAL:
1178           error = G_IO_CHANNEL_ERROR_INVAL;
1179           break;
1180         case WSAEWOULDBLOCK:
1181           return G_IO_STATUS_AGAIN;
1182 #ifdef WE_NEED_TO_HANDLE_WSAEINTR /* not anymore with wsock2 ? */
1183         case WSAEINTR:
1184           goto repeat;
1185 #endif
1186         default:
1187           error = G_IO_CHANNEL_ERROR_FAILED;
1188           break;
1189         }
1190       g_set_error (err, G_IO_CHANNEL_ERROR, error, "Socket write error");
1191       LOCK (win32_channel->mutex);
1192       SetEvent (win32_channel->data_avail_noticed_event);
1193       win32_channel->needs_close = 1;
1194       send (win32_channel->reset_send, send_buffer, sizeof (send_buffer), 0);
1195       UNLOCK (win32_channel->mutex);
1196       return G_IO_STATUS_ERROR;
1197       /* FIXME get all errors, better error messages */
1198     }
1199   else
1200     {
1201       *bytes_written = result;
1202
1203       return G_IO_STATUS_NORMAL;
1204     }
1205 }
1206
1207 static GIOStatus
1208 g_io_win32_sock_close (GIOChannel *channel,
1209                        GError    **err)
1210 {
1211   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1212
1213   LOCK (win32_channel->mutex);
1214   if (win32_channel->running)
1215     {
1216       if (win32_channel->debug)
1217         g_print ("thread %#x: running, marking for later close\n",
1218                  win32_channel->thread_id);
1219       win32_channel->running = FALSE;
1220       win32_channel->needs_close = TRUE;
1221       SetEvent(win32_channel->data_avail_noticed_event);
1222     }
1223   if (win32_channel->fd != -1)
1224     {
1225       if (win32_channel->debug)
1226         g_print ("thread %#x: closing socket %d\n",
1227                  win32_channel->thread_id,
1228                  win32_channel->fd);
1229       
1230       closesocket (win32_channel->fd);
1231       win32_channel->fd = -1;
1232     }
1233   UNLOCK (win32_channel->mutex);
1234
1235   /* FIXME error detection? */
1236
1237   return G_IO_STATUS_NORMAL;
1238 }
1239
1240 static GSource *
1241 g_io_win32_sock_create_watch (GIOChannel    *channel,
1242                               GIOCondition   condition)
1243 {
1244   return g_io_win32_create_watch (channel, condition, select_thread);
1245 }
1246
1247 GIOChannel *
1248 g_io_channel_new_file (const gchar  *filename,
1249                        const gchar  *mode,
1250                        GError      **error)
1251 {
1252   int fid, flags, pmode;
1253   GIOChannel *channel;
1254
1255   enum { /* Cheesy hack */
1256     MODE_R = 1 << 0,
1257     MODE_W = 1 << 1,
1258     MODE_A = 1 << 2,
1259     MODE_PLUS = 1 << 3,
1260   } mode_num;
1261
1262   g_return_val_if_fail (filename != NULL, NULL);
1263   g_return_val_if_fail (mode != NULL, NULL);
1264   g_return_val_if_fail ((error == NULL) || (*error == NULL), NULL);
1265
1266   switch (mode[0])
1267     {
1268       case 'r':
1269         mode_num = MODE_R;
1270         break;
1271       case 'w':
1272         mode_num = MODE_W;
1273         break;
1274       case 'a':
1275         mode_num = MODE_A;
1276         break;
1277       default:
1278         g_warning ("Invalid GIOFileMode %s.\n", mode);
1279         return NULL;
1280     }
1281
1282   switch (mode[1])
1283     {
1284       case '\0':
1285         break;
1286       case '+':
1287         if (mode[2] == '\0')
1288           {
1289             mode_num |= MODE_PLUS;
1290             break;
1291           }
1292         /* Fall through */
1293       default:
1294         g_warning ("Invalid GIOFileMode %s.\n", mode);
1295         return NULL;
1296     }
1297
1298   switch (mode_num)
1299     {
1300       case MODE_R:
1301         flags = O_RDONLY;
1302         pmode = _S_IREAD;
1303         break;
1304       case MODE_W:
1305         flags = O_WRONLY | O_TRUNC | O_CREAT;
1306         pmode = _S_IWRITE;
1307         break;
1308       case MODE_A:
1309         flags = O_WRONLY | O_APPEND | O_CREAT;
1310         pmode = _S_IWRITE;
1311         break;
1312       case MODE_R | MODE_PLUS:
1313         flags = O_RDWR;
1314         pmode = _S_IREAD | _S_IWRITE;
1315         break;
1316       case MODE_W | MODE_PLUS:
1317         flags = O_RDWR | O_TRUNC | O_CREAT;
1318         pmode = _S_IREAD | _S_IWRITE;
1319         break;
1320       case MODE_A | MODE_PLUS:
1321         flags = O_RDWR | O_APPEND | O_CREAT;
1322         pmode = _S_IREAD | _S_IWRITE;
1323         break;
1324       default:
1325         g_assert_not_reached ();
1326         flags = 0;
1327         pmode = 0;
1328     }
1329
1330   /* always open 'untranslated' */
1331   fid = open (filename, flags | _O_BINARY, pmode);
1332
1333   if (g_io_win32_get_debug_flag ())
1334     {
1335       g_print ("g_io_channel_win32_new_file: open(\"%s\", ", filename);
1336       g_win32_print_access_mode (flags|_O_BINARY);
1337       g_print (",%#o)=%d\n", pmode, fid);
1338     }
1339
1340   if (fid < 0)
1341     {
1342       g_set_error (error, G_FILE_ERROR,
1343                    g_file_error_from_errno (errno),
1344                    g_strerror (errno));
1345       return (GIOChannel *)NULL;
1346     }
1347
1348   channel = g_io_channel_win32_new_fd (fid);
1349
1350   /* XXX: move this to g_io_channel_win32_new_fd () */
1351   channel->close_on_unref = TRUE;
1352   channel->is_seekable = TRUE;
1353
1354   /* g_io_channel_win32_new_fd sets is_readable and is_writeable to
1355    * correspond to actual readability/writeability. Set to FALSE those
1356    * that mode doesn't allow
1357    */
1358   switch (mode_num)
1359     {
1360       case MODE_R:
1361         channel->is_writeable = FALSE;
1362         break;
1363       case MODE_W:
1364       case MODE_A:
1365         channel->is_readable = FALSE;
1366         break;
1367       case MODE_R | MODE_PLUS:
1368       case MODE_W | MODE_PLUS:
1369       case MODE_A | MODE_PLUS:
1370         break;
1371       default:
1372         g_assert_not_reached ();
1373     }
1374
1375   return channel;
1376 }
1377
1378 static GIOStatus
1379 g_io_win32_set_flags (GIOChannel *channel,
1380                       GIOFlags    flags,
1381                       GError    **err)
1382 {
1383   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1384
1385   if (win32_channel->debug)
1386     {
1387       g_print ("g_io_win32_set_flags: ");
1388       g_win32_print_gioflags (flags);
1389       g_print ("\n");
1390     }
1391
1392   g_warning ("g_io_win32_set_flags () not implemented.\n");
1393
1394   return G_IO_STATUS_NORMAL;
1395 }
1396
1397 static GIOFlags
1398 g_io_win32_fd_get_flags_internal (GIOChannel  *channel,
1399                                   struct stat *st)
1400 {
1401   GIOWin32Channel *win32_channel = (GIOWin32Channel *) channel;
1402   gchar c;
1403   DWORD count;
1404
1405   if (st->st_mode & _S_IFIFO)
1406     {
1407       channel->is_readable =
1408         (PeekNamedPipe ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL, NULL) != 0) || GetLastError () == ERROR_BROKEN_PIPE;
1409       channel->is_writeable =
1410         (WriteFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1411       channel->is_seekable  = FALSE;
1412     }
1413   else if (st->st_mode & _S_IFCHR)
1414     {
1415       /* XXX Seems there is no way to find out the readability of file
1416        * handles to device files (consoles, mostly) without doing a
1417        * blocking read. So punt, use st->st_mode.
1418        */
1419       channel->is_readable  = !!(st->st_mode & _S_IREAD);
1420
1421       channel->is_writeable =
1422         (WriteFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1423
1424       /* XXX What about devices that actually *are* seekable? But
1425        * those would probably not be handled using the C runtime
1426        * anyway, but using Windows-specific code.
1427        */
1428       channel->is_seekable = FALSE;
1429     }
1430   else
1431     {
1432       channel->is_readable =
1433         (ReadFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1434       channel->is_writeable =
1435         (WriteFile ((HANDLE) _get_osfhandle (win32_channel->fd), &c, 0, &count, NULL) != 0);
1436       channel->is_seekable = TRUE;
1437     }
1438
1439   /* XXX: G_IO_FLAG_APPEND */
1440   /* XXX: G_IO_FLAG_NONBLOCK */
1441
1442   return 0;
1443 }
1444
1445 static GIOFlags
1446 g_io_win32_fd_get_flags (GIOChannel *channel)
1447 {
1448   struct stat st;
1449   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1450
1451   g_return_val_if_fail (win32_channel != NULL, 0);
1452   g_return_val_if_fail (win32_channel->type == G_IO_WIN32_FILE_DESC, 0);
1453
1454   if (0 == fstat (win32_channel->fd, &st))
1455     return g_io_win32_fd_get_flags_internal (channel, &st);
1456   else
1457     return 0;
1458 }
1459
1460 static GIOFlags
1461 g_io_win32_msg_get_flags (GIOChannel *channel)
1462 {
1463   return 0;
1464 }
1465
1466 static GIOFlags
1467 g_io_win32_sock_get_flags (GIOChannel *channel)
1468 {
1469   /* XXX Could do something here. */
1470   return 0;
1471 }
1472
1473 static GIOFuncs win32_channel_msg_funcs = {
1474   g_io_win32_msg_read,
1475   g_io_win32_msg_write,
1476   NULL,
1477   g_io_win32_msg_close,
1478   g_io_win32_msg_create_watch,
1479   g_io_win32_free,
1480   g_io_win32_set_flags,
1481   g_io_win32_msg_get_flags,
1482 };
1483
1484 static GIOFuncs win32_channel_fd_funcs = {
1485   g_io_win32_fd_read,
1486   g_io_win32_fd_write,
1487   g_io_win32_fd_seek,
1488   g_io_win32_fd_close,
1489   g_io_win32_fd_create_watch,
1490   g_io_win32_free,
1491   g_io_win32_set_flags,
1492   g_io_win32_fd_get_flags,
1493 };
1494
1495 static GIOFuncs win32_channel_sock_funcs = {
1496   g_io_win32_sock_read,
1497   g_io_win32_sock_write,
1498   NULL,
1499   g_io_win32_sock_close,
1500   g_io_win32_sock_create_watch,
1501   g_io_win32_free,
1502   g_io_win32_set_flags,
1503   g_io_win32_sock_get_flags,
1504 };
1505
1506 GIOChannel *
1507 g_io_channel_win32_new_messages (guint hwnd)
1508 {
1509   GIOWin32Channel *win32_channel = g_new (GIOWin32Channel, 1);
1510   GIOChannel *channel = (GIOChannel *)win32_channel;
1511
1512   g_io_channel_init (channel);
1513   g_io_channel_win32_init (win32_channel);
1514   if (win32_channel->debug)
1515     g_print ("g_io_channel_win32_new_messages: hwnd = %ud\n", hwnd);
1516   channel->funcs = &win32_channel_msg_funcs;
1517   win32_channel->type = G_IO_WIN32_WINDOWS_MESSAGES;
1518   win32_channel->hwnd = (HWND) hwnd;
1519
1520   /* XXX: check this. */
1521   channel->is_readable = IsWindow (win32_channel->hwnd);
1522   channel->is_writeable = IsWindow (win32_channel->hwnd);
1523
1524   channel->is_seekable = FALSE;
1525
1526   return channel;
1527 }
1528
1529 static GIOChannel *
1530 g_io_channel_win32_new_fd_internal (gint         fd,
1531                                     struct stat *st)
1532 {
1533   GIOWin32Channel *win32_channel;
1534   GIOChannel *channel;
1535
1536   win32_channel = g_new (GIOWin32Channel, 1);
1537   channel = (GIOChannel *)win32_channel;
1538
1539   g_io_channel_init (channel);
1540   g_io_channel_win32_init (win32_channel);
1541   if (win32_channel->debug)
1542     g_print ("g_io_channel_win32_new_fd: %u\n", fd);
1543   channel->funcs = &win32_channel_fd_funcs;
1544   win32_channel->type = G_IO_WIN32_FILE_DESC;
1545   win32_channel->fd = fd;
1546
1547   g_io_win32_fd_get_flags_internal (channel, st);
1548   
1549   return channel;
1550 }
1551
1552 GIOChannel *
1553 g_io_channel_win32_new_fd (gint fd)
1554 {
1555   struct stat st;
1556
1557   if (fstat (fd, &st) == -1)
1558     {
1559       g_warning (G_STRLOC ": %d isn't a C library file descriptor", fd);
1560       return NULL;
1561     }
1562
1563   return g_io_channel_win32_new_fd_internal (fd, &st);
1564 }
1565
1566 gint
1567 g_io_channel_win32_get_fd (GIOChannel *channel)
1568 {
1569   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1570
1571   return win32_channel->fd;
1572 }
1573
1574 GIOChannel *
1575 g_io_channel_win32_new_socket (int socket)
1576 {
1577   GIOWin32Channel *win32_channel = g_new (GIOWin32Channel, 1);
1578   GIOChannel *channel = (GIOChannel *)win32_channel;
1579
1580   g_io_channel_init (channel);
1581   g_io_channel_win32_init (win32_channel);
1582   init_reset_sockets (win32_channel);
1583   if (win32_channel->debug)
1584     g_print ("g_io_channel_win32_new_socket: sockfd:%d\n", socket);
1585   channel->funcs = &win32_channel_sock_funcs;
1586   win32_channel->type = G_IO_WIN32_SOCKET;
1587   win32_channel->fd = socket;
1588
1589   /* XXX: check this */
1590   channel->is_readable = TRUE;
1591   channel->is_writeable = TRUE;
1592
1593   channel->is_seekable = FALSE;
1594
1595   return channel;
1596 }
1597
1598 GIOChannel *
1599 g_io_channel_unix_new (gint fd)
1600 {
1601   gboolean is_fd, is_socket;
1602   struct stat st;
1603   int optval, optlen;
1604
1605   is_fd = (fstat (fd, &st) == 0);
1606
1607   optlen = sizeof (optval);
1608   is_socket = (getsockopt (fd, SOL_SOCKET, SO_TYPE, (char *) &optval, &optlen) != SOCKET_ERROR);
1609
1610   if (is_fd && is_socket)
1611     g_warning (G_STRLOC ": %d is both a file descriptor and a socket, file descriptor interpretation assumed.", fd);
1612
1613   if (is_fd)
1614     return g_io_channel_win32_new_fd_internal (fd, &st);
1615
1616   if (is_socket)
1617     return g_io_channel_win32_new_socket(fd);
1618
1619   g_warning (G_STRLOC ": %d is neither a file descriptor or a socket", fd);
1620
1621   return NULL;
1622 }
1623
1624 gint
1625 g_io_channel_unix_get_fd (GIOChannel *channel)
1626 {
1627   return g_io_channel_win32_get_fd (channel);
1628 }
1629
1630 void
1631 g_io_channel_win32_set_debug (GIOChannel *channel,
1632                               gboolean    flag)
1633 {
1634   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1635
1636   win32_channel->debug = flag;
1637 }
1638
1639 gint
1640 g_io_channel_win32_poll (GPollFD *fds,
1641                          gint     n_fds,
1642                          gint     timeout)
1643 {
1644   int result;
1645
1646   g_return_val_if_fail (n_fds >= 0, 0);
1647
1648   result = (*g_main_context_get_poll_func (NULL)) (fds, n_fds, timeout);
1649
1650   return result;
1651 }
1652
1653 void
1654 g_io_channel_win32_make_pollfd (GIOChannel   *channel,
1655                                 GIOCondition  condition,
1656                                 GPollFD      *fd)
1657 {
1658   GIOWin32Channel *win32_channel = (GIOWin32Channel *)channel;
1659
1660   if (win32_channel->data_avail_event == NULL)
1661     create_events (win32_channel);
1662   
1663   fd->fd = (gint) win32_channel->data_avail_event;
1664   fd->events = condition;
1665
1666   if (win32_channel->thread_id == 0)
1667     {
1668       if ((condition & G_IO_IN) && win32_channel->type == G_IO_WIN32_FILE_DESC)
1669         create_thread (win32_channel, condition, read_thread);
1670       else if (win32_channel->type == G_IO_WIN32_SOCKET)
1671         create_thread (win32_channel, condition, select_thread);
1672     }
1673 }
1674
1675 /* Binary compatibility */
1676 GIOChannel *
1677 g_io_channel_win32_new_stream_socket (int socket)
1678 {
1679   return g_io_channel_win32_new_socket (socket);
1680 }