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