GIO: Remove trailing "." from Since: tags in docs
[platform/upstream/glib.git] / gio / gsocket.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4  * Copyright © 2009 Codethink Limited
5  * Copyright © 2009 Red Hat, Inc
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Authors: Christian Kellner <gicmo@gnome.org>
23  *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
24  *          Ryan Lortie <desrt@desrt.ca>
25  *          Alexander Larsson <alexl@redhat.com>
26  */
27
28 #include "config.h"
29 #include "glib.h"
30
31 #include <errno.h>
32 #include <signal.h>
33 #include <string.h>
34 #include <stdlib.h>
35
36 #ifndef G_OS_WIN32
37 # include <fcntl.h>
38 # include <unistd.h>
39 #endif
40
41 #ifdef HAVE_SYS_UIO_H
42 #include <sys/uio.h>
43 #endif
44
45 #include "gsocket.h"
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginitable.h"
49 #include "gasynchelper.h"
50 #include "gioerror.h"
51 #include "gioenums.h"
52 #include "gioerror.h"
53 #include "gnetworkingprivate.h"
54 #include "glibintl.h"
55
56 #include "gioalias.h"
57
58 /**
59  * SECTION:gsocket
60  * @short_description: Low-level socket object
61  * @include: gio/gio.h
62  * @see_also: #GInitable
63  *
64  * A #GSocket is a low-level networking primitive. It is a more or less
65  * direct mapping of the BSD socket API in a portable GObject based API.
66  * It supports both the UNIX socket implementations and winsock2 on Windows.
67  *
68  * #GSocket is the platform independent base upon which the higher level
69  * network primitives are based. Applications are not typically meant to
70  * use it directly, but rather through classes like #GSocketClient,
71  * #GSocketService and #GSocketConnection. However there may be cases where
72  * direct use of #GSocket is useful.
73  *
74  * #GSocket implements the #GInitable interface, so if it is manually constructed
75  * by e.g. g_object_new() you must call g_initable_init() and check the
76  * results before using the object. This is done automatically in
77  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
78  * %NULL.
79  *
80  * Sockets operate in two general modes, blocking or non-blocking. When
81  * in blocking mode all operations block until the requested operation
82  * is finished or there is an error. In non-blocking mode all calls that
83  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
84  * To know when a call would successfully run you can call g_socket_condition_check(),
85  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
86  * attach it to a #GMainContext to get callbacks when I/O is possible.
87  * Note that all sockets are always set to non blocking mode in the system, and
88  * blocking mode is emulated in GSocket.
89  *
90  * When working in non-blocking mode applications should always be able to
91  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
92  * function said that I/O was possible. This can easily happen in case
93  * of a race condition in the application, but it can also happen for other
94  * reasons. For instance, on Windows a socket is always seen as writable
95  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
96  *
97  * #GSocket<!-- -->s can be either connection oriented or datagram based.
98  * For connection oriented types you must first establish a connection by
99  * either connecting to an address or accepting a connection from another
100  * address. For connectionless socket types the target/source address is
101  * specified or received in each I/O operation.
102  *
103  * All socket file descriptors are set to be close-on-exec.
104  *
105  * Note that creating a #GSocket causes the signal %SIGPIPE to be
106  * ignored for the remainder of the program. If you are writing a
107  * command-line utility that uses #GSocket, you may need to take into
108  * account the fact that your program will not automatically be killed
109  * if it tries to write to %stdout after it has been closed.
110  *
111  * Since: 2.22
112  */
113
114 static void     g_socket_initable_iface_init (GInitableIface  *iface);
115 static gboolean g_socket_initable_init       (GInitable       *initable,
116                                               GCancellable    *cancellable,
117                                               GError         **error);
118
119 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
120                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
121                                                 g_socket_initable_iface_init));
122
123 enum
124 {
125   PROP_0,
126   PROP_FAMILY,
127   PROP_TYPE,
128   PROP_PROTOCOL,
129   PROP_FD,
130   PROP_BLOCKING,
131   PROP_LISTEN_BACKLOG,
132   PROP_KEEPALIVE,
133   PROP_LOCAL_ADDRESS,
134   PROP_REMOTE_ADDRESS
135 };
136
137 struct _GSocketPrivate
138 {
139   GSocketFamily   family;
140   GSocketType     type;
141   GSocketProtocol protocol;
142   gint            fd;
143   gint            listen_backlog;
144   GError         *construct_error;
145   guint           inited : 1;
146   guint           blocking : 1;
147   guint           keepalive : 1;
148   guint           closed : 1;
149   guint           connected : 1;
150   guint           listening : 1;
151 #ifdef G_OS_WIN32
152   WSAEVENT        event;
153   int             current_events;
154   int             current_errors;
155   int             selected_events;
156   GList          *requested_conditions; /* list of requested GIOCondition * */
157 #endif
158 };
159
160 static int
161 get_socket_errno (void)
162 {
163 #ifndef G_OS_WIN32
164   return errno;
165 #else
166   return WSAGetLastError ();
167 #endif
168 }
169
170 static GIOErrorEnum
171 socket_io_error_from_errno (int err)
172 {
173 #ifndef G_OS_WIN32
174   return g_io_error_from_errno (err);
175 #else
176   switch (err)
177     {
178     case WSAEADDRINUSE:
179       return G_IO_ERROR_ADDRESS_IN_USE;
180     case WSAEWOULDBLOCK:
181       return G_IO_ERROR_WOULD_BLOCK;
182     case WSAEACCES:
183       return G_IO_ERROR_PERMISSION_DENIED;
184     case WSA_INVALID_HANDLE:
185     case WSA_INVALID_PARAMETER:
186     case WSAEBADF:
187     case WSAENOTSOCK:
188       return G_IO_ERROR_INVALID_ARGUMENT;
189     case WSAEPROTONOSUPPORT:
190       return G_IO_ERROR_NOT_SUPPORTED;
191     case WSAECANCELLED:
192       return G_IO_ERROR_CANCELLED;
193     case WSAESOCKTNOSUPPORT:
194     case WSAEOPNOTSUPP:
195     case WSAEPFNOSUPPORT:
196     case WSAEAFNOSUPPORT:
197       return G_IO_ERROR_NOT_SUPPORTED;
198     default:
199       return G_IO_ERROR_FAILED;
200     }
201 #endif
202 }
203
204 static const char *
205 socket_strerror (int err)
206 {
207 #ifndef G_OS_WIN32
208   return g_strerror (err);
209 #else
210   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
211   char *buf, *msg;
212
213   buf = g_static_private_get (&msg_private);
214   if (!buf)
215     {
216       buf = g_new (gchar, 128);
217       g_static_private_set (&msg_private, buf, g_free);
218     }
219
220   msg = g_win32_error_message (err);
221   strncpy (buf, msg, 128);
222   g_free (msg);
223   return buf;
224 #endif
225 }
226
227 #ifdef G_OS_WIN32
228 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
229 static void
230 _win32_unset_event_mask (GSocket *socket, int mask)
231 {
232   socket->priv->current_events &= ~mask;
233   socket->priv->current_errors &= ~mask;
234 }
235 #else
236 #define win32_unset_event_mask(_socket, _mask)
237 #endif
238
239 static void
240 set_fd_nonblocking (int fd)
241 {
242 #ifndef G_OS_WIN32
243   glong arg;
244 #else
245   gulong arg;
246 #endif
247
248 #ifndef G_OS_WIN32
249   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
250     {
251       g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
252       arg = 0;
253     }
254
255   arg = arg | O_NONBLOCK;
256
257   if (fcntl (fd, F_SETFL, arg) < 0)
258       g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
259 #else
260   arg = TRUE;
261
262   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
263     {
264       int errsv = get_socket_errno ();
265       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
266     }
267 #endif
268 }
269
270 static gboolean
271 check_socket (GSocket *socket,
272               GError **error)
273 {
274   if (!socket->priv->inited)
275     {
276       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277                            _("Invalid socket, not initialized"));
278       return FALSE;
279     }
280
281   if (socket->priv->construct_error)
282     {
283       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
284                    _("Invalid socket, initialization failed due to: %s"),
285                    socket->priv->construct_error->message);
286       return FALSE;
287     }
288
289   if (socket->priv->closed)
290     {
291       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
292                            _("Socket is already closed"));
293       return FALSE;
294     }
295   return TRUE;
296 }
297
298 static void
299 g_socket_details_from_fd (GSocket *socket)
300 {
301   struct sockaddr_storage address;
302   gint fd;
303   guint addrlen;
304   guint optlen;
305   int value;
306   int errsv;
307 #ifdef G_OS_WIN32
308   BOOL bool_val;
309 #else
310   int bool_val;
311 #endif
312
313   fd = socket->priv->fd;
314   optlen = sizeof value;
315   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
316     {
317       errsv = get_socket_errno ();
318
319       switch (errsv)
320         {
321 #ifdef ENOTSOCK
322          case ENOTSOCK:
323 #endif
324 #ifdef WSAENOTSOCK
325          case WSAENOTSOCK:
326 #endif
327          case EBADF:
328           /* programmer error */
329           g_error ("creating GSocket from fd %d: %s\n",
330                    fd, socket_strerror (errsv));
331          default:
332            break;
333         }
334
335       goto err;
336     }
337
338   g_assert (optlen == sizeof value);
339   switch (value)
340     {
341      case SOCK_STREAM:
342       socket->priv->type = G_SOCKET_TYPE_STREAM;
343       break;
344
345      case SOCK_DGRAM:
346       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
347       break;
348
349      case SOCK_SEQPACKET:
350       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
351       break;
352
353      default:
354       socket->priv->type = G_SOCKET_TYPE_INVALID;
355       break;
356     }
357
358   addrlen = sizeof address;
359   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
360     {
361       errsv = get_socket_errno ();
362       goto err;
363     }
364
365   g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
366             sizeof address.ss_family <= addrlen);
367   switch (address.ss_family)
368     {
369      case G_SOCKET_FAMILY_IPV4:
370      case G_SOCKET_FAMILY_IPV6:
371      case G_SOCKET_FAMILY_UNIX:
372       socket->priv->family = address.ss_family;
373       break;
374
375      default:
376       socket->priv->family = G_SOCKET_FAMILY_INVALID;
377       break;
378     }
379
380   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
381     {
382       addrlen = sizeof address;
383       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
384         socket->priv->connected = TRUE;
385     }
386
387   optlen = sizeof bool_val;
388   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
389                   (void *)&bool_val, &optlen) == 0)
390     {
391       g_assert (optlen == sizeof bool_val);
392       socket->priv->keepalive = !!bool_val;
393     }
394   else
395     {
396       /* Can't read, maybe not supported, assume FALSE */
397       socket->priv->keepalive = FALSE;
398     }
399
400   return;
401
402  err:
403   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
404                socket_io_error_from_errno (errsv),
405                _("creating GSocket from fd: %s"),
406                socket_strerror (errsv));
407 }
408
409 static gint
410 g_socket_create_socket (GSocketFamily   family,
411                         GSocketType     type,
412                         int             protocol,
413                         GError        **error)
414 {
415   gint native_type;
416   gint fd;
417
418   switch (type)
419     {
420      case G_SOCKET_TYPE_STREAM:
421       native_type = SOCK_STREAM;
422       break;
423
424      case G_SOCKET_TYPE_DATAGRAM:
425       native_type = SOCK_DGRAM;
426       break;
427
428      case G_SOCKET_TYPE_SEQPACKET:
429       native_type = SOCK_SEQPACKET;
430       break;
431
432      default:
433       g_assert_not_reached ();
434     }
435
436   if (protocol == -1)
437     {
438       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
439                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
440       return -1;
441     }
442
443 #ifdef SOCK_CLOEXEC
444   native_type |= SOCK_CLOEXEC;
445 #endif
446   fd = socket (family, native_type, protocol);
447
448   if (fd < 0)
449     {
450       int errsv = get_socket_errno ();
451
452       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
453                    _("Unable to create socket: %s"), socket_strerror (errsv));
454     }
455
456 #ifndef G_OS_WIN32
457   {
458     int flags;
459
460     /* We always want to set close-on-exec to protect users. If you
461        need to so some weird inheritance to exec you can re-enable this
462        using lower level hacks with g_socket_get_fd(). */
463     flags = fcntl (fd, F_GETFD, 0);
464     if (flags != -1 &&
465         (flags & FD_CLOEXEC) == 0)
466       {
467         flags |= FD_CLOEXEC;
468         fcntl (fd, F_SETFD, flags);
469       }
470   }
471 #endif
472
473   return fd;
474 }
475
476 static void
477 g_socket_constructed (GObject *object)
478 {
479   GSocket *socket = G_SOCKET (object);
480
481   if (socket->priv->fd >= 0)
482     /* create socket->priv info from the fd */
483     g_socket_details_from_fd (socket);
484
485   else
486     /* create the fd from socket->priv info */
487     socket->priv->fd = g_socket_create_socket (socket->priv->family,
488                                                socket->priv->type,
489                                                socket->priv->protocol,
490                                                &socket->priv->construct_error);
491
492   /* Always use native nonblocking sockets, as
493      windows sets sockets to nonblocking automatically
494      in certain operations. This way we make things work
495      the same on all platforms */
496   if (socket->priv->fd != -1)
497     set_fd_nonblocking (socket->priv->fd);
498 }
499
500 static void
501 g_socket_get_property (GObject    *object,
502                        guint       prop_id,
503                        GValue     *value,
504                        GParamSpec *pspec)
505 {
506   GSocket *socket = G_SOCKET (object);
507   GSocketAddress *address;
508
509   switch (prop_id)
510     {
511       case PROP_FAMILY:
512         g_value_set_enum (value, socket->priv->family);
513         break;
514
515       case PROP_TYPE:
516         g_value_set_enum (value, socket->priv->type);
517         break;
518
519       case PROP_PROTOCOL:
520         g_value_set_enum (value, socket->priv->protocol);
521         break;
522
523       case PROP_FD:
524         g_value_set_int (value, socket->priv->fd);
525         break;
526
527       case PROP_BLOCKING:
528         g_value_set_boolean (value, socket->priv->blocking);
529         break;
530
531       case PROP_LISTEN_BACKLOG:
532         g_value_set_int (value, socket->priv->listen_backlog);
533         break;
534
535       case PROP_KEEPALIVE:
536         g_value_set_boolean (value, socket->priv->keepalive);
537         break;
538
539       case PROP_LOCAL_ADDRESS:
540         address = g_socket_get_local_address (socket, NULL);
541         g_value_take_object (value, address);
542         break;
543
544       case PROP_REMOTE_ADDRESS:
545         address = g_socket_get_remote_address (socket, NULL);
546         g_value_take_object (value, address);
547         break;
548
549       default:
550         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
551     }
552 }
553
554 static void
555 g_socket_set_property (GObject      *object,
556                        guint         prop_id,
557                        const GValue *value,
558                        GParamSpec   *pspec)
559 {
560   GSocket *socket = G_SOCKET (object);
561
562   switch (prop_id)
563     {
564       case PROP_FAMILY:
565         socket->priv->family = g_value_get_enum (value);
566         break;
567
568       case PROP_TYPE:
569         socket->priv->type = g_value_get_enum (value);
570         break;
571
572       case PROP_PROTOCOL:
573         socket->priv->protocol = g_value_get_enum (value);
574         break;
575
576       case PROP_FD:
577         socket->priv->fd = g_value_get_int (value);
578         break;
579
580       case PROP_BLOCKING:
581         g_socket_set_blocking (socket, g_value_get_boolean (value));
582         break;
583
584       case PROP_LISTEN_BACKLOG:
585         g_socket_set_listen_backlog (socket, g_value_get_int (value));
586         break;
587
588       case PROP_KEEPALIVE:
589         g_socket_set_keepalive (socket, g_value_get_boolean (value));
590         break;
591
592       default:
593         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
594     }
595 }
596
597 static void
598 g_socket_finalize (GObject *object)
599 {
600   GSocket *socket = G_SOCKET (object);
601
602   g_clear_error (&socket->priv->construct_error);
603
604   if (socket->priv->fd != -1 &&
605       !socket->priv->closed)
606     g_socket_close (socket, NULL);
607
608 #ifdef G_OS_WIN32
609   g_assert (socket->priv->requested_conditions == NULL);
610 #endif
611
612   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
613     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
614 }
615
616 static void
617 g_socket_class_init (GSocketClass *klass)
618 {
619   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
620   volatile GType type;
621
622   /* Make sure winsock has been initialized */
623   type = g_inet_address_get_type ();
624
625 #ifdef SIGPIPE
626   /* There is no portable, thread-safe way to avoid having the process
627    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
628    * forced to simply ignore the signal process-wide.
629    */
630   signal (SIGPIPE, SIG_IGN);
631 #endif
632
633   g_type_class_add_private (klass, sizeof (GSocketPrivate));
634
635   gobject_class->finalize = g_socket_finalize;
636   gobject_class->constructed = g_socket_constructed;
637   gobject_class->set_property = g_socket_set_property;
638   gobject_class->get_property = g_socket_get_property;
639
640   g_object_class_install_property (gobject_class, PROP_FAMILY,
641                                    g_param_spec_enum ("family",
642                                                       P_("Socket family"),
643                                                       P_("The sockets address family"),
644                                                       G_TYPE_SOCKET_FAMILY,
645                                                       G_SOCKET_FAMILY_INVALID,
646                                                       G_PARAM_CONSTRUCT_ONLY |
647                                                       G_PARAM_READWRITE |
648                                                       G_PARAM_STATIC_STRINGS));
649
650   g_object_class_install_property (gobject_class, PROP_TYPE,
651                                    g_param_spec_enum ("type",
652                                                       P_("Socket type"),
653                                                       P_("The sockets type"),
654                                                       G_TYPE_SOCKET_TYPE,
655                                                       G_SOCKET_TYPE_STREAM,
656                                                       G_PARAM_CONSTRUCT_ONLY |
657                                                       G_PARAM_READWRITE |
658                                                       G_PARAM_STATIC_STRINGS));
659
660   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
661                                    g_param_spec_enum ("protocol",
662                                                       P_("Socket protocol"),
663                                                       P_("The id of the protocol to use, or -1 for unknown"),
664                                                       G_TYPE_SOCKET_PROTOCOL,
665                                                       G_SOCKET_PROTOCOL_UNKNOWN,
666                                                       G_PARAM_CONSTRUCT_ONLY |
667                                                       G_PARAM_READWRITE |
668                                                       G_PARAM_STATIC_STRINGS));
669
670   g_object_class_install_property (gobject_class, PROP_FD,
671                                    g_param_spec_int ("fd",
672                                                      P_("File descriptor"),
673                                                      P_("The sockets file descriptor"),
674                                                      G_MININT,
675                                                      G_MAXINT,
676                                                      -1,
677                                                      G_PARAM_CONSTRUCT_ONLY |
678                                                      G_PARAM_READWRITE |
679                                                      G_PARAM_STATIC_STRINGS));
680
681   g_object_class_install_property (gobject_class, PROP_BLOCKING,
682                                    g_param_spec_boolean ("blocking",
683                                                          P_("blocking"),
684                                                          P_("Whether or not I/O on this socket is blocking"),
685                                                          TRUE,
686                                                          G_PARAM_READWRITE |
687                                                          G_PARAM_STATIC_STRINGS));
688
689   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
690                                    g_param_spec_int ("listen-backlog",
691                                                      P_("Listen backlog"),
692                                                      P_("Outstanding connections in the listen queue"),
693                                                      0,
694                                                      SOMAXCONN,
695                                                      10,
696                                                      G_PARAM_READWRITE |
697                                                      G_PARAM_STATIC_STRINGS));
698
699   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
700                                    g_param_spec_boolean ("keepalive",
701                                                          P_("Keep connection alive"),
702                                                          P_("Keep connection alive by sending periodic pings"),
703                                                          FALSE,
704                                                          G_PARAM_READWRITE |
705                                                          G_PARAM_STATIC_STRINGS));
706
707   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
708                                    g_param_spec_object ("local-address",
709                                                         P_("Local address"),
710                                                         P_("The local address the socket is bound to"),
711                                                         G_TYPE_SOCKET_ADDRESS,
712                                                         G_PARAM_READABLE |
713                                                         G_PARAM_STATIC_STRINGS));
714
715   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
716                                    g_param_spec_object ("remote-address",
717                                                         P_("Remote address"),
718                                                         P_("The remote address the socket is connected to"),
719                                                         G_TYPE_SOCKET_ADDRESS,
720                                                         G_PARAM_READABLE |
721                                                         G_PARAM_STATIC_STRINGS));
722 }
723
724 static void
725 g_socket_initable_iface_init (GInitableIface *iface)
726 {
727   iface->init = g_socket_initable_init;
728 }
729
730 static void
731 g_socket_init (GSocket *socket)
732 {
733   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
734
735   socket->priv->fd = -1;
736   socket->priv->blocking = TRUE;
737   socket->priv->listen_backlog = 10;
738   socket->priv->construct_error = NULL;
739 #ifdef G_OS_WIN32
740   socket->priv->event = WSA_INVALID_EVENT;
741 #endif
742 }
743
744 static gboolean
745 g_socket_initable_init (GInitable *initable,
746                         GCancellable *cancellable,
747                         GError  **error)
748 {
749   GSocket  *socket;
750
751   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
752
753   socket = G_SOCKET (initable);
754
755   if (cancellable != NULL)
756     {
757       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
758                            _("Cancellable initialization not supported"));
759       return FALSE;
760     }
761
762   socket->priv->inited = TRUE;
763
764   if (socket->priv->construct_error)
765     {
766       if (error)
767         *error = g_error_copy (socket->priv->construct_error);
768       return FALSE;
769     }
770
771
772   return TRUE;
773 }
774
775 /**
776  * g_socket_new:
777  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
778  * @type: the socket type to use.
779  * @protocol: the id of the protocol to use, or 0 for default.
780  * @error: #GError for error reporting, or %NULL to ignore.
781  *
782  * Creates a new #GSocket with the defined family, type and protocol.
783  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
784  * for the family and type is used.
785  *
786  * The @protocol is a family and type specific int that specifies what
787  * kind of protocol to use. #GSocketProtocol lists several common ones.
788  * Many families only support one protocol, and use 0 for this, others
789  * support several and using 0 means to use the default protocol for
790  * the family and type.
791  *
792  * The protocol id is passed directly to the operating
793  * system, so you can use protocols not listed in #GSocketProtocol if you
794  * know the protocol number used for it.
795  *
796  * Returns: a #GSocket or %NULL on error.
797  *     Free the returned object with g_object_unref().
798  *
799  * Since: 2.22
800  */
801 GSocket *
802 g_socket_new (GSocketFamily     family,
803               GSocketType       type,
804               GSocketProtocol   protocol,
805               GError          **error)
806 {
807   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
808                                    NULL, error,
809                                    "family", family,
810                                    "type", type,
811                                    "protocol", protocol,
812                                    NULL));
813 }
814
815 /**
816  * g_socket_new_from_fd:
817  * @fd: a native socket file descriptor.
818  * @error: #GError for error reporting, or %NULL to ignore.
819  *
820  * Creates a new #GSocket from a native file descriptor
821  * or winsock SOCKET handle.
822  *
823  * This reads all the settings from the file descriptor so that
824  * all properties should work. Note that the file descriptor
825  * will be set to non-blocking mode, independent on the blocking
826  * mode of the #GSocket.
827  *
828  * Returns: a #GSocket or %NULL on error.
829  *     Free the returned object with g_object_unref().
830  *
831  * Since: 2.22
832  */
833 GSocket *
834 g_socket_new_from_fd (gint     fd,
835                       GError **error)
836 {
837   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
838                                    NULL, error,
839                                    "fd", fd,
840                                    NULL));
841 }
842
843 /**
844  * g_socket_set_blocking:
845  * @socket: a #GSocket.
846  * @blocking: Whether to use blocking I/O or not.
847  *
848  * Sets the blocking mode of the socket. In blocking mode
849  * all operations block until they succeed or there is an error. In
850  * non-blocking mode all functions return results immediately or
851  * with a %G_IO_ERROR_WOULD_BLOCK error.
852  *
853  * All sockets are created in blocking mode. However, note that the
854  * platform level socket is always non-blocking, and blocking mode
855  * is a GSocket level feature.
856  *
857  * Since: 2.22
858  */
859 void
860 g_socket_set_blocking (GSocket  *socket,
861                        gboolean  blocking)
862 {
863   g_return_if_fail (G_IS_SOCKET (socket));
864
865   blocking = !!blocking;
866
867   if (socket->priv->blocking == blocking)
868     return;
869
870   socket->priv->blocking = blocking;
871   g_object_notify (G_OBJECT (socket), "blocking");
872 }
873
874 /**
875  * g_socket_get_blocking:
876  * @socket: a #GSocket.
877  *
878  * Gets the blocking mode of the socket. For details on blocking I/O,
879  * see g_socket_set_blocking().
880  *
881  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
882  *
883  * Since: 2.22
884  */
885 gboolean
886 g_socket_get_blocking (GSocket *socket)
887 {
888   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
889
890   return socket->priv->blocking;
891 }
892
893 /**
894  * g_socket_set_keepalive:
895  * @socket: a #GSocket.
896  * @keepalive: Value for the keepalive flag
897  *
898  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
899  * this flag is set on a socket, the system will attempt to verify that the
900  * remote socket endpoint is still present if a sufficiently long period of
901  * time passes with no data being exchanged. If the system is unable to
902  * verify the presence of the remote endpoint, it will automatically close
903  * the connection.
904  *
905  * This option is only functional on certain kinds of sockets. (Notably,
906  * %G_SOCKET_PROTOCOL_TCP sockets.)
907  *
908  * The exact time between pings is system- and protocol-dependent, but will
909  * normally be at least two hours. Most commonly, you would set this flag
910  * on a server socket if you want to allow clients to remain idle for long
911  * periods of time, but also want to ensure that connections are eventually
912  * garbage-collected if clients crash or become unreachable.
913  *
914  * Since: 2.22
915  */
916 void
917 g_socket_set_keepalive (GSocket  *socket,
918                         gboolean  keepalive)
919 {
920   int value;
921
922   g_return_if_fail (G_IS_SOCKET (socket));
923
924   keepalive = !!keepalive;
925   if (socket->priv->keepalive == keepalive)
926     return;
927
928   value = (gint) keepalive;
929   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
930                   (gpointer) &value, sizeof (value)) < 0)
931     {
932       int errsv = get_socket_errno ();
933       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
934       return;
935     }
936
937   socket->priv->keepalive = keepalive;
938   g_object_notify (G_OBJECT (socket), "keepalive");
939 }
940
941 /**
942  * g_socket_get_keepalive:
943  * @socket: a #GSocket.
944  *
945  * Gets the keepalive mode of the socket. For details on this,
946  * see g_socket_set_keepalive().
947  *
948  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
949  *
950  * Since: 2.22
951  */
952 gboolean
953 g_socket_get_keepalive (GSocket *socket)
954 {
955   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
956
957   return socket->priv->keepalive;
958 }
959
960 /**
961  * g_socket_get_listen_backlog:
962  * @socket: a #GSocket.
963  *
964  * Gets the listen backlog setting of the socket. For details on this,
965  * see g_socket_set_listen_backlog().
966  *
967  * Returns: the maximum number of pending connections.
968  *
969  * Since: 2.22
970  */
971 gint
972 g_socket_get_listen_backlog  (GSocket *socket)
973 {
974   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
975
976   return socket->priv->listen_backlog;
977 }
978
979 /**
980  * g_socket_set_listen_backlog:
981  * @socket: a #GSocket.
982  * @backlog: the maximum number of pending connections.
983  *
984  * Sets the maximum number of outstanding connections allowed
985  * when listening on this socket. If more clients than this are
986  * connecting to the socket and the application is not handling them
987  * on time then the new connections will be refused.
988  *
989  * Note that this must be called before g_socket_listen() and has no
990  * effect if called after that.
991  *
992  * Since: 2.22
993  */
994 void
995 g_socket_set_listen_backlog (GSocket *socket,
996                              gint     backlog)
997 {
998   g_return_if_fail (G_IS_SOCKET (socket));
999   g_return_if_fail (!socket->priv->listening);
1000
1001   if (backlog != socket->priv->listen_backlog)
1002     {
1003       socket->priv->listen_backlog = backlog;
1004       g_object_notify (G_OBJECT (socket), "listen-backlog");
1005     }
1006 }
1007
1008 /**
1009  * g_socket_get_family:
1010  * @socket: a #GSocket.
1011  *
1012  * Gets the socket family of the socket.
1013  *
1014  * Returns: a #GSocketFamily
1015  *
1016  * Since: 2.22
1017  */
1018 GSocketFamily
1019 g_socket_get_family (GSocket *socket)
1020 {
1021   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1022
1023   return socket->priv->family;
1024 }
1025
1026 /**
1027  * g_socket_get_socket_type:
1028  * @socket: a #GSocket.
1029  *
1030  * Gets the socket type of the socket.
1031  *
1032  * Returns: a #GSocketType
1033  *
1034  * Since: 2.22
1035  */
1036 GSocketType
1037 g_socket_get_socket_type (GSocket *socket)
1038 {
1039   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1040
1041   return socket->priv->type;
1042 }
1043
1044 /**
1045  * g_socket_get_protocol:
1046  * @socket: a #GSocket.
1047  *
1048  * Gets the socket protocol id the socket was created with.
1049  * In case the protocol is unknown, -1 is returned.
1050  *
1051  * Returns: a protocol id, or -1 if unknown
1052  *
1053  * Since: 2.22
1054  */
1055 GSocketProtocol
1056 g_socket_get_protocol (GSocket *socket)
1057 {
1058   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1059
1060   return socket->priv->protocol;
1061 }
1062
1063 /**
1064  * g_socket_get_fd:
1065  * @socket: a #GSocket.
1066  *
1067  * Returns the underlying OS socket object. On unix this
1068  * is a socket file descriptor, and on windows this is
1069  * a Winsock2 SOCKET handle. This may be useful for
1070  * doing platform specific or otherwise unusual operations
1071  * on the socket.
1072  *
1073  * Returns: the file descriptor of the socket.
1074  *
1075  * Since: 2.22
1076  */
1077 int
1078 g_socket_get_fd (GSocket *socket)
1079 {
1080   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1081
1082   return socket->priv->fd;
1083 }
1084
1085 /**
1086  * g_socket_get_local_address:
1087  * @socket: a #GSocket.
1088  * @error: #GError for error reporting, or %NULL to ignore.
1089  *
1090  * Try to get the local address of a bound socket. This is only
1091  * useful if the socket has been bound to a local address,
1092  * either explicitly or implicitly when connecting.
1093  *
1094  * Returns: a #GSocketAddress or %NULL on error.
1095  *     Free the returned object with g_object_unref().
1096  *
1097  * Since: 2.22
1098  */
1099 GSocketAddress *
1100 g_socket_get_local_address (GSocket  *socket,
1101                             GError  **error)
1102 {
1103   struct sockaddr_storage buffer;
1104   guint32 len = sizeof (buffer);
1105
1106   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1107
1108   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1109     {
1110       int errsv = get_socket_errno ();
1111       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1112                    _("could not get local address: %s"), socket_strerror (errsv));
1113       return NULL;
1114     }
1115
1116   return g_socket_address_new_from_native (&buffer, len);
1117 }
1118
1119 /**
1120  * g_socket_get_remote_address:
1121  * @socket: a #GSocket.
1122  * @error: #GError for error reporting, or %NULL to ignore.
1123  *
1124  * Try to get the remove address of a connected socket. This is only
1125  * useful for connection oriented sockets that have been connected.
1126  *
1127  * Returns: a #GSocketAddress or %NULL on error.
1128  *     Free the returned object with g_object_unref().
1129  *
1130  * Since: 2.22
1131  */
1132 GSocketAddress *
1133 g_socket_get_remote_address (GSocket  *socket,
1134                              GError  **error)
1135 {
1136   struct sockaddr_storage buffer;
1137   guint32 len = sizeof (buffer);
1138
1139   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1140
1141   if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1142     {
1143       int errsv = get_socket_errno ();
1144       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1145                    _("could not get remote address: %s"), socket_strerror (errsv));
1146       return NULL;
1147     }
1148
1149   return g_socket_address_new_from_native (&buffer, len);
1150 }
1151
1152 /**
1153  * g_socket_is_connected:
1154  * @socket: a #GSocket.
1155  *
1156  * Check whether the socket is connected. This is only useful for
1157  * connection-oriented sockets.
1158  *
1159  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1160  *
1161  * Since: 2.22
1162  */
1163 gboolean
1164 g_socket_is_connected (GSocket *socket)
1165 {
1166   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1167
1168   return socket->priv->connected;
1169 }
1170
1171 /**
1172  * g_socket_listen:
1173  * @socket: a #GSocket.
1174  * @error: #GError for error reporting, or %NULL to ignore.
1175  *
1176  * Marks the socket as a server socket, i.e. a socket that is used
1177  * to accept incoming requests using g_socket_accept().
1178  *
1179  * Before calling this the socket must be bound to a local address using
1180  * g_socket_bind().
1181  *
1182  * To set the maximum amount of outstanding clients, use
1183  * g_socket_set_listen_backlog().
1184  *
1185  * Returns: %TRUE on success, %FALSE on error.
1186  *
1187  * Since: 2.22
1188  */
1189 gboolean
1190 g_socket_listen (GSocket  *socket,
1191                  GError  **error)
1192 {
1193   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1194
1195   if (!check_socket (socket, error))
1196     return FALSE;
1197
1198   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1199     {
1200       int errsv = get_socket_errno ();
1201
1202       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1203                    _("could not listen: %s"), socket_strerror (errsv));
1204       return FALSE;
1205     }
1206
1207   socket->priv->listening = TRUE;
1208
1209   return TRUE;
1210 }
1211
1212 /**
1213  * g_socket_bind:
1214  * @socket: a #GSocket.
1215  * @address: a #GSocketAddress specifying the local address.
1216  * @allow_reuse: whether to allow reusing this address
1217  * @error: #GError for error reporting, or %NULL to ignore.
1218  *
1219  * When a socket is created it is attached to an address family, but it
1220  * doesn't have an address in this family. g_socket_bind() assigns the
1221  * address (sometimes called name) of the socket.
1222  *
1223  * It is generally required to bind to a local address before you can
1224  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1225  * In certain situations, you may also want to bind a socket that will be
1226  * used to initiate connections, though this is not normally required.
1227  *
1228  * @allow_reuse should be %TRUE for server sockets (sockets that you will
1229  * eventually call g_socket_accept() on), and %FALSE for client sockets.
1230  * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1231  * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1232  * that address was previously used by another socket that has not yet been
1233  * fully cleaned-up by the kernel. Failing to set this flag on a server
1234  * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1235  * the server program is stopped and then immediately restarted.)
1236  *
1237  * Returns: %TRUE on success, %FALSE on error.
1238  *
1239  * Since: 2.22
1240  */
1241 gboolean
1242 g_socket_bind (GSocket         *socket,
1243                GSocketAddress  *address,
1244                gboolean         reuse_address,
1245                GError         **error)
1246 {
1247   struct sockaddr_storage addr;
1248
1249   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1250
1251   if (!check_socket (socket, error))
1252     return FALSE;
1253
1254   /* SO_REUSEADDR on windows means something else and is not what we want.
1255      It always allows the unix variant of SO_REUSEADDR anyway */
1256 #ifndef G_OS_WIN32
1257   {
1258     int value;
1259
1260     value = (int) !!reuse_address;
1261     /* Ignore errors here, the only likely error is "not supported", and
1262        this is a "best effort" thing mainly */
1263     setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1264                 (gpointer) &value, sizeof (value));
1265   }
1266 #endif
1267
1268   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1269     return FALSE;
1270
1271   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1272             g_socket_address_get_native_size (address)) < 0)
1273     {
1274       int errsv = get_socket_errno ();
1275       g_set_error (error,
1276                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1277                    _("Error binding to address: %s"), socket_strerror (errsv));
1278       return FALSE;
1279     }
1280
1281   return TRUE;
1282 }
1283
1284 /**
1285  * g_socket_speaks_ipv4:
1286  * @socket: a #GSocket
1287  *
1288  * Checks if a socket is capable of speaking IPv4.
1289  *
1290  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
1291  * and under some combinations of circumstances IPv6 sockets are also
1292  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
1293  * information.
1294  *
1295  * No other types of sockets are currently considered as being capable
1296  * of speaking IPv4.
1297  *
1298  * Returns: %TRUE if this socket can be used with IPv4.
1299  *
1300  * Since: 2.22
1301  **/
1302 gboolean
1303 g_socket_speaks_ipv4 (GSocket *socket)
1304 {
1305   switch (socket->priv->family)
1306     {
1307     case G_SOCKET_FAMILY_IPV4:
1308       return TRUE;
1309
1310     case G_SOCKET_FAMILY_IPV6:
1311 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1312       {
1313         guint sizeof_int = sizeof (int);
1314         gint v6_only;
1315
1316         if (getsockopt (socket->priv->fd,
1317                         IPPROTO_IPV6, IPV6_V6ONLY,
1318                         &v6_only, &sizeof_int) != 0)
1319           return FALSE;
1320
1321         return !v6_only;
1322       }
1323 #else
1324       return FALSE;
1325 #endif
1326
1327     default:
1328       return FALSE;
1329     }
1330 }
1331
1332 /**
1333  * g_socket_accept:
1334  * @socket: a #GSocket.
1335  * @cancellable: a %GCancellable or %NULL
1336  * @error: #GError for error reporting, or %NULL to ignore.
1337  *
1338  * Accept incoming connections on a connection-based socket. This removes
1339  * the first outstanding connection request from the listening socket and
1340  * creates a #GSocket object for it.
1341  *
1342  * The @socket must be bound to a local address with g_socket_bind() and
1343  * must be listening for incoming connections (g_socket_listen()).
1344  *
1345  * If there are no outstanding connections then the operation will block
1346  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1347  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1348  *
1349  * Returns: a new #GSocket, or %NULL on error.
1350  *     Free the returned object with g_object_unref().
1351  *
1352  * Since: 2.22
1353  */
1354 GSocket *
1355 g_socket_accept (GSocket       *socket,
1356                  GCancellable  *cancellable,
1357                  GError       **error)
1358 {
1359   GSocket *new_socket;
1360   gint ret;
1361
1362   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1363
1364   if (!check_socket (socket, error))
1365     return NULL;
1366
1367   while (TRUE)
1368     {
1369       if (socket->priv->blocking &&
1370           !g_socket_condition_wait (socket,
1371                                     G_IO_IN, cancellable, error))
1372         return NULL;
1373
1374       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1375         {
1376           int errsv = get_socket_errno ();
1377
1378           win32_unset_event_mask (socket, FD_ACCEPT);
1379
1380           if (errsv == EINTR)
1381             continue;
1382
1383           if (socket->priv->blocking)
1384             {
1385 #ifdef WSAEWOULDBLOCK
1386               if (errsv == WSAEWOULDBLOCK)
1387                 continue;
1388 #else
1389               if (errsv == EWOULDBLOCK ||
1390                   errsv == EAGAIN)
1391                 continue;
1392 #endif
1393             }
1394
1395           g_set_error (error, G_IO_ERROR,
1396                        socket_io_error_from_errno (errsv),
1397                        _("Error accepting connection: %s"), socket_strerror (errsv));
1398           return NULL;
1399         }
1400       break;
1401     }
1402
1403   win32_unset_event_mask (socket, FD_ACCEPT);
1404
1405 #ifdef G_OS_WIN32
1406   {
1407     /* The socket inherits the accepting sockets event mask and even object,
1408        we need to remove that */
1409     WSAEventSelect (ret, NULL, 0);
1410   }
1411 #else
1412   {
1413     int flags;
1414
1415     /* We always want to set close-on-exec to protect users. If you
1416        need to so some weird inheritance to exec you can re-enable this
1417        using lower level hacks with g_socket_get_fd(). */
1418     flags = fcntl (ret, F_GETFD, 0);
1419     if (flags != -1 &&
1420         (flags & FD_CLOEXEC) == 0)
1421       {
1422         flags |= FD_CLOEXEC;
1423         fcntl (ret, F_SETFD, flags);
1424       }
1425   }
1426 #endif
1427
1428   new_socket = g_socket_new_from_fd (ret, error);
1429   if (new_socket == NULL)
1430     {
1431 #ifdef G_OS_WIN32
1432       closesocket (ret);
1433 #else
1434       close (ret);
1435 #endif
1436     }
1437   else
1438     new_socket->priv->protocol = socket->priv->protocol;
1439
1440   return new_socket;
1441 }
1442
1443 /**
1444  * g_socket_connect:
1445  * @socket: a #GSocket.
1446  * @address: a #GSocketAddress specifying the remote address.
1447  * @cancellable: a %GCancellable or %NULL
1448  * @error: #GError for error reporting, or %NULL to ignore.
1449  *
1450  * Connect the socket to the specified remote address.
1451  *
1452  * For connection oriented socket this generally means we attempt to make
1453  * a connection to the @address. For a connection-less socket it sets
1454  * the default address for g_socket_send() and discards all incoming datagrams
1455  * from other sources.
1456  *
1457  * Generally connection oriented sockets can only connect once, but
1458  * connection-less sockets can connect multiple times to change the
1459  * default address.
1460  *
1461  * If the connect call needs to do network I/O it will block, unless
1462  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1463  * and the user can be notified of the connection finishing by waiting
1464  * for the G_IO_OUT condition. The result of the connection can then be
1465  * checked with g_socket_check_connect_result().
1466  *
1467  * Returns: %TRUE if connected, %FALSE on error.
1468  *
1469  * Since: 2.22
1470  */
1471 gboolean
1472 g_socket_connect (GSocket         *socket,
1473                   GSocketAddress  *address,
1474                   GCancellable    *cancellable,
1475                   GError         **error)
1476 {
1477   struct sockaddr_storage buffer;
1478
1479   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1480
1481   if (!check_socket (socket, error))
1482     return FALSE;
1483
1484   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1485     return FALSE;
1486
1487   while (1)
1488     {
1489       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1490                    g_socket_address_get_native_size (address)) < 0)
1491         {
1492           int errsv = get_socket_errno ();
1493
1494           if (errsv == EINTR)
1495             continue;
1496
1497 #ifndef G_OS_WIN32
1498           if (errsv == EINPROGRESS)
1499 #else
1500           if (errsv == WSAEWOULDBLOCK)
1501 #endif
1502             {
1503               if (socket->priv->blocking)
1504                 {
1505                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1506                     {
1507                       if (g_socket_check_connect_result (socket, error))
1508                         break;
1509                     }
1510                   g_prefix_error (error, _("Error connecting: "));
1511                 }
1512               else
1513                 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1514                                      _("Connection in progress"));
1515             }
1516           else
1517             g_set_error (error, G_IO_ERROR,
1518                          socket_io_error_from_errno (errsv),
1519                          _("Error connecting: %s"), socket_strerror (errsv));
1520
1521           return FALSE;
1522         }
1523       break;
1524     }
1525
1526   win32_unset_event_mask (socket, FD_CONNECT);
1527
1528   socket->priv->connected = TRUE;
1529
1530   return TRUE;
1531 }
1532
1533 /**
1534  * g_socket_check_connect_result:
1535  * @socket: a #GSocket
1536  * @error: #GError for error reporting, or %NULL to ignore.
1537  *
1538  * Checks and resets the pending connect error for the socket.
1539  * This is used to check for errors when g_socket_connect() is
1540  * used in non-blocking mode.
1541  *
1542  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1543  *
1544  * Since: 2.22
1545  */
1546 gboolean
1547 g_socket_check_connect_result (GSocket  *socket,
1548                                GError  **error)
1549 {
1550   guint optlen;
1551   int value;
1552
1553   optlen = sizeof (value);
1554   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1555     {
1556       int errsv = get_socket_errno ();
1557
1558       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1559                    _("Unable to get pending error: %s"), socket_strerror (errsv));
1560       return FALSE;
1561     }
1562
1563   if (value != 0)
1564     {
1565       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1566                            socket_strerror (value));
1567       return FALSE;
1568     }
1569   return TRUE;
1570 }
1571
1572 /**
1573  * g_socket_receive:
1574  * @socket: a #GSocket
1575  * @buffer: a buffer to read data into (which should be at least @size
1576  *     bytes long).
1577  * @size: the number of bytes you want to read from the socket
1578  * @cancellable: a %GCancellable or %NULL
1579  * @error: #GError for error reporting, or %NULL to ignore.
1580  *
1581  * Receive data (up to @size bytes) from a socket. This is mainly used by
1582  * connection-oriented sockets; it is identical to g_socket_receive_from()
1583  * with @address set to %NULL.
1584  *
1585  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1586  * g_socket_receive() will always read either 0 or 1 complete messages from
1587  * the socket. If the received message is too large to fit in @buffer, then
1588  * the data beyond @size bytes will be discarded, without any explicit
1589  * indication that this has occurred.
1590  *
1591  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1592  * number of bytes, up to @size. If more than @size bytes have been
1593  * received, the additional data will be returned in future calls to
1594  * g_socket_receive().
1595  *
1596  * If the socket is in blocking mode the call will block until there is
1597  * some data to receive or there is an error. If there is no data available
1598  * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1599  * will be returned. To be notified when data is available, wait for the
1600  * %G_IO_IN condition.
1601  *
1602  * On error -1 is returned and @error is set accordingly.
1603  *
1604  * Returns: Number of bytes read, or -1 on error
1605  *
1606  * Since: 2.22
1607  */
1608 gssize
1609 g_socket_receive (GSocket       *socket,
1610                   gchar         *buffer,
1611                   gsize          size,
1612                   GCancellable  *cancellable,
1613                   GError       **error)
1614 {
1615   gssize ret;
1616
1617   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1618
1619   if (!check_socket (socket, error))
1620     return -1;
1621
1622   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1623     return -1;
1624
1625   while (1)
1626     {
1627       if (socket->priv->blocking &&
1628           !g_socket_condition_wait (socket,
1629                                     G_IO_IN, cancellable, error))
1630         return -1;
1631
1632       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1633         {
1634           int errsv = get_socket_errno ();
1635
1636           if (errsv == EINTR)
1637             continue;
1638
1639           if (socket->priv->blocking)
1640             {
1641 #ifdef WSAEWOULDBLOCK
1642               if (errsv == WSAEWOULDBLOCK)
1643                 continue;
1644 #else
1645               if (errsv == EWOULDBLOCK ||
1646                   errsv == EAGAIN)
1647                 continue;
1648 #endif
1649             }
1650
1651           win32_unset_event_mask (socket, FD_READ);
1652
1653           g_set_error (error, G_IO_ERROR,
1654                        socket_io_error_from_errno (errsv),
1655                        _("Error receiving data: %s"), socket_strerror (errsv));
1656           return -1;
1657         }
1658
1659       win32_unset_event_mask (socket, FD_READ);
1660
1661       break;
1662     }
1663
1664   return ret;
1665 }
1666
1667 /**
1668  * g_socket_receive_from:
1669  * @socket: a #GSocket
1670  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1671  * @buffer: a buffer to read data into (which should be at least @size
1672  *     bytes long).
1673  * @size: the number of bytes you want to read from the socket
1674  * @cancellable: a %GCancellable or %NULL
1675  * @error: #GError for error reporting, or %NULL to ignore.
1676  *
1677  * Receive data (up to @size bytes) from a socket.
1678  *
1679  * If @address is non-%NULL then @address will be set equal to the
1680  * source address of the received packet.
1681  * @address is owned by the caller.
1682  *
1683  * See g_socket_receive() for additional information.
1684  *
1685  * Returns: Number of bytes read, or -1 on error
1686  *
1687  * Since: 2.22
1688  */
1689 gssize
1690 g_socket_receive_from (GSocket         *socket,
1691                        GSocketAddress **address,
1692                        gchar           *buffer,
1693                        gsize            size,
1694                        GCancellable    *cancellable,
1695                        GError         **error)
1696 {
1697   GInputVector v;
1698
1699   v.buffer = buffer;
1700   v.size = size;
1701
1702   return g_socket_receive_message (socket,
1703                                    address,
1704                                    &v, 1,
1705                                    NULL, 0, NULL,
1706                                    cancellable,
1707                                    error);
1708 }
1709
1710 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1711  * one, which can be confusing and annoying. So if possible, we want
1712  * to suppress the signal entirely.
1713  */
1714 #ifdef MSG_NOSIGNAL
1715 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1716 #else
1717 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1718 #endif
1719
1720 /**
1721  * g_socket_send:
1722  * @socket: a #GSocket
1723  * @buffer: the buffer containing the data to send.
1724  * @size: the number of bytes to send
1725  * @cancellable: a %GCancellable or %NULL
1726  * @error: #GError for error reporting, or %NULL to ignore.
1727  *
1728  * Tries to send @size bytes from @buffer on the socket. This is
1729  * mainly used by connection-oriented sockets; it is identical to
1730  * g_socket_send_to() with @address set to %NULL.
1731  *
1732  * If the socket is in blocking mode the call will block until there is
1733  * space for the data in the socket queue. If there is no space available
1734  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1735  * will be returned. To be notified when space is available, wait for the
1736  * %G_IO_OUT condition. Note though that you may still receive
1737  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1738  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1739  * very common due to the way the underlying APIs work.)
1740  *
1741  * On error -1 is returned and @error is set accordingly.
1742  *
1743  * Returns: Number of bytes written (which may be less than @size), or -1
1744  * on error
1745  *
1746  * Since: 2.22
1747  */
1748 gssize
1749 g_socket_send (GSocket       *socket,
1750                const gchar   *buffer,
1751                gsize          size,
1752                GCancellable  *cancellable,
1753                GError       **error)
1754 {
1755   gssize ret;
1756
1757   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1758
1759   if (!check_socket (socket, error))
1760     return -1;
1761
1762   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1763     return -1;
1764
1765   while (1)
1766     {
1767       if (socket->priv->blocking &&
1768           !g_socket_condition_wait (socket,
1769                                     G_IO_OUT, cancellable, error))
1770         return -1;
1771
1772       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1773         {
1774           int errsv = get_socket_errno ();
1775
1776           if (errsv == EINTR)
1777             continue;
1778
1779 #ifdef WSAEWOULDBLOCK
1780           if (errsv == WSAEWOULDBLOCK)
1781             win32_unset_event_mask (socket, FD_WRITE);
1782 #endif
1783
1784           if (socket->priv->blocking)
1785             {
1786 #ifdef WSAEWOULDBLOCK
1787               if (errsv == WSAEWOULDBLOCK)
1788                 continue;
1789 #else
1790               if (errsv == EWOULDBLOCK ||
1791                   errsv == EAGAIN)
1792                 continue;
1793 #endif
1794             }
1795
1796           g_set_error (error, G_IO_ERROR,
1797                        socket_io_error_from_errno (errsv),
1798                        _("Error sending data: %s"), socket_strerror (errsv));
1799           return -1;
1800         }
1801       break;
1802     }
1803
1804   return ret;
1805 }
1806
1807 /**
1808  * g_socket_send_to:
1809  * @socket: a #GSocket
1810  * @address: a #GSocketAddress, or %NULL
1811  * @buffer: the buffer containing the data to send.
1812  * @size: the number of bytes to send
1813  * @cancellable: a %GCancellable or %NULL
1814  * @error: #GError for error reporting, or %NULL to ignore.
1815  *
1816  * Tries to send @size bytes from @buffer to @address. If @address is
1817  * %NULL then the message is sent to the default receiver (set by
1818  * g_socket_connect()).
1819  *
1820  * See g_socket_send() for additional information.
1821  *
1822  * Returns: Number of bytes written (which may be less than @size), or -1
1823  * on error
1824  *
1825  * Since: 2.22
1826  */
1827 gssize
1828 g_socket_send_to (GSocket         *socket,
1829                   GSocketAddress  *address,
1830                   const gchar     *buffer,
1831                   gsize            size,
1832                   GCancellable    *cancellable,
1833                   GError         **error)
1834 {
1835   GOutputVector v;
1836
1837   v.buffer = buffer;
1838   v.size = size;
1839
1840   return g_socket_send_message (socket,
1841                                 address,
1842                                 &v, 1,
1843                                 NULL, 0,
1844                                 0,
1845                                 cancellable,
1846                                 error);
1847 }
1848
1849 /**
1850  * g_socket_shutdown:
1851  * @socket: a #GSocket
1852  * @shutdown_read: whether to shut down the read side
1853  * @shutdown_write: whether to shut down the write side
1854  * @error: #GError for error reporting, or %NULL to ignore.
1855  *
1856  * Shut down part of a full-duplex connection.
1857  *
1858  * If @shutdown_read is %TRUE then the recieving side of the connection
1859  * is shut down, and further reading is disallowed.
1860  *
1861  * If @shutdown_write is %TRUE then the sending side of the connection
1862  * is shut down, and further writing is disallowed.
1863  *
1864  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1865  *
1866  * One example where this is used is graceful disconnect for TCP connections
1867  * where you close the sending side, then wait for the other side to close
1868  * the connection, thus ensuring that the other side saw all sent data.
1869  *
1870  * Returns: %TRUE on success, %FALSE on error
1871  *
1872  * Since: 2.22
1873  */
1874 gboolean
1875 g_socket_shutdown (GSocket   *socket,
1876                    gboolean   shutdown_read,
1877                    gboolean   shutdown_write,
1878                    GError   **error)
1879 {
1880   int how;
1881
1882   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1883
1884   if (!check_socket (socket, NULL))
1885     return FALSE;
1886
1887   /* Do nothing? */
1888   if (!shutdown_read && !shutdown_write)
1889     return TRUE;
1890
1891 #ifndef G_OS_WIN32
1892   if (shutdown_read && shutdown_write)
1893     how = SHUT_RDWR;
1894   else if (shutdown_read)
1895     how = SHUT_RD;
1896   else
1897     how = SHUT_WR;
1898 #else
1899   if (shutdown_read && shutdown_write)
1900     how = SD_BOTH;
1901   else if (shutdown_read)
1902     how = SD_RECEIVE;
1903   else
1904     how = SD_SEND;
1905 #endif
1906
1907   if (shutdown (socket->priv->fd, how) != 0)
1908     {
1909       int errsv = get_socket_errno ();
1910       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1911                    _("Unable to create socket: %s"), socket_strerror (errsv));
1912       return FALSE;
1913     }
1914
1915   if (shutdown_read && shutdown_write)
1916     socket->priv->connected = FALSE;
1917
1918   return TRUE;
1919 }
1920
1921 /**
1922  * g_socket_close:
1923  * @socket: a #GSocket
1924  * @error: #GError for error reporting, or %NULL to ignore.
1925  *
1926  * Closes the socket, shutting down any active connection.
1927  *
1928  * Closing a socket does not wait for all outstanding I/O operations
1929  * to finish, so the caller should not rely on them to be guaranteed
1930  * to complete even if the close returns with no error.
1931  *
1932  * Once the socket is closed, all other operations will return
1933  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
1934  * return an error.
1935  *
1936  * Sockets will be automatically closed when the last reference
1937  * is dropped, but you might want to call this function to make sure
1938  * resources are released as early as possible.
1939  *
1940  * Beware that due to the way that TCP works, it is possible for
1941  * recently-sent data to be lost if either you close a socket while the
1942  * %G_IO_IN condition is set, or else if the remote connection tries to
1943  * send something to you after you close the socket but before it has
1944  * finished reading all of the data you sent. There is no easy generic
1945  * way to avoid this problem; the easiest fix is to design the network
1946  * protocol such that the client will never send data "out of turn".
1947  * Another solution is for the server to half-close the connection by
1948  * calling g_socket_shutdown() with only the @shutdown_write flag set,
1949  * and then wait for the client to notice this and close its side of the
1950  * connection, after which the server can safely call g_socket_close().
1951  * (This is what #GTcpConnection does if you call
1952  * g_tcp_connection_set_graceful_disconnect(). But of course, this
1953  * only works if the client will close its connection after the server
1954  * does.)
1955  *
1956  * Returns: %TRUE on success, %FALSE on error
1957  *
1958  * Since: 2.22
1959  */
1960 gboolean
1961 g_socket_close (GSocket  *socket,
1962                 GError  **error)
1963 {
1964   int res;
1965
1966   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1967
1968   if (socket->priv->closed)
1969     return TRUE; /* Multiple close not an error */
1970
1971   if (!check_socket (socket, NULL))
1972     return FALSE;
1973
1974   while (1)
1975     {
1976 #ifdef G_OS_WIN32
1977       res = closesocket (socket->priv->fd);
1978 #else
1979       res = close (socket->priv->fd);
1980 #endif
1981       if (res == -1)
1982         {
1983           int errsv = get_socket_errno ();
1984
1985           if (errsv == EINTR)
1986             continue;
1987
1988           g_set_error (error, G_IO_ERROR,
1989                        socket_io_error_from_errno (errsv),
1990                        _("Error closing socket: %s"),
1991                        socket_strerror (errsv));
1992           return FALSE;
1993         }
1994       break;
1995     }
1996
1997 #ifdef G_OS_WIN32
1998   if (socket->priv->event != WSA_INVALID_EVENT)
1999     {
2000       WSACloseEvent (socket->priv->event);
2001       socket->priv->event = WSA_INVALID_EVENT;
2002     }
2003 #endif
2004
2005   socket->priv->connected = FALSE;
2006   socket->priv->closed = TRUE;
2007
2008   return TRUE;
2009 }
2010
2011 /**
2012  * g_socket_is_closed:
2013  * @socket: a #GSocket
2014  *
2015  * Checks whether a socket is closed.
2016  *
2017  * Returns: %TRUE if socket is closed, %FALSE otherwise
2018  *
2019  * Since: 2.22
2020  */
2021 gboolean
2022 g_socket_is_closed (GSocket *socket)
2023 {
2024   return socket->priv->closed;
2025 }
2026
2027 #ifdef G_OS_WIN32
2028 /* Broken source, used on errors */
2029 static gboolean
2030 broken_prepare  (GSource *source,
2031                  gint    *timeout)
2032 {
2033   return FALSE;
2034 }
2035
2036 static gboolean
2037 broken_check (GSource *source)
2038 {
2039   return FALSE;
2040 }
2041
2042 static gboolean
2043 broken_dispatch (GSource     *source,
2044                  GSourceFunc  callback,
2045                  gpointer     user_data)
2046 {
2047   return TRUE;
2048 }
2049
2050 static GSourceFuncs broken_funcs =
2051 {
2052   broken_prepare,
2053   broken_check,
2054   broken_dispatch,
2055   NULL
2056 };
2057
2058 static gint
2059 network_events_for_condition (GIOCondition condition)
2060 {
2061   int event_mask = 0;
2062
2063   if (condition & G_IO_IN)
2064     event_mask |= (FD_READ | FD_ACCEPT);
2065   if (condition & G_IO_OUT)
2066     event_mask |= (FD_WRITE | FD_CONNECT);
2067   event_mask |= FD_CLOSE;
2068
2069   return event_mask;
2070 }
2071
2072 static void
2073 ensure_event (GSocket *socket)
2074 {
2075   if (socket->priv->event == WSA_INVALID_EVENT)
2076     socket->priv->event = WSACreateEvent();
2077 }
2078
2079 static void
2080 update_select_events (GSocket *socket)
2081 {
2082   int event_mask;
2083   GIOCondition *ptr;
2084   GList *l;
2085   WSAEVENT event;
2086
2087   ensure_event (socket);
2088
2089   event_mask = 0;
2090   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2091     {
2092       ptr = l->data;
2093       event_mask |= network_events_for_condition (*ptr);
2094     }
2095
2096   if (event_mask != socket->priv->selected_events)
2097     {
2098       /* If no events selected, disable event so we can unset
2099          nonblocking mode */
2100
2101       if (event_mask == 0)
2102         event = NULL;
2103       else
2104         event = socket->priv->event;
2105
2106       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2107         socket->priv->selected_events = event_mask;
2108     }
2109 }
2110
2111 static void
2112 add_condition_watch (GSocket      *socket,
2113                      GIOCondition *condition)
2114 {
2115   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2116
2117   socket->priv->requested_conditions =
2118     g_list_prepend (socket->priv->requested_conditions, condition);
2119
2120   update_select_events (socket);
2121 }
2122
2123 static void
2124 remove_condition_watch (GSocket      *socket,
2125                         GIOCondition *condition)
2126 {
2127   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2128
2129   socket->priv->requested_conditions =
2130     g_list_remove (socket->priv->requested_conditions, condition);
2131
2132   update_select_events (socket);
2133 }
2134
2135 static GIOCondition
2136 update_condition (GSocket *socket)
2137 {
2138   WSANETWORKEVENTS events;
2139   GIOCondition condition;
2140
2141   if (WSAEnumNetworkEvents (socket->priv->fd,
2142                             socket->priv->event,
2143                             &events) == 0)
2144     {
2145       socket->priv->current_events |= events.lNetworkEvents;
2146       if (events.lNetworkEvents & FD_WRITE &&
2147           events.iErrorCode[FD_WRITE_BIT] != 0)
2148         socket->priv->current_errors |= FD_WRITE;
2149       if (events.lNetworkEvents & FD_CONNECT &&
2150           events.iErrorCode[FD_CONNECT_BIT] != 0)
2151         socket->priv->current_errors |= FD_CONNECT;
2152     }
2153
2154   condition = 0;
2155   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2156     condition |= G_IO_IN;
2157
2158   if (socket->priv->current_events & FD_CLOSE ||
2159       socket->priv->closed)
2160     condition |= G_IO_HUP;
2161
2162   /* Never report both G_IO_OUT and HUP, these are
2163      mutually exclusive (can't write to a closed socket) */
2164   if ((condition & G_IO_HUP) == 0 &&
2165       socket->priv->current_events & FD_WRITE)
2166     {
2167       if (socket->priv->current_errors & FD_WRITE)
2168         condition |= G_IO_ERR;
2169       else
2170         condition |= G_IO_OUT;
2171     }
2172   else
2173     {
2174       if (socket->priv->current_events & FD_CONNECT)
2175         {
2176           if (socket->priv->current_errors & FD_CONNECT)
2177             condition |= (G_IO_HUP | G_IO_ERR);
2178           else
2179             condition |= G_IO_OUT;
2180         }
2181     }
2182
2183   return condition;
2184 }
2185
2186 typedef struct {
2187   GSource       source;
2188   GPollFD       pollfd;
2189   GSocket      *socket;
2190   GIOCondition  condition;
2191   GCancellable *cancellable;
2192   GPollFD       cancel_pollfd;
2193   GIOCondition  result_condition;
2194 } GWinsockSource;
2195
2196 static gboolean
2197 winsock_prepare (GSource *source,
2198                  gint    *timeout)
2199 {
2200   GWinsockSource *winsock_source = (GWinsockSource *)source;
2201   GIOCondition current_condition;
2202
2203   current_condition = update_condition (winsock_source->socket);
2204
2205   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2206     {
2207       winsock_source->result_condition = current_condition;
2208       return TRUE;
2209     }
2210
2211   if ((winsock_source->condition & current_condition) != 0)
2212     {
2213       winsock_source->result_condition = current_condition;
2214       return TRUE;
2215     }
2216
2217   return FALSE;
2218 }
2219
2220 static gboolean
2221 winsock_check (GSource *source)
2222 {
2223   GWinsockSource *winsock_source = (GWinsockSource *)source;
2224   GIOCondition current_condition;
2225
2226   current_condition = update_condition (winsock_source->socket);
2227
2228   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2229     {
2230       winsock_source->result_condition = current_condition;
2231       return TRUE;
2232     }
2233
2234   if ((winsock_source->condition & current_condition) != 0)
2235     {
2236       winsock_source->result_condition = current_condition;
2237       return TRUE;
2238     }
2239
2240   return FALSE;
2241 }
2242
2243 static gboolean
2244 winsock_dispatch (GSource     *source,
2245                   GSourceFunc  callback,
2246                   gpointer     user_data)
2247 {
2248   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2249   GWinsockSource *winsock_source = (GWinsockSource *)source;
2250
2251   return (*func) (winsock_source->socket,
2252                   winsock_source->result_condition & winsock_source->condition,
2253                   user_data);
2254 }
2255
2256 static void
2257 winsock_finalize (GSource *source)
2258 {
2259   GWinsockSource *winsock_source = (GWinsockSource *)source;
2260   GSocket *socket;
2261
2262   socket = winsock_source->socket;
2263
2264   remove_condition_watch (socket, &winsock_source->condition);
2265   g_object_unref (socket);
2266
2267   if (winsock_source->cancellable)
2268     {
2269       g_cancellable_release_fd (winsock_source->cancellable);
2270       g_object_unref (winsock_source->cancellable);
2271     }
2272 }
2273
2274 static GSourceFuncs winsock_funcs =
2275 {
2276   winsock_prepare,
2277   winsock_check,
2278   winsock_dispatch,
2279   winsock_finalize
2280 };
2281
2282 static GSource *
2283 winsock_source_new (GSocket      *socket,
2284                     GIOCondition  condition,
2285                     GCancellable *cancellable)
2286 {
2287   GSource *source;
2288   GWinsockSource *winsock_source;
2289
2290   ensure_event (socket);
2291
2292   if (socket->priv->event == WSA_INVALID_EVENT)
2293     {
2294       g_warning ("Failed to create WSAEvent");
2295       return g_source_new (&broken_funcs, sizeof (GSource));
2296     }
2297
2298   condition |= G_IO_HUP | G_IO_ERR;
2299
2300   source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2301   winsock_source = (GWinsockSource *)source;
2302
2303   winsock_source->socket = g_object_ref (socket);
2304   winsock_source->condition = condition;
2305   add_condition_watch (socket, &winsock_source->condition);
2306
2307   if (g_cancellable_make_pollfd (cancellable,
2308                                  &winsock_source->cancel_pollfd))
2309     {
2310       winsock_source->cancellable = g_object_ref (cancellable);
2311       g_source_add_poll (source, &winsock_source->cancel_pollfd);
2312     }
2313
2314   winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2315   winsock_source->pollfd.events = condition;
2316   g_source_add_poll (source, &winsock_source->pollfd);
2317
2318   return source;
2319 }
2320 #endif
2321
2322 /**
2323  * g_socket_create_source:
2324  * @socket: a #GSocket
2325  * @condition: a #GIOCondition mask to monitor
2326  * @cancellable: a %GCancellable or %NULL
2327  *
2328  * Creates a %GSource that can be attached to a %GMainContext to monitor
2329  * for the availibility of the specified @condition on the socket.
2330  *
2331  * The callback on the source is of the #GSocketSourceFunc type.
2332  *
2333  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2334  * these conditions will always be reported output if they are true.
2335  *
2336  * @cancellable if not %NULL can be used to cancel the source, which will
2337  * cause the source to trigger, reporting the current condition (which
2338  * is likely 0 unless cancellation happened at the same time as a
2339  * condition change). You can check for this in the callback using
2340  * g_cancellable_is_cancelled().
2341  *
2342  * Returns: a newly allocated %GSource, free with g_source_unref().
2343  *
2344  * Since: 2.22
2345  */
2346 GSource *
2347 g_socket_create_source (GSocket      *socket,
2348                         GIOCondition  condition,
2349                         GCancellable *cancellable)
2350 {
2351   GSource *source;
2352   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2353
2354 #ifdef G_OS_WIN32
2355   source = winsock_source_new (socket, condition, cancellable);
2356 #else
2357   source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2358                                         condition, cancellable);
2359 #endif
2360   return source;
2361 }
2362
2363 /**
2364  * g_socket_condition_check:
2365  * @socket: a #GSocket
2366  * @condition: a #GIOCondition mask to check
2367  *
2368  * Checks on the readiness of @socket to perform operations.
2369  * The operations specified in @condition are checked for and masked
2370  * against the currently-satisfied conditions on @socket. The result
2371  * is returned.
2372  *
2373  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2374  * these conditions will always be set in the output if they are true.
2375  *
2376  * This call never blocks.
2377  *
2378  * Returns: the @GIOCondition mask of the current state
2379  *
2380  * Since: 2.22
2381  */
2382 GIOCondition
2383 g_socket_condition_check (GSocket      *socket,
2384                           GIOCondition  condition)
2385 {
2386   if (!check_socket (socket, NULL))
2387     return 0;
2388
2389 #ifdef G_OS_WIN32
2390   {
2391     GIOCondition current_condition;
2392
2393     condition |= G_IO_ERR | G_IO_HUP;
2394
2395     add_condition_watch (socket, &condition);
2396     current_condition = update_condition (socket);
2397     remove_condition_watch (socket, &condition);
2398     return condition & current_condition;
2399   }
2400 #else
2401   {
2402     GPollFD poll_fd;
2403     gint result;
2404     poll_fd.fd = socket->priv->fd;
2405     poll_fd.events = condition;
2406
2407     do
2408       result = g_poll (&poll_fd, 1, 0);
2409     while (result == -1 && get_socket_errno () == EINTR);
2410
2411     return poll_fd.revents;
2412   }
2413 #endif
2414 }
2415
2416 /**
2417  * g_socket_condition_wait:
2418  * @socket: a #GSocket
2419  * @condition: a #GIOCondition mask to wait for
2420  * @cancellable: a #GCancellable, or %NULL
2421  * @error: a #GError pointer, or %NULL
2422  *
2423  * Waits for @condition to become true on @socket. When the condition
2424  * is met, %TRUE is returned.
2425  *
2426  * If @cancellable is cancelled before the condition is met then %FALSE
2427  * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2428  *
2429  * Returns: %TRUE if the condition was met, %FALSE otherwise
2430  *
2431  * Since: 2.22
2432  */
2433 gboolean
2434 g_socket_condition_wait (GSocket       *socket,
2435                          GIOCondition   condition,
2436                          GCancellable  *cancellable,
2437                          GError       **error)
2438 {
2439   if (!check_socket (socket, error))
2440     return FALSE;
2441
2442   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2443     return FALSE;
2444
2445 #ifdef G_OS_WIN32
2446   {
2447     GIOCondition current_condition;
2448     WSAEVENT events[2];
2449     DWORD res;
2450     GPollFD cancel_fd;
2451     int num_events;
2452
2453     /* Always check these */
2454     condition |=  G_IO_ERR | G_IO_HUP;
2455
2456     add_condition_watch (socket, &condition);
2457
2458     num_events = 0;
2459     events[num_events++] = socket->priv->event;
2460
2461     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2462       events[num_events++] = (WSAEVENT)cancel_fd.fd;
2463
2464     current_condition = update_condition (socket);
2465     while ((condition & current_condition) == 0)
2466       {
2467         res = WSAWaitForMultipleEvents(num_events, events,
2468                                        FALSE, WSA_INFINITE, FALSE);
2469         if (res == WSA_WAIT_FAILED)
2470           {
2471             int errsv = get_socket_errno ();
2472
2473             g_set_error (error, G_IO_ERROR,
2474                          socket_io_error_from_errno (errsv),
2475                          _("Waiting for socket condition: %s"),
2476                          socket_strerror (errsv));
2477             break;
2478           }
2479
2480         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2481           break;
2482
2483         current_condition = update_condition (socket);
2484       }
2485     remove_condition_watch (socket, &condition);
2486     if (num_events > 1)
2487       g_cancellable_release_fd (cancellable);
2488
2489     return (condition & current_condition) != 0;
2490   }
2491 #else
2492   {
2493     GPollFD poll_fd[2];
2494     gint result;
2495     gint num;
2496
2497     poll_fd[0].fd = socket->priv->fd;
2498     poll_fd[0].events = condition;
2499     num = 1;
2500
2501     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2502       num++;
2503
2504     do
2505       result = g_poll (poll_fd, num, -1);
2506     while (result == -1 && get_socket_errno () == EINTR);
2507     
2508     if (num > 1)
2509       g_cancellable_release_fd (cancellable);
2510
2511     return cancellable == NULL ||
2512       !g_cancellable_set_error_if_cancelled (cancellable, error);
2513   }
2514   #endif
2515 }
2516
2517 /**
2518  * g_socket_send_message:
2519  * @socket: a #GSocket
2520  * @address: a #GSocketAddress, or %NULL
2521  * @vectors: an array of #GOutputVector structs
2522  * @num_vectors: the number of elements in @vectors, or -1
2523  * @messages: a pointer to an array of #GSocketControlMessages, or
2524  *   %NULL.
2525  * @num_messages: number of elements in @messages, or -1.
2526  * @flags: an int containing #GSocketMsgFlags flags
2527  * @cancellable: a %GCancellable or %NULL
2528  * @error: #GError for error reporting, or %NULL to ignore.
2529  *
2530  * Send data to @address on @socket.  This is the most complicated and
2531  * fully-featured version of this call. For easier use, see
2532  * g_socket_send() and g_socket_send_to().
2533  *
2534  * If @address is %NULL then the message is sent to the default receiver
2535  * (set by g_socket_connect()).
2536  *
2537  * @vectors must point to an array of #GOutputVector structs and
2538  * @num_vectors must be the length of this array. (If @num_vectors is -1,
2539  * then @vectors is assumed to be terminated by a #GOutputVector with a
2540  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2541  * that the sent data will be gathered from. Using multiple
2542  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2543  * data from multiple sources into a single buffer, and more
2544  * network-efficient than making multiple calls to g_socket_send().
2545  *
2546  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2547  * #GSocketControlMessage instances. These correspond to the control
2548  * messages to be sent on the socket.
2549  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2550  * array.
2551  *
2552  * @flags modify how the message is sent. The commonly available arguments
2553  * for this are available in the #GSocketMsgFlags enum, but the
2554  * values there are the same as the system values, and the flags
2555  * are passed in as-is, so you can pass in system-specific flags too.
2556  *
2557  * If the socket is in blocking mode the call will block until there is
2558  * space for the data in the socket queue. If there is no space available
2559  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2560  * will be returned. To be notified when space is available, wait for the
2561  * %G_IO_OUT condition. Note though that you may still receive
2562  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2563  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2564  * very common due to the way the underlying APIs work.)
2565  *
2566  * On error -1 is returned and @error is set accordingly.
2567  *
2568  * Returns: Number of bytes written (which may be less than @size), or -1
2569  * on error
2570  *
2571  * Since: 2.22
2572  */
2573 gssize
2574 g_socket_send_message (GSocket                *socket,
2575                        GSocketAddress         *address,
2576                        GOutputVector          *vectors,
2577                        gint                    num_vectors,
2578                        GSocketControlMessage **messages,
2579                        gint                    num_messages,
2580                        gint                    flags,
2581                        GCancellable           *cancellable,
2582                        GError                **error)
2583 {
2584   GOutputVector one_vector;
2585   char zero;
2586
2587   if (!check_socket (socket, error))
2588     return -1;
2589
2590   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2591     return -1;
2592
2593   if (num_vectors == -1)
2594     {
2595       for (num_vectors = 0;
2596            vectors[num_vectors].buffer != NULL;
2597            num_vectors++)
2598         ;
2599     }
2600
2601   if (num_messages == -1)
2602     {
2603       for (num_messages = 0;
2604            messages != NULL && messages[num_messages] != NULL;
2605            num_messages++)
2606         ;
2607     }
2608
2609   if (num_vectors == 0)
2610     {
2611       zero = '\0';
2612
2613       one_vector.buffer = &zero;
2614       one_vector.size = 1;
2615       num_vectors = 1;
2616       vectors = &one_vector;
2617     }
2618
2619 #ifndef G_OS_WIN32
2620   {
2621     struct msghdr msg;
2622     gssize result;
2623
2624     /* name */
2625     if (address)
2626       {
2627         msg.msg_namelen = g_socket_address_get_native_size (address);
2628         msg.msg_name = g_alloca (msg.msg_namelen);
2629         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2630           return -1;
2631       }
2632     else
2633       {
2634         msg.msg_name = NULL;
2635         msg.msg_namelen = 0;
2636       }
2637
2638     /* iov */
2639     {
2640       /* this entire expression will be evaluated at compile time */
2641       if (sizeof *msg.msg_iov == sizeof *vectors &&
2642           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2643           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2644           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2645           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2646           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2647           G_STRUCT_OFFSET (GOutputVector, size))
2648         /* ABI is compatible */
2649         {
2650           msg.msg_iov = (struct iovec *) vectors;
2651           msg.msg_iovlen = num_vectors;
2652         }
2653       else
2654         /* ABI is incompatible */
2655         {
2656           gint i;
2657
2658           msg.msg_iov = g_newa (struct iovec, num_vectors);
2659           for (i = 0; i < num_vectors; i++)
2660             {
2661               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2662               msg.msg_iov[i].iov_len = vectors[i].size;
2663             }
2664           msg.msg_iovlen = num_vectors;
2665         }
2666     }
2667
2668     /* control */
2669     {
2670       struct cmsghdr *cmsg;
2671       gint i;
2672
2673       msg.msg_controllen = 0;
2674       for (i = 0; i < num_messages; i++)
2675         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2676
2677       msg.msg_control = g_alloca (msg.msg_controllen);
2678
2679       cmsg = CMSG_FIRSTHDR (&msg);
2680       for (i = 0; i < num_messages; i++)
2681         {
2682           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2683           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2684           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2685           g_socket_control_message_serialize (messages[i],
2686                                               CMSG_DATA (cmsg));
2687           cmsg = CMSG_NXTHDR (&msg, cmsg);
2688         }
2689       g_assert (cmsg == NULL);
2690     }
2691
2692     while (1)
2693       {
2694         if (socket->priv->blocking &&
2695             !g_socket_condition_wait (socket,
2696                                       G_IO_OUT, cancellable, error))
2697           return -1;
2698
2699         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2700         if (result < 0)
2701           {
2702             int errsv = get_socket_errno ();
2703
2704             if (errsv == EINTR)
2705               continue;
2706
2707             if (socket->priv->blocking &&
2708                 (errsv == EWOULDBLOCK ||
2709                  errsv == EAGAIN))
2710               continue;
2711
2712             g_set_error (error, G_IO_ERROR,
2713                          socket_io_error_from_errno (errsv),
2714                          _("Error sending message: %s"), socket_strerror (errsv));
2715
2716             return -1;
2717           }
2718         break;
2719       }
2720
2721     return result;
2722   }
2723 #else
2724   {
2725     struct sockaddr_storage addr;
2726     guint addrlen;
2727     DWORD bytes_sent;
2728     int result;
2729     WSABUF *bufs;
2730     gint i;
2731
2732     /* Win32 doesn't support control messages.
2733        Actually this is possible for raw and datagram sockets
2734        via WSASendMessage on Vista or later, but that doesn't
2735        seem very useful */
2736     if (num_messages != 0)
2737       {
2738         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2739                              _("GSocketControlMessage not supported on windows"));
2740         return -1;
2741       }
2742
2743     /* iov */
2744     bufs = g_newa (WSABUF, num_vectors);
2745     for (i = 0; i < num_vectors; i++)
2746       {
2747         bufs[i].buf = (char *)vectors[i].buffer;
2748         bufs[i].len = (gulong)vectors[i].size;
2749       }
2750
2751     /* name */
2752     addrlen = 0; /* Avoid warning */
2753     if (address)
2754       {
2755         addrlen = g_socket_address_get_native_size (address);
2756         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2757           return -1;
2758       }
2759
2760     while (1)
2761       {
2762         if (socket->priv->blocking &&
2763             !g_socket_condition_wait (socket,
2764                                       G_IO_OUT, cancellable, error))
2765           return -1;
2766
2767         if (address)
2768           result = WSASendTo (socket->priv->fd,
2769                               bufs, num_vectors,
2770                               &bytes_sent, flags,
2771                               (const struct sockaddr *)&addr, addrlen,
2772                               NULL, NULL);
2773         else
2774           result = WSASend (socket->priv->fd,
2775                             bufs, num_vectors,
2776                             &bytes_sent, flags,
2777                             NULL, NULL);
2778
2779         if (result != 0)
2780           {
2781             int errsv = get_socket_errno ();
2782
2783             if (errsv == WSAEINTR)
2784               continue;
2785
2786             if (errsv == WSAEWOULDBLOCK)
2787               win32_unset_event_mask (socket, FD_WRITE);
2788
2789             if (socket->priv->blocking &&
2790                 errsv == WSAEWOULDBLOCK)
2791               continue;
2792
2793             g_set_error (error, G_IO_ERROR,
2794                          socket_io_error_from_errno (errsv),
2795                          _("Error sending message: %s"), socket_strerror (errsv));
2796
2797             return -1;
2798           }
2799         break;
2800       }
2801
2802     return bytes_sent;
2803   }
2804 #endif
2805 }
2806
2807 /**
2808  * g_socket_receive_message:
2809  * @socket: a #GSocket
2810  * @address: a pointer to a #GSocketAddress pointer, or %NULL
2811  * @vectors: an array of #GInputVector structs
2812  * @num_vectors: the number of elements in @vectors, or -1
2813  * @messages: a pointer which will be filled with an array of
2814  *     #GSocketControlMessages, or %NULL
2815  * @num_messages: a pointer which will be filled with the number of
2816  *    elements in @messages, or %NULL
2817  * @flags: a pointer to an int containing #GSocketMsgFlags flags
2818  * @cancellable: a %GCancellable or %NULL
2819  * @error: a #GError pointer, or %NULL
2820  *
2821  * Receive data from a socket.  This is the most complicated and
2822  * fully-featured version of this call. For easier use, see
2823  * g_socket_receive() and g_socket_receive_from().
2824  *
2825  * If @address is non-%NULL then @address will be set equal to the
2826  * source address of the received packet.
2827  * @address is owned by the caller.
2828  *
2829  * @vector must point to an array of #GInputVector structs and
2830  * @num_vectors must be the length of this array.  These structs
2831  * describe the buffers that received data will be scattered into.
2832  * If @num_vectors is -1, then @vectors is assumed to be terminated
2833  * by a #GInputVector with a %NULL buffer pointer.
2834  *
2835  * As a special case, if @num_vectors is 0 (in which case, @vectors
2836  * may of course be %NULL), then a single byte is received and
2837  * discarded. This is to facilitate the common practice of sending a
2838  * single '\0' byte for the purposes of transferring ancillary data.
2839  *
2840  * @messages, if non-%NULL, will be set to point to a newly-allocated
2841  * array of #GSocketControlMessage instances. These correspond to the
2842  * control messages received from the kernel, one
2843  * #GSocketControlMessage per message from the kernel. This array is
2844  * %NULL-terminated and must be freed by the caller using g_free(). If
2845  * @messages is %NULL, any control messages received will be
2846  * discarded.
2847  *
2848  * @num_messages, if non-%NULL, will be set to the number of control
2849  * messages received.
2850  *
2851  * If both @messages and @num_messages are non-%NULL, then
2852  * @num_messages gives the number of #GSocketControlMessage instances
2853  * in @messages (ie: not including the %NULL terminator).
2854  *
2855  * @flags is an in/out parameter. The commonly available arguments
2856  * for this are available in the #GSocketMsgFlags enum, but the
2857  * values there are the same as the system values, and the flags
2858  * are passed in as-is, so you can pass in system-specific flags too
2859  * (and g_socket_receive_message() may pass system-specific flags out).
2860  *
2861  * As with g_socket_receive(), data may be discarded if @socket is
2862  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
2863  * provide enough buffer space to read a complete message. You can pass
2864  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
2865  * removing it from the receive queue, but there is no portable way to find
2866  * out the length of the message other than by reading it into a
2867  * sufficiently-large buffer.
2868  *
2869  * If the socket is in blocking mode the call will block until there
2870  * is some data to receive or there is an error. If there is no data
2871  * available and the socket is in non-blocking mode, a
2872  * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
2873  * data is available, wait for the %G_IO_IN condition.
2874  *
2875  * On error -1 is returned and @error is set accordingly.
2876  *
2877  * Returns: Number of bytes read, or -1 on error
2878  *
2879  * Since: 2.22
2880  */
2881 gssize
2882 g_socket_receive_message (GSocket                 *socket,
2883                           GSocketAddress         **address,
2884                           GInputVector            *vectors,
2885                           gint                     num_vectors,
2886                           GSocketControlMessage ***messages,
2887                           gint                    *num_messages,
2888                           gint                    *flags,
2889                           GCancellable            *cancellable,
2890                           GError                 **error)
2891 {
2892   GInputVector one_vector;
2893   char one_byte;
2894
2895   if (!check_socket (socket, error))
2896     return -1;
2897
2898   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2899     return -1;
2900
2901   if (num_vectors == -1)
2902     {
2903       for (num_vectors = 0;
2904            vectors[num_vectors].buffer != NULL;
2905            num_vectors++)
2906         ;
2907     }
2908
2909   if (num_vectors == 0)
2910     {
2911       one_vector.buffer = &one_byte;
2912       one_vector.size = 1;
2913       num_vectors = 1;
2914       vectors = &one_vector;
2915     }
2916
2917 #ifndef G_OS_WIN32
2918   {
2919     struct msghdr msg;
2920     gssize result;
2921     struct sockaddr_storage one_sockaddr;
2922
2923     /* name */
2924     if (address)
2925       {
2926         msg.msg_name = &one_sockaddr;
2927         msg.msg_namelen = sizeof (struct sockaddr_storage);
2928       }
2929     else
2930       {
2931         msg.msg_name = NULL;
2932         msg.msg_namelen = 0;
2933       }
2934
2935     /* iov */
2936     /* this entire expression will be evaluated at compile time */
2937     if (sizeof *msg.msg_iov == sizeof *vectors &&
2938         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2939         G_STRUCT_OFFSET (struct iovec, iov_base) ==
2940         G_STRUCT_OFFSET (GInputVector, buffer) &&
2941         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2942         G_STRUCT_OFFSET (struct iovec, iov_len) ==
2943         G_STRUCT_OFFSET (GInputVector, size))
2944       /* ABI is compatible */
2945       {
2946         msg.msg_iov = (struct iovec *) vectors;
2947         msg.msg_iovlen = num_vectors;
2948       }
2949     else
2950       /* ABI is incompatible */
2951       {
2952         gint i;
2953
2954         msg.msg_iov = g_newa (struct iovec, num_vectors);
2955         for (i = 0; i < num_vectors; i++)
2956           {
2957             msg.msg_iov[i].iov_base = vectors[i].buffer;
2958             msg.msg_iov[i].iov_len = vectors[i].size;
2959           }
2960         msg.msg_iovlen = num_vectors;
2961       }
2962
2963     /* control */
2964     msg.msg_control = g_alloca (2048);
2965     msg.msg_controllen = 2048;
2966
2967     /* flags */
2968     if (flags != NULL)
2969       msg.msg_flags = *flags;
2970     else
2971       msg.msg_flags = 0;
2972
2973     /* do it */
2974     while (1)
2975       {
2976         if (socket->priv->blocking &&
2977             !g_socket_condition_wait (socket,
2978                                       G_IO_IN, cancellable, error))
2979           return -1;
2980
2981         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2982
2983         if (result < 0)
2984           {
2985             int errsv = get_socket_errno ();
2986
2987             if (errsv == EINTR)
2988               continue;
2989
2990             if (socket->priv->blocking &&
2991                 (errsv == EWOULDBLOCK ||
2992                  errsv == EAGAIN))
2993               continue;
2994
2995             g_set_error (error, G_IO_ERROR,
2996                          socket_io_error_from_errno (errsv),
2997                          _("Error receiving message: %s"), socket_strerror (errsv));
2998
2999             return -1;
3000           }
3001         break;
3002       }
3003
3004     /* decode address */
3005     if (address != NULL)
3006       {
3007         if (msg.msg_namelen > 0)
3008           *address = g_socket_address_new_from_native (msg.msg_name,
3009                                                        msg.msg_namelen);
3010         else
3011           *address = NULL;
3012       }
3013
3014     /* decode control messages */
3015     {
3016       GSocketControlMessage **my_messages = NULL;
3017       gint allocated = 0, index = 0;
3018       const gchar *scm_pointer;
3019       struct cmsghdr *cmsg;
3020       gsize scm_size;
3021
3022       scm_pointer = (const gchar *) msg.msg_control;
3023       scm_size = msg.msg_controllen;
3024
3025       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3026         {
3027           GSocketControlMessage *message;
3028
3029           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3030                                                           cmsg->cmsg_type,
3031                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3032                                                           CMSG_DATA (cmsg));
3033           if (message == NULL)
3034             /* We've already spewed about the problem in the
3035                deserialization code, so just continue */
3036             continue;
3037
3038           if (index == allocated)
3039             {
3040               /* estimated 99% case: exactly 1 control message */
3041               allocated = MAX (allocated * 2, 1);
3042               my_messages = g_new (GSocketControlMessage *, (allocated + 1));
3043             }
3044
3045           my_messages[index++] = message;
3046         }
3047
3048       if (num_messages)
3049         *num_messages = index;
3050
3051       if (messages)
3052         {
3053           my_messages[index++] = NULL;
3054           *messages = my_messages;
3055         }
3056       else
3057         {
3058           gint i;
3059
3060           /* free all those messages we just constructed.
3061            * we have to do it this way if the user ignores the
3062            * messages so that we will close any received fds.
3063            */
3064           for (i = 0; i < index; i++)
3065             g_object_unref (my_messages[i]);
3066           g_free (my_messages);
3067         }
3068     }
3069
3070     /* capture the flags */
3071     if (flags != NULL)
3072       *flags = msg.msg_flags;
3073
3074     return result;
3075   }
3076 #else
3077   {
3078     struct sockaddr_storage addr;
3079     int addrlen;
3080     DWORD bytes_received;
3081     DWORD win_flags;
3082     int result;
3083     WSABUF *bufs;
3084     gint i;
3085
3086     /* iov */
3087     bufs = g_newa (WSABUF, num_vectors);
3088     for (i = 0; i < num_vectors; i++)
3089       {
3090         bufs[i].buf = (char *)vectors[i].buffer;
3091         bufs[i].len = (gulong)vectors[i].size;
3092       }
3093
3094     /* flags */
3095     if (flags != NULL)
3096       win_flags = *flags;
3097     else
3098       win_flags = 0;
3099
3100     /* do it */
3101     while (1)
3102       {
3103         if (socket->priv->blocking &&
3104             !g_socket_condition_wait (socket,
3105                                       G_IO_IN, cancellable, error))
3106           return -1;
3107
3108         addrlen = sizeof addr;
3109         if (address)
3110           result = WSARecvFrom (socket->priv->fd,
3111                                 bufs, num_vectors,
3112                                 &bytes_received, &win_flags,
3113                                 (struct sockaddr *)&addr, &addrlen,
3114                                 NULL, NULL);
3115         else
3116           result = WSARecv (socket->priv->fd,
3117                             bufs, num_vectors,
3118                             &bytes_received, &win_flags,
3119                             NULL, NULL);
3120         if (result != 0)
3121           {
3122             int errsv = get_socket_errno ();
3123
3124             if (errsv == WSAEINTR)
3125               continue;
3126
3127             win32_unset_event_mask (socket, FD_READ);
3128
3129             if (socket->priv->blocking &&
3130                 errsv == WSAEWOULDBLOCK)
3131               continue;
3132
3133             g_set_error (error, G_IO_ERROR,
3134                          socket_io_error_from_errno (errsv),
3135                          _("Error receiving message: %s"), socket_strerror (errsv));
3136
3137             return -1;
3138           }
3139         win32_unset_event_mask (socket, FD_READ);
3140         break;
3141       }
3142
3143     /* decode address */
3144     if (address != NULL)
3145       {
3146         if (addrlen > 0)
3147           *address = g_socket_address_new_from_native (&addr, addrlen);
3148         else
3149           *address = NULL;
3150       }
3151
3152     /* capture the flags */
3153     if (flags != NULL)
3154       *flags = win_flags;
3155
3156     return bytes_received;
3157   }
3158 #endif
3159 }
3160
3161 #define __G_SOCKET_C__
3162 #include "gioaliasdef.c"