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