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