Misc networking build fixes
[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: Whether to use try to keep the connection alive or not.
893  *
894  * Setting @keepalive to %TRUE enables the sending of periodic ping requests
895  * on idle connections in order to keep the connection alive. This is only
896  * useful for connection oriented sockets. The exact period used between
897  * each ping is system and protocol dependent.
898  *
899  * Sending keepalive requests like this has a few disadvantages. For instance,
900  * it uses more network bandwidth, and it makes your application more sensitive
901  * to temporary outages in the network (i.e. if a cable is pulled your otherwise
902  * idle connection could be terminated, whereas otherwise it would survive unless
903  * actually used before the cable was reinserted). However, it is sometimes
904  * useful to ensure that connections are eventually terminated if e.g. the
905  * remote side is disconnected, so as to avoid leaking resources forever.
906  *
907  * Since: 2.22
908  */
909 void
910 g_socket_set_keepalive (GSocket  *socket,
911                         gboolean  keepalive)
912 {
913   int value;
914
915   g_return_if_fail (G_IS_SOCKET (socket));
916
917   keepalive = !!keepalive;
918   if (socket->priv->keepalive == keepalive)
919     return;
920
921   value = (gint) keepalive;
922   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
923                   (gpointer) &value, sizeof (value)) < 0)
924     {
925       int errsv = get_socket_errno ();
926       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
927       return;
928     }
929
930   socket->priv->keepalive = keepalive;
931   g_object_notify (G_OBJECT (socket), "keepalive");
932 }
933
934 /**
935  * g_socket_get_keepalive:
936  * @socket: a #GSocket.
937  *
938  * Gets the keepalive mode of the socket. For details on this,
939  * see g_socket_set_keepalive().
940  *
941  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
942  *
943  * Since: 2.22
944  */
945 gboolean
946 g_socket_get_keepalive (GSocket *socket)
947 {
948   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
949
950   return socket->priv->keepalive;
951 }
952
953 /**
954  * g_socket_get_listen_backlog:
955  * @socket: a #GSocket.
956  *
957  * Gets the listen backlog setting of the socket. For details on this,
958  * see g_socket_set_listen_backlog().
959  *
960  * Returns: the maximum number of pending connections.
961  *
962  * Since: 2.22
963  */
964 gint
965 g_socket_get_listen_backlog  (GSocket *socket)
966 {
967   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
968
969   return socket->priv->listen_backlog;
970 }
971
972 /**
973  * g_socket_set_listen_backlog:
974  * @socket: a #GSocket.
975  * @backlog: the maximum number of pending connections.
976  *
977  * Sets the maximum number of outstanding connections allowed
978  * when listening on this socket. If more clients than this are
979  * connecting to the socket and the application is not handling them
980  * on time then the new connections will be refused.
981  *
982  * Note that this must be called before g_socket_listen() and has no
983  * effect if called after that.
984  *
985  * Since: 2.22
986  */
987 void
988 g_socket_set_listen_backlog (GSocket *socket,
989                              gint     backlog)
990 {
991   g_return_if_fail (G_IS_SOCKET (socket));
992   g_return_if_fail (!socket->priv->listening);
993
994   if (backlog != socket->priv->listen_backlog)
995     {
996       socket->priv->listen_backlog = backlog;
997       g_object_notify (G_OBJECT (socket), "listen-backlog");
998     }
999 }
1000
1001 /**
1002  * g_socket_get_family:
1003  * @socket: a #GSocket.
1004  *
1005  * Gets the socket family of the socket.
1006  *
1007  * Returns: a #GSocketFamily
1008  *
1009  * Since: 2.22
1010  */
1011 GSocketFamily
1012 g_socket_get_family (GSocket *socket)
1013 {
1014   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1015
1016   return socket->priv->family;
1017 }
1018
1019 /**
1020  * g_socket_get_socket_type:
1021  * @socket: a #GSocket.
1022  *
1023  * Gets the socket type of the socket.
1024  *
1025  * Returns: a #GSocketType
1026  *
1027  * Since: 2.22
1028  */
1029 GSocketType
1030 g_socket_get_socket_type (GSocket *socket)
1031 {
1032   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1033
1034   return socket->priv->type;
1035 }
1036
1037 /**
1038  * g_socket_get_protocol:
1039  * @socket: a #GSocket.
1040  *
1041  * Gets the socket protocol id the socket was created with.
1042  * In case the protocol is unknown, -1 is returned.
1043  *
1044  * Returns: a protocol id, or -1 if unknown
1045  *
1046  * Since: 2.22
1047  */
1048 GSocketProtocol
1049 g_socket_get_protocol (GSocket *socket)
1050 {
1051   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1052
1053   return socket->priv->protocol;
1054 }
1055
1056 /**
1057  * g_socket_get_fd:
1058  * @socket: a #GSocket.
1059  *
1060  * Returns the underlying OS socket object. On unix this
1061  * is a socket file descriptor, and on windows this is
1062  * a Winsock2 SOCKET handle. This may be useful for
1063  * doing platform specific or otherwise unusual operations
1064  * on the socket.
1065  *
1066  * Returns: the file descriptor of the socket.
1067  *
1068  * Since: 2.22
1069  */
1070 int
1071 g_socket_get_fd (GSocket *socket)
1072 {
1073   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1074
1075   return socket->priv->fd;
1076 }
1077
1078 /**
1079  * g_socket_get_local_address:
1080  * @socket: a #GSocket.
1081  * @error: #GError for error reporting, or %NULL to ignore.
1082  *
1083  * Try to get the local address of a bound socket. This is only
1084  * useful if the socket has been bound to a local address,
1085  * either explicitly or implicitly when connecting.
1086  *
1087  * Returns: a #GSocketAddress or %NULL on error.
1088  *     Free the returned object with g_object_unref().
1089  *
1090  * Since: 2.22
1091  */
1092 GSocketAddress *
1093 g_socket_get_local_address (GSocket  *socket,
1094                             GError  **error)
1095 {
1096   struct sockaddr_storage buffer;
1097   guint32 len = sizeof (buffer);
1098
1099   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1100
1101   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1102     {
1103       int errsv = get_socket_errno ();
1104       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1105                    _("could not get local address: %s"), socket_strerror (errsv));
1106       return NULL;
1107     }
1108
1109   return g_socket_address_new_from_native (&buffer, len);
1110 }
1111
1112 /**
1113  * g_socket_get_remote_address:
1114  * @socket: a #GSocket.
1115  * @error: #GError for error reporting, or %NULL to ignore.
1116  *
1117  * Try to get the remove address of a connected socket. This is only
1118  * useful for connection oriented sockets that have been connected.
1119  *
1120  * Returns: a #GSocketAddress or %NULL on error.
1121  *     Free the returned object with g_object_unref().
1122  *
1123  * Since: 2.22
1124  */
1125 GSocketAddress *
1126 g_socket_get_remote_address (GSocket  *socket,
1127                              GError  **error)
1128 {
1129   struct sockaddr_storage buffer;
1130   guint32 len = sizeof (buffer);
1131
1132   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1133
1134   if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1135     {
1136       int errsv = get_socket_errno ();
1137       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1138                    _("could not get remote address: %s"), socket_strerror (errsv));
1139       return NULL;
1140     }
1141
1142   return g_socket_address_new_from_native (&buffer, len);
1143 }
1144
1145 /**
1146  * g_socket_is_connected:
1147  * @socket: a #GSocket.
1148  *
1149  * Check whether the socket is connected. This is only useful for
1150  * connection-oriented sockets.
1151  *
1152  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1153  *
1154  * Since: 2.22
1155  */
1156 gboolean
1157 g_socket_is_connected (GSocket *socket)
1158 {
1159   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1160
1161   return socket->priv->connected;
1162 }
1163
1164 /**
1165  * g_socket_listen:
1166  * @socket: a #GSocket.
1167  * @error: #GError for error reporting, or %NULL to ignore.
1168  *
1169  * Marks the socket as a server socket, i.e. a socket that is used
1170  * to accept incoming requests using g_socket_accept().
1171  *
1172  * Before calling this the socket must be bound to a local address using
1173  * g_socket_bind().
1174  *
1175  * To set the maximum amount of outstanding clients, use
1176  * g_socket_set_listen_backlog().
1177  *
1178  * Returns: %TRUE on success, %FALSE on error.
1179  *
1180  * Since: 2.22
1181  */
1182 gboolean
1183 g_socket_listen (GSocket  *socket,
1184                  GError  **error)
1185 {
1186   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1187
1188   if (!check_socket (socket, error))
1189     return FALSE;
1190
1191   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1192     {
1193       int errsv = get_socket_errno ();
1194
1195       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1196                    _("could not listen: %s"), socket_strerror (errsv));
1197       return FALSE;
1198     }
1199
1200   socket->priv->listening = TRUE;
1201
1202   return TRUE;
1203 }
1204
1205 /**
1206  * g_socket_bind:
1207  * @socket: a #GSocket.
1208  * @address: a #GSocketAddress specifying the local address.
1209  * @allow_reuse: whether to allow reusing this address
1210  * @error: #GError for error reporting, or %NULL to ignore.
1211  *
1212  * When a socket is created it is attached to an address family, but it
1213  * doesn't have an address in this family. g_socket_bind() assigns the
1214  * address (sometimes called name) of the socket.
1215  *
1216  * It is generally required to bind to a local address before you can
1217  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1218  *
1219  * If @allow_reuse is %TRUE this allows the bind call to succeed in some
1220  * situation where it would otherwise return a %G_IO_ERROR_ADDRESS_IN_USE
1221  * error. The main example is for a TCP server socket where there are
1222  * outstanding connections in the WAIT state, which are generally safe
1223  * to ignore. However, setting it to %TRUE doesn't mean the call will
1224  * succeed if there is a socket actively bound to the address.
1225  *
1226  * In general, pass %TRUE if the socket will be used to accept connections,
1227  * otherwise pass %FALSE.
1228  *
1229  * Returns: %TRUE on success, %FALSE on error.
1230  *
1231  * Since: 2.22
1232  */
1233 gboolean
1234 g_socket_bind (GSocket         *socket,
1235                GSocketAddress  *address,
1236                gboolean         reuse_address,
1237                GError         **error)
1238 {
1239   struct sockaddr_storage addr;
1240
1241   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1242
1243   if (!check_socket (socket, error))
1244     return FALSE;
1245
1246   /* SO_REUSEADDR on windows means something else and is not what we want.
1247      It always allows the unix variant of SO_REUSEADDR anyway */
1248 #ifndef G_OS_WIN32
1249   {
1250     int value;
1251
1252     value = (int) !!reuse_address;
1253     /* Ignore errors here, the only likely error is "not supported", and
1254        this is a "best effort" thing mainly */
1255     setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1256                 (gpointer) &value, sizeof (value));
1257   }
1258 #endif
1259
1260   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1261     return FALSE;
1262
1263   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1264             g_socket_address_get_native_size (address)) < 0)
1265     {
1266       int errsv = get_socket_errno ();
1267       g_set_error (error,
1268                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1269                    _("Error binding to address: %s"), socket_strerror (errsv));
1270       return FALSE;
1271     }
1272
1273   return TRUE;
1274 }
1275
1276 /**
1277  * g_socket_accept:
1278  * @socket: a #GSocket.
1279  * @error: #GError for error reporting, or %NULL to ignore.
1280  *
1281  * Accept incoming connections on a connection-based socket. This removes
1282  * the first outstanding connection request from the listening socket and
1283  * creates a #GSocket object for it.
1284  *
1285  * The @socket must be bound to a local address with g_socket_bind() and
1286  * must be listening for incoming connections (g_socket_listen()).
1287  *
1288  * If there are no outstanding connections then the operation will block
1289  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1290  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1291  *
1292  * Returns: a new #GSocket, or %NULL on error.
1293  *     Free the returned object with g_object_unref().
1294  *
1295  * Since: 2.22
1296  */
1297 GSocket *
1298 g_socket_accept (GSocket       *socket,
1299                  GError       **error)
1300 {
1301   GSocket *new_socket;
1302   gint ret;
1303
1304   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1305
1306   if (!check_socket (socket, error))
1307     return NULL;
1308
1309   while (TRUE)
1310     {
1311       if (socket->priv->blocking &&
1312           !g_socket_condition_wait (socket,
1313                                     G_IO_IN, NULL, error))
1314         return NULL;
1315
1316       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1317         {
1318           int errsv = get_socket_errno ();
1319
1320           win32_unset_event_mask (socket, FD_ACCEPT);
1321
1322           if (errsv == EINTR)
1323             continue;
1324
1325           if (socket->priv->blocking)
1326             {
1327 #ifdef WSAEWOULDBLOCK
1328               if (errsv == WSAEWOULDBLOCK)
1329                 continue;
1330 #else
1331               if (errsv == EWOULDBLOCK ||
1332                   errsv == EAGAIN)
1333                 continue;
1334 #endif
1335             }
1336
1337           g_set_error (error, G_IO_ERROR,
1338                        socket_io_error_from_errno (errsv),
1339                        _("Error accepting connection: %s"), socket_strerror (errsv));
1340           return NULL;
1341         }
1342       break;
1343     }
1344
1345   win32_unset_event_mask (socket, FD_ACCEPT);
1346
1347 #ifdef G_OS_WIN32
1348   {
1349     /* The socket inherits the accepting sockets event mask and even object,
1350        we need to remove that */
1351     WSAEventSelect (ret, NULL, 0);
1352   }
1353 #else
1354   {
1355     int flags;
1356
1357     /* We always want to set close-on-exec to protect users. If you
1358        need to so some weird inheritance to exec you can re-enable this
1359        using lower level hacks with g_socket_get_fd(). */
1360     flags = fcntl (ret, F_GETFD, 0);
1361     if (flags != -1 &&
1362         (flags & FD_CLOEXEC) == 0)
1363       {
1364         flags |= FD_CLOEXEC;
1365         fcntl (ret, F_SETFD, flags);
1366       }
1367   }
1368 #endif
1369
1370   new_socket = g_socket_new_from_fd (ret, error);
1371   if (new_socket == NULL)
1372     {
1373 #ifdef G_OS_WIN32
1374       closesocket (ret);
1375 #else
1376       close (ret);
1377 #endif
1378     }
1379   else
1380     new_socket->priv->protocol = socket->priv->protocol;
1381
1382   return new_socket;
1383 }
1384
1385 /**
1386  * g_socket_connect:
1387  * @socket: a #GSocket.
1388  * @address: a #GSocketAddress specifying the remote address.
1389  * @error: #GError for error reporting, or %NULL to ignore.
1390  *
1391  * Connect the socket to the specified remote address.
1392  *
1393  * For connection oriented socket this generally means we attempt to make
1394  * a connection to the @address. For a connection-less socket it sets
1395  * the default address for g_socket_send() and discards all incoming datagrams
1396  * from other sources.
1397  *
1398  * Generally connection oriented sockets can only connect once, but
1399  * connection-less sockets can connect multiple times to change the
1400  * default address.
1401  *
1402  * If the connect call needs to do network I/O it will block, unless
1403  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1404  * and the user can be notified of the connection finishing by waiting
1405  * for the G_IO_OUT condition. The result of the connection can then be
1406  * checked with g_socket_check_connect_result().
1407  *
1408  * Returns: %TRUE if connected, %FALSE on error.
1409  *
1410  * Since: 2.22
1411  */
1412 gboolean
1413 g_socket_connect (GSocket         *socket,
1414                   GSocketAddress  *address,
1415                   GError         **error)
1416 {
1417   struct sockaddr_storage buffer;
1418
1419   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1420
1421   if (!check_socket (socket, error))
1422     return FALSE;
1423
1424   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1425     return FALSE;
1426
1427   while (1)
1428     {
1429       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1430                    g_socket_address_get_native_size (address)) < 0)
1431         {
1432           int errsv = get_socket_errno ();
1433
1434           if (errsv == EINTR)
1435             continue;
1436
1437 #ifndef G_OS_WIN32
1438           if (errsv == EINPROGRESS)
1439 #else
1440           if (errsv == WSAEWOULDBLOCK)
1441 #endif
1442             {
1443               if (socket->priv->blocking)
1444                 {
1445                   g_socket_condition_wait (socket, G_IO_OUT, NULL, NULL);
1446                   if (g_socket_check_connect_result (socket, error))
1447                     break;
1448                   else
1449                     g_prefix_error (error, _("Error connecting: "));
1450                 }
1451               else
1452                 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1453                                      _("Connection in progress"));
1454             }
1455           else
1456             g_set_error (error, G_IO_ERROR,
1457                          socket_io_error_from_errno (errsv),
1458                          _("Error connecting: %s"), socket_strerror (errsv));
1459
1460           return FALSE;
1461         }
1462       break;
1463     }
1464
1465   win32_unset_event_mask (socket, FD_CONNECT);
1466
1467   socket->priv->connected = TRUE;
1468
1469   return TRUE;
1470 }
1471
1472 /**
1473  * g_socket_check_connect_result:
1474  * @socket: a #GSocket
1475  * @error: #GError for error reporting, or %NULL to ignore.
1476  *
1477  * Checks and resets the pending connect error for the socket.
1478  * This is used to check for errors when g_socket_connect() is
1479  * used in non-blocking mode.
1480  *
1481  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1482  *
1483  * Since: 2.22
1484  */
1485 gboolean
1486 g_socket_check_connect_result (GSocket  *socket,
1487                                GError  **error)
1488 {
1489   guint optlen;
1490   int value;
1491
1492   optlen = sizeof (value);
1493   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1494     {
1495       int errsv = get_socket_errno ();
1496
1497       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1498                    _("Unable to get pending error: %s"), socket_strerror (errsv));
1499       return FALSE;
1500     }
1501
1502   if (value != 0)
1503     {
1504       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1505                            socket_strerror (value));
1506       return FALSE;
1507     }
1508   return TRUE;
1509 }
1510
1511 /**
1512  * g_socket_receive:
1513  * @socket: a #GSocket
1514  * @buffer: a buffer to read data into (which should be at least @size
1515  *     bytes long).
1516  * @size: the number of bytes that will be read from the stream
1517  * @error: #GError for error reporting, or %NULL to ignore.
1518  *
1519  * Receive data (up to @size bytes) from a socket. This is mainly used by
1520  * connection oriented sockets, it is identical to g_socket_receive_from()
1521  * with @address set to %NULL.
1522  *
1523  * If a message is too long to fit in @buffer, excess bytes may be discarded
1524  * depending on the type of socket the message is received from.
1525  *
1526  * If the socket is in blocking mode the call will block until there is
1527  * some data to receive or there is an error. If there is no data available
1528  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1529  * will be returned. To be notified of available data, wait for the %G_IO_IN
1530  * condition.
1531  *
1532  * On error -1 is returned and @error is set accordingly.
1533  *
1534  * Returns: Number of bytes read, or -1 on error
1535  *
1536  * Since: 2.22
1537  */
1538 gssize
1539 g_socket_receive (GSocket  *socket,
1540                   gchar    *buffer,
1541                   gsize     size,
1542                   GError  **error)
1543 {
1544   gssize ret;
1545
1546   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1547
1548   if (!check_socket (socket, error))
1549     return -1;
1550
1551   while (1)
1552     {
1553       if (socket->priv->blocking &&
1554           !g_socket_condition_wait (socket,
1555                                     G_IO_IN, NULL, error))
1556         return -1;
1557
1558       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1559         {
1560           int errsv = get_socket_errno ();
1561
1562           if (errsv == EINTR)
1563             continue;
1564
1565           if (socket->priv->blocking)
1566             {
1567 #ifdef WSAEWOULDBLOCK
1568               if (errsv == WSAEWOULDBLOCK)
1569                 continue;
1570 #else
1571               if (errsv == EWOULDBLOCK ||
1572                   errsv == EAGAIN)
1573                 continue;
1574 #endif
1575             }
1576
1577           win32_unset_event_mask (socket, FD_READ);
1578
1579           g_set_error (error, G_IO_ERROR,
1580                        socket_io_error_from_errno (errsv),
1581                        _("Error receiving data: %s"), socket_strerror (errsv));
1582           return -1;
1583         }
1584
1585       win32_unset_event_mask (socket, FD_READ);
1586
1587       break;
1588     }
1589
1590   return ret;
1591 }
1592
1593 /**
1594  * g_socket_receive_from:
1595  * @socket: a #GSocket
1596  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1597  * @buffer: a buffer to read data into (which should be at least @size
1598  *     bytes long).
1599  * @size: the number of bytes that will be read from the stream
1600  * @error: #GError for error reporting, or %NULL to ignore.
1601  *
1602  * Receive data (up to @size bytes) from a socket.
1603  *
1604  * If @address is non-%NULL then @address will be set equal to the
1605  * source address of the received packet.
1606  * @address is owned by the caller.
1607  *
1608  * If the socket is in blocking mode the call will block until there is
1609  * some data to receive or there is an error. If there is no data available
1610  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1611  * will be returned. To be notified of available data, wait for the %G_IO_IN
1612  * condition.
1613  *
1614  * On error -1 is returned and @error is set accordingly.
1615  *
1616  * Returns: Number of bytes read, or -1 on error
1617  *
1618  * Since: 2.22
1619  */
1620 gssize
1621 g_socket_receive_from (GSocket         *socket,
1622                        GSocketAddress **address,
1623                        gchar           *buffer,
1624                        gsize            size,
1625                        GError         **error)
1626 {
1627   GInputVector v;
1628
1629   v.buffer = buffer;
1630   v.size = size;
1631
1632   return g_socket_receive_message (socket,
1633                                    address,
1634                                    &v, 1,
1635                                    NULL, 0, NULL,
1636                                    error);
1637 }
1638
1639 /**
1640  * g_socket_send:
1641  * @socket: a #GSocket
1642  * @buffer: the buffer containing the data to send.
1643  * @size: the number of bytes to send
1644  * @error: #GError for error reporting, or %NULL to ignore.
1645  *
1646  * Tries to send @size bytes from @buffer on the socket.
1647  * This is mainly used by connection oriented sockets, it is identical
1648  * to g_socket_send_to() with @address set to %NULL.
1649  *
1650  * If the socket is in blocking mode the call will block until there is
1651  * space for the data in the socket queue. If there is no space available
1652  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1653  * will be returned. To be notified of available space, wait for the
1654  * %G_IO_OUT condition.
1655  *
1656  * Note that on Windows you can't rely on a %G_IO_OUT condition
1657  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1658  * write notification works. However, robust apps should always be able to
1659  * handle this since it can easily appear in other cases too.
1660  *
1661  * On error -1 is returned and @error is set accordingly.
1662  *
1663  * Returns: Number of bytes read, or -1 on error
1664  *
1665  * Since: 2.22
1666  */
1667 gssize
1668 g_socket_send (GSocket      *socket,
1669                const gchar  *buffer,
1670                gsize         size,
1671                GError      **error)
1672 {
1673   gssize ret;
1674
1675   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1676
1677   if (!check_socket (socket, error))
1678     return -1;
1679
1680   while (1)
1681     {
1682       if (socket->priv->blocking &&
1683           !g_socket_condition_wait (socket,
1684                                     G_IO_OUT, NULL, error))
1685         return -1;
1686
1687       if ((ret = send (socket->priv->fd, buffer, size, 0)) < 0)
1688         {
1689           int errsv = get_socket_errno ();
1690
1691           if (errsv == EINTR)
1692             continue;
1693
1694 #ifdef WSAEWOULDBLOCK
1695           if (errsv == WSAEWOULDBLOCK)
1696             win32_unset_event_mask (socket, FD_WRITE);
1697 #endif
1698
1699           if (socket->priv->blocking)
1700             {
1701 #ifdef WSAEWOULDBLOCK
1702               if (errsv == WSAEWOULDBLOCK)
1703                 continue;
1704 #else
1705               if (errsv == EWOULDBLOCK ||
1706                   errsv == EAGAIN)
1707                 continue;
1708 #endif
1709             }
1710
1711           g_set_error (error, G_IO_ERROR,
1712                        socket_io_error_from_errno (errsv),
1713                        _("Error sending data: %s"), socket_strerror (errsv));
1714           return -1;
1715         }
1716       break;
1717     }
1718
1719   return ret;
1720 }
1721
1722 /**
1723  * g_socket_send_to:
1724  * @socket: a #GSocket
1725  * @address: a #GSocketAddress, or %NULL
1726  * @buffer: the buffer containing the data to send.
1727  * @size: the number of bytes to send
1728  * @error: #GError for error reporting, or %NULL to ignore.
1729  *
1730  * Tries to send @size bytes from @buffer to @address. If @address is
1731  * %NULL then the message is sent to the default receiver (set by
1732  * g_socket_connect()).
1733  *
1734  * If the socket is in blocking mode the call will block until there is
1735  * space for the data in the socket queue. If there is no space available
1736  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1737  * will be returned. To be notified of available space, wait for the %G_IO_OUT
1738  * condition.
1739  *
1740  * Note that on Windows you can't rely on a %G_IO_OUT condition
1741  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
1742  * write notification works. However, robust apps should always be able to
1743  * handle this since it can easily appear in other cases too.
1744  *
1745  * On error -1 is returned and @error is set accordingly.
1746  *
1747  * Returns: Number of bytes read, or -1 on error
1748  *
1749  * Since: 2.22
1750  */
1751 gssize
1752 g_socket_send_to (GSocket         *socket,
1753                   GSocketAddress  *address,
1754                   const gchar     *buffer,
1755                   gsize            size,
1756                   GError         **error)
1757 {
1758   GOutputVector v;
1759
1760   v.buffer = buffer;
1761   v.size = size;
1762
1763   return g_socket_send_message (socket,
1764                                 address,
1765                                 &v, 1,
1766                                 NULL, 0,
1767                                 0, error);
1768 }
1769
1770 /**
1771  * g_socket_shutdown:
1772  * @socket: a #GSocket
1773  * @shutdown_read: whether to shut down the read side
1774  * @shutdown_write: whether to shut down the write side
1775  * @error: #GError for error reporting, or %NULL to ignore.
1776  *
1777  * Shut down part of a full-duplex connection.
1778  *
1779  * If @shutdown_read is %TRUE then the recieving side of the connection
1780  * is shut down, and further reading is disallowed.
1781  *
1782  * If @shutdown_write is %TRUE then the sending side of the connection
1783  * is shut down, and further writing is disallowed.
1784  *
1785  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1786  *
1787  * One example where this is used is graceful disconnect for TCP connections
1788  * where you close the sending side, then wait for the other side to close
1789  * the connection, thus ensuring that the other side saw all sent data.
1790  *
1791  * Returns: %TRUE on success, %FALSE on error
1792  *
1793  * Since: 2.22
1794  */
1795 gboolean
1796 g_socket_shutdown (GSocket   *socket,
1797                    gboolean   shutdown_read,
1798                    gboolean   shutdown_write,
1799                    GError   **error)
1800 {
1801   int how;
1802
1803   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1804
1805   if (!check_socket (socket, NULL))
1806     return FALSE;
1807
1808   /* Do nothing? */
1809   if (!shutdown_read && !shutdown_write)
1810     return TRUE;
1811
1812 #ifndef G_OS_WIN32
1813   if (shutdown_read && shutdown_write)
1814     how = SHUT_RDWR;
1815   else if (shutdown_read)
1816     how = SHUT_RD;
1817   else
1818     how = SHUT_WR;
1819 #else
1820   if (shutdown_read && shutdown_write)
1821     how = SD_BOTH;
1822   else if (shutdown_read)
1823     how = SD_RECEIVE;
1824   else
1825     how = SD_SEND;
1826 #endif
1827
1828   if (shutdown (socket->priv->fd, how) != 0)
1829     {
1830       int errsv = get_socket_errno ();
1831       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1832                    _("Unable to create socket: %s"), socket_strerror (errsv));
1833       return FALSE;
1834     }
1835
1836   if (shutdown_read && shutdown_write)
1837     socket->priv->connected = FALSE;
1838
1839   return TRUE;
1840 }
1841
1842 /**
1843  * g_socket_close:
1844  * @socket: a #GSocket
1845  * @error: #GError for error reporting, or %NULL to ignore.
1846  *
1847  * Closes the socket, shutting down any active connection.
1848  *
1849  * Closing a socket does not wait for all outstanding I/O operations
1850  * to finish, so the caller should not rely on them to be guaranteed
1851  * to complete even if the close returns with no error.
1852  *
1853  * Once the socket is closed, all other operations will return
1854  * %G_IO_ERROR_CLOSED. Closing a stream multiple times will not
1855  * return an error.
1856  *
1857  * Sockets will be automatically closed when the last reference
1858  * is dropped, but you might want to call this function to make sure
1859  * resources are released as early as possible.
1860  *
1861  * Returns: %TRUE on success, %FALSE on error
1862  *
1863  * Since: 2.22
1864  */
1865 gboolean
1866 g_socket_close (GSocket  *socket,
1867                 GError  **error)
1868 {
1869   int res;
1870
1871   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1872
1873   if (socket->priv->closed)
1874     return TRUE; /* Multiple close not an error */
1875
1876   if (!check_socket (socket, NULL))
1877     return FALSE;
1878
1879   while (1)
1880     {
1881 #ifdef G_OS_WIN32
1882       res = closesocket (socket->priv->fd);
1883 #else
1884       res = close (socket->priv->fd);
1885 #endif
1886       if (res == -1)
1887         {
1888           int errsv = get_socket_errno ();
1889
1890           if (errsv == EINTR)
1891             continue;
1892
1893           g_set_error (error, G_IO_ERROR,
1894                        socket_io_error_from_errno (errsv),
1895                        _("Error closing socket: %s"),
1896                        socket_strerror (errsv));
1897           return FALSE;
1898         }
1899       break;
1900     }
1901
1902 #ifdef G_OS_WIN32
1903   if (socket->priv->event != WSA_INVALID_EVENT)
1904     {
1905       WSACloseEvent (socket->priv->event);
1906       socket->priv->event = WSA_INVALID_EVENT;
1907     }
1908 #endif
1909
1910   socket->priv->connected = FALSE;
1911   socket->priv->closed = TRUE;
1912
1913   return TRUE;
1914 }
1915
1916 /**
1917  * g_socket_is_closed:
1918  * @socket: a #GSocket
1919  *
1920  * Checks whether a socket is closed.
1921  *
1922  * Returns: %TRUE if socket is closed, %FALSE otherwise
1923  *
1924  * Since: 2.22
1925  */
1926 gboolean
1927 g_socket_is_closed (GSocket *socket)
1928 {
1929   return socket->priv->closed;
1930 }
1931
1932 #ifdef G_OS_WIN32
1933 /* Broken source, used on errors */
1934 static gboolean
1935 broken_prepare  (GSource *source,
1936                  gint    *timeout)
1937 {
1938   return FALSE;
1939 }
1940
1941 static gboolean
1942 broken_check (GSource *source)
1943 {
1944   return FALSE;
1945 }
1946
1947 static gboolean
1948 broken_dispatch (GSource     *source,
1949                  GSourceFunc  callback,
1950                  gpointer     user_data)
1951 {
1952   return TRUE;
1953 }
1954
1955 static GSourceFuncs broken_funcs =
1956 {
1957   broken_prepare,
1958   broken_check,
1959   broken_dispatch,
1960   NULL
1961 };
1962
1963 static gint
1964 network_events_for_condition (GIOCondition condition)
1965 {
1966   int event_mask = 0;
1967
1968   if (condition & G_IO_IN)
1969     event_mask |= (FD_READ | FD_ACCEPT);
1970   if (condition & G_IO_OUT)
1971     event_mask |= (FD_WRITE | FD_CONNECT);
1972   event_mask |= FD_CLOSE;
1973
1974   return event_mask;
1975 }
1976
1977 static void
1978 ensure_event (GSocket *socket)
1979 {
1980   if (socket->priv->event == WSA_INVALID_EVENT)
1981     socket->priv->event = WSACreateEvent();
1982 }
1983
1984 static void
1985 update_select_events (GSocket *socket)
1986 {
1987   int event_mask;
1988   GIOCondition *ptr;
1989   GList *l;
1990   WSAEVENT event;
1991
1992   ensure_event (socket);
1993
1994   event_mask = 0;
1995   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
1996     {
1997       ptr = l->data;
1998       event_mask |= network_events_for_condition (*ptr);
1999     }
2000
2001   if (event_mask != socket->priv->selected_events)
2002     {
2003       /* If no events selected, disable event so we can unset
2004          nonblocking mode */
2005
2006       if (event_mask == 0)
2007         event = NULL;
2008       else
2009         event = socket->priv->event;
2010
2011       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2012         socket->priv->selected_events = event_mask;
2013     }
2014 }
2015
2016 static void
2017 add_condition_watch (GSocket      *socket,
2018                      GIOCondition *condition)
2019 {
2020   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2021
2022   socket->priv->requested_conditions =
2023     g_list_prepend (socket->priv->requested_conditions, condition);
2024
2025   update_select_events (socket);
2026 }
2027
2028 static void
2029 remove_condition_watch (GSocket      *socket,
2030                         GIOCondition *condition)
2031 {
2032   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2033
2034   socket->priv->requested_conditions =
2035     g_list_remove (socket->priv->requested_conditions, condition);
2036
2037   update_select_events (socket);
2038 }
2039
2040 static GIOCondition
2041 update_condition (GSocket *socket)
2042 {
2043   WSANETWORKEVENTS events;
2044   GIOCondition condition;
2045
2046   if (WSAEnumNetworkEvents (socket->priv->fd,
2047                             socket->priv->event,
2048                             &events) == 0)
2049     {
2050       socket->priv->current_events |= events.lNetworkEvents;
2051       if (events.lNetworkEvents & FD_WRITE &&
2052           events.iErrorCode[FD_WRITE_BIT] != 0)
2053         socket->priv->current_errors |= FD_WRITE;
2054       if (events.lNetworkEvents & FD_CONNECT &&
2055           events.iErrorCode[FD_CONNECT_BIT] != 0)
2056         socket->priv->current_errors |= FD_CONNECT;
2057     }
2058
2059   condition = 0;
2060   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2061     condition |= G_IO_IN;
2062
2063   if (socket->priv->current_events & FD_CLOSE ||
2064       socket->priv->closed)
2065     condition |= G_IO_HUP;
2066
2067   /* Never report both G_IO_OUT and HUP, these are
2068      mutually exclusive (can't write to a closed socket) */
2069   if ((condition & G_IO_HUP) == 0 &&
2070       socket->priv->current_events & FD_WRITE)
2071     {
2072       if (socket->priv->current_errors & FD_WRITE)
2073         condition |= G_IO_ERR;
2074       else
2075         condition |= G_IO_OUT;
2076     }
2077   else
2078     {
2079       if (socket->priv->current_events & FD_CONNECT)
2080         {
2081           if (socket->priv->current_errors & FD_CONNECT)
2082             condition |= (G_IO_HUP | G_IO_ERR);
2083           else
2084             condition |= G_IO_OUT;
2085         }
2086     }
2087
2088   return condition;
2089 }
2090
2091 typedef struct {
2092   GSource       source;
2093   GPollFD       pollfd;
2094   GSocket      *socket;
2095   GIOCondition  condition;
2096   GCancellable *cancellable;
2097   GPollFD       cancel_pollfd;
2098   GIOCondition  result_condition;
2099 } GWinsockSource;
2100
2101 static gboolean
2102 winsock_prepare (GSource *source,
2103                  gint    *timeout)
2104 {
2105   GWinsockSource *winsock_source = (GWinsockSource *)source;
2106   GIOCondition current_condition;
2107
2108   current_condition = update_condition (winsock_source->socket);
2109
2110   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2111     {
2112       winsock_source->result_condition = current_condition;
2113       return TRUE;
2114     }
2115
2116   if ((winsock_source->condition & current_condition) != 0)
2117     {
2118       winsock_source->result_condition = current_condition;
2119       return TRUE;
2120     }
2121
2122   return FALSE;
2123 }
2124
2125 static gboolean
2126 winsock_check (GSource *source)
2127 {
2128   GWinsockSource *winsock_source = (GWinsockSource *)source;
2129   GIOCondition current_condition;
2130
2131   current_condition = update_condition (winsock_source->socket);
2132
2133   if (g_cancellable_is_cancelled (winsock_source->cancellable))
2134     {
2135       winsock_source->result_condition = current_condition;
2136       return TRUE;
2137     }
2138
2139   if ((winsock_source->condition & current_condition) != 0)
2140     {
2141       winsock_source->result_condition = current_condition;
2142       return TRUE;
2143     }
2144
2145   return FALSE;
2146 }
2147
2148 static gboolean
2149 winsock_dispatch (GSource     *source,
2150                   GSourceFunc  callback,
2151                   gpointer     user_data)
2152 {
2153   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2154   GWinsockSource *winsock_source = (GWinsockSource *)source;
2155
2156   return (*func) (winsock_source->socket,
2157                   winsock_source->result_condition & winsock_source->condition,
2158                   user_data);
2159 }
2160
2161 static void
2162 winsock_finalize (GSource *source)
2163 {
2164   GWinsockSource *winsock_source = (GWinsockSource *)source;
2165   GSocket *socket;
2166
2167   socket = winsock_source->socket;
2168
2169   remove_condition_watch (socket, &winsock_source->condition);
2170   g_object_unref (socket);
2171
2172   if (winsock_source->cancellable)
2173     g_object_unref (winsock_source->cancellable);
2174 }
2175
2176 static GSourceFuncs winsock_funcs =
2177 {
2178   winsock_prepare,
2179   winsock_check,
2180   winsock_dispatch,
2181   winsock_finalize
2182 };
2183
2184 static GSource *
2185 winsock_source_new (GSocket      *socket,
2186                     GIOCondition  condition,
2187                     GCancellable *cancellable)
2188 {
2189   GSource *source;
2190   GWinsockSource *winsock_source;
2191
2192   ensure_event (socket);
2193
2194   if (socket->priv->event == WSA_INVALID_EVENT)
2195     {
2196       g_warning ("Failed to create WSAEvent");
2197       return g_source_new (&broken_funcs, sizeof (GSource));
2198     }
2199
2200   condition |= G_IO_HUP | G_IO_ERR;
2201
2202   source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2203   winsock_source = (GWinsockSource *)source;
2204
2205   winsock_source->socket = g_object_ref (socket);
2206   winsock_source->condition = condition;
2207   add_condition_watch (socket, &winsock_source->condition);
2208
2209   if (cancellable)
2210     {
2211       winsock_source->cancellable = g_object_ref (cancellable);
2212       g_cancellable_make_pollfd (cancellable,
2213                                  &winsock_source->cancel_pollfd);
2214       g_source_add_poll (source, &winsock_source->cancel_pollfd);
2215     }
2216
2217   winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2218   winsock_source->pollfd.events = condition;
2219   g_source_add_poll (source, &winsock_source->pollfd);
2220
2221   return source;
2222 }
2223 #endif
2224
2225 /**
2226  * g_socket_create_source:
2227  * @socket: a #GSocket
2228  * @condition: a #GIOCondition mask to monitor
2229  * @cancellable: a %GCancellable or %NULL
2230  *
2231  * Creates a %GSource that can be attached to a %GMainContext to monitor
2232  * for the availibility of the specified @condition on the socket.
2233  *
2234  * The callback on the source is of the #GSocketSourceFunc type.
2235  *
2236  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2237  * these conditions will always be reported output if they are true.
2238  *
2239  * @cancellable if not %NULL can be used to cancel the source, which will
2240  * cause the source to trigger, reporting the current condition (which
2241  * is likely 0 unless cancellation happened at the same time as a
2242  * condition change). You can check for this in the callback using
2243  * g_cancellable_is_cancelled().
2244  *
2245  * Returns: a newly allocated %GSource, free with g_source_unref().
2246  *
2247  * Since: 2.22
2248  */
2249 GSource *
2250 g_socket_create_source (GSocket      *socket,
2251                         GIOCondition  condition,
2252                         GCancellable *cancellable)
2253 {
2254   GSource *source;
2255   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2256
2257 #ifdef G_OS_WIN32
2258   source = winsock_source_new (socket, condition, cancellable);
2259 #else
2260   source =_g_fd_source_new_with_object (G_OBJECT (socket), socket->priv->fd,
2261                                         condition, cancellable);
2262 #endif
2263   return source;
2264 }
2265
2266 /**
2267  * g_socket_condition_check:
2268  * @socket: a #GSocket
2269  * @condition: a #GIOCondition mask to check
2270  *
2271  * Checks on the readiness of @socket to perform operations.
2272  * The operations specified in @condition are checked for and masked
2273  * against the currently-satisfied conditions on @socket. The result
2274  * is returned.
2275  *
2276  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2277  * these conditions will always be set in the output if they are true.
2278  *
2279  * This call never blocks.
2280  *
2281  * Returns: the @GIOCondition mask of the current state
2282  *
2283  * Since: 2.22
2284  */
2285 GIOCondition
2286 g_socket_condition_check (GSocket      *socket,
2287                           GIOCondition  condition)
2288 {
2289   if (!check_socket (socket, NULL))
2290     return 0;
2291
2292 #ifdef G_OS_WIN32
2293   {
2294     GIOCondition current_condition;
2295
2296     condition |= G_IO_ERR | G_IO_HUP;
2297
2298     add_condition_watch (socket, &condition);
2299     current_condition = update_condition (socket);
2300     remove_condition_watch (socket, &condition);
2301     return condition & current_condition;
2302   }
2303 #else
2304   {
2305     GPollFD poll_fd;
2306     gint result;
2307     poll_fd.fd = socket->priv->fd;
2308     poll_fd.events = condition;
2309
2310     do
2311       result = g_poll (&poll_fd, 1, 0);
2312     while (result == -1 && get_socket_errno () == EINTR);
2313
2314     return poll_fd.revents;
2315   }
2316 #endif
2317 }
2318
2319 /**
2320  * g_socket_condition_wait:
2321  * @socket: a #GSocket
2322  * @condition: a #GIOCondition mask to wait for
2323  * @cancellable: a #GCancellable, or %NULL
2324  * @error: a #GError pointer, or %NULL
2325  *
2326  * Waits for @condition to become true on @socket. When the condition
2327  * is met, %TRUE is returned.
2328  *
2329  * If @cancellable is cancelled before the condition is met then %FALSE
2330  * is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2331  *
2332  * Returns: %TRUE if the condition was met, %FALSE otherwise
2333  *
2334  * Since: 2.22
2335  */
2336 gboolean
2337 g_socket_condition_wait (GSocket       *socket,
2338                          GIOCondition   condition,
2339                          GCancellable  *cancellable,
2340                          GError       **error)
2341 {
2342   if (!check_socket (socket, error))
2343     return FALSE;
2344
2345   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2346     return FALSE;
2347
2348 #ifdef G_OS_WIN32
2349   {
2350     GIOCondition current_condition;
2351     WSAEVENT events[2];
2352     DWORD res;
2353     GPollFD cancel_fd;
2354     int num_events;
2355
2356     /* Always check these */
2357     condition |=  G_IO_ERR | G_IO_HUP;
2358
2359     add_condition_watch (socket, &condition);
2360
2361     num_events = 0;
2362     events[num_events++] = socket->priv->event;
2363
2364     if (cancellable)
2365       {
2366         g_cancellable_make_pollfd (cancellable, &cancel_fd);
2367         events[num_events++] = (WSAEVENT)cancel_fd.fd;
2368       }
2369
2370     current_condition = update_condition (socket);
2371     while ((condition & current_condition) == 0)
2372       {
2373         res = WSAWaitForMultipleEvents(num_events, events,
2374                                        FALSE, WSA_INFINITE, FALSE);
2375         if (res == WSA_WAIT_FAILED)
2376           {
2377             int errsv = get_socket_errno ();
2378
2379             g_set_error (error, G_IO_ERROR,
2380                          socket_io_error_from_errno (errsv),
2381                          _("Waiting for socket condition: %s"),
2382                          socket_strerror (errsv));
2383             break;
2384           }
2385
2386         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2387           break;
2388
2389         current_condition = update_condition (socket);
2390       }
2391     remove_condition_watch (socket, &condition);
2392
2393     return (condition & current_condition) != 0;
2394   }
2395 #else
2396   {
2397     GPollFD poll_fd[2];
2398     gint result;
2399     gint num;
2400
2401     poll_fd[0].fd = socket->priv->fd;
2402     poll_fd[0].events = condition;
2403     num = 1;
2404
2405     if (cancellable)
2406       {
2407         g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2408         num++;
2409       }
2410
2411     do
2412       result = g_poll (poll_fd, num, -1);
2413     while (result == -1 && get_socket_errno () == EINTR);
2414
2415     return cancellable == NULL ||
2416       !g_cancellable_set_error_if_cancelled (cancellable, error);
2417   }
2418   #endif
2419 }
2420
2421 /**
2422  * g_socket_send_message:
2423  * @socket: a #GSocket
2424  * @address: a #GSocketAddress, or %NULL
2425  * @vectors: an array of #GOutputVector structs
2426  * @num_vectors: the number of elements in @vectors, or -1
2427  * @messages: a pointer to an array of #GSocketControlMessages, or
2428  *   %NULL.
2429  * @num_messages: number of elements in @messages, or -1.
2430  * @flags: an int containing #GSocketMsgFlags flags
2431  * @error: #GError for error reporting, or %NULL to ignore.
2432  *
2433  * Send data to @address on @socket.  This is the most complicated and
2434  * fully-featured version of this call. For easier use, see
2435  * g_socket_send() and g_socket_send_to().
2436  *
2437  * If @address is %NULL then the message is sent to the default receiver
2438  * (set by g_socket_connect()).
2439  *
2440  * @vector must point to an array of #GOutputVector structs and
2441  * @num_vectors must be the length of this array.  These structs
2442  * describe the buffers that the sent data will be gathered from.
2443  * If @num_vector is -1, then @vector is assumed to be terminated
2444  * by a #GOutputVector with a %NULL buffer pointer.
2445  *
2446  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2447  * #GSocketControlMessage instances. These correspond to the control
2448  * messages to be sent on the socket.
2449  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2450  * array.
2451  *
2452  * @flags modify how the message sent. The commonly available arguments
2453  * for this is available in the #GSocketMsgFlags enum, but the
2454  * values there are the same as the system values, and the flags
2455  * are passed in as-is, so you can pass in system specific flags too.
2456  *
2457  * If the socket is in blocking mode the call will block until there is
2458  * space for the data in the socket queue. If there is no space available
2459  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2460  * will be returned. To be notified of available space, wait for the %G_IO_OUT
2461  * condition.
2462  *
2463  * Note that on Windows you can't rely on a %G_IO_OUT condition
2464  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2465  * write notification works. However, robust apps should always be able to
2466  * handle this since it can easily appear in other cases too.
2467  *
2468  * On error -1 is returned and @error is set accordingly.
2469  *
2470  * Returns: Number of bytes read, or -1 on error
2471  *
2472  * Since: 2.22
2473  */
2474 gssize
2475 g_socket_send_message (GSocket                *socket,
2476                        GSocketAddress         *address,
2477                        GOutputVector          *vectors,
2478                        gint                    num_vectors,
2479                        GSocketControlMessage **messages,
2480                        gint                    num_messages,
2481                        gint                    flags,
2482                        GError                **error)
2483 {
2484   GOutputVector one_vector;
2485   char zero;
2486
2487   if (!check_socket (socket, error))
2488     return -1;
2489
2490   if (num_vectors == -1)
2491     {
2492       for (num_vectors = 0;
2493            vectors[num_vectors].buffer != NULL;
2494            num_vectors++)
2495         ;
2496     }
2497
2498   if (num_messages == -1)
2499     {
2500       for (num_messages = 0;
2501            messages != NULL && messages[num_messages] != NULL;
2502            num_messages++)
2503         ;
2504     }
2505
2506   if (num_vectors == 0)
2507     {
2508       zero = '\0';
2509
2510       one_vector.buffer = &zero;
2511       one_vector.size = 1;
2512       num_vectors = 1;
2513       vectors = &one_vector;
2514     }
2515
2516 #ifndef G_OS_WIN32
2517   {
2518     struct msghdr msg;
2519     gssize result;
2520
2521     /* name */
2522     if (address)
2523       {
2524         msg.msg_namelen = g_socket_address_get_native_size (address);
2525         msg.msg_name = g_alloca (msg.msg_namelen);
2526         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2527           return -1;
2528       }
2529
2530     /* iov */
2531     {
2532       /* this entire expression will be evaluated at compile time */
2533       if (sizeof *msg.msg_iov == sizeof *vectors &&
2534           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2535           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2536           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2537           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2538           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2539           G_STRUCT_OFFSET (GOutputVector, size))
2540         /* ABI is compatible */
2541         {
2542           msg.msg_iov = (struct iovec *) vectors;
2543           msg.msg_iovlen = num_vectors;
2544         }
2545       else
2546         /* ABI is incompatible */
2547         {
2548           gint i;
2549
2550           msg.msg_iov = g_newa (struct iovec, num_vectors);
2551           for (i = 0; i < num_vectors; i++)
2552             {
2553               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2554               msg.msg_iov[i].iov_len = vectors[i].size;
2555             }
2556           msg.msg_iovlen = num_vectors;
2557         }
2558     }
2559
2560     /* control */
2561     {
2562       struct cmsghdr *cmsg;
2563       gint i;
2564
2565       msg.msg_controllen = 0;
2566       for (i = 0; i < num_messages; i++)
2567         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2568
2569       msg.msg_control = g_alloca (msg.msg_controllen);
2570
2571       cmsg = CMSG_FIRSTHDR (&msg);
2572       for (i = 0; i < num_messages; i++)
2573         {
2574           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2575           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2576           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2577           g_socket_control_message_serialize (messages[i],
2578                                               CMSG_DATA (cmsg));
2579           cmsg = CMSG_NXTHDR (&msg, cmsg);
2580         }
2581       g_assert (cmsg == NULL);
2582     }
2583
2584     while (1)
2585       {
2586         if (socket->priv->blocking &&
2587             !g_socket_condition_wait (socket,
2588                                       G_IO_OUT, NULL, error))
2589           return -1;
2590
2591         result = sendmsg (socket->priv->fd, &msg, flags);
2592         if (result < 0)
2593           {
2594             int errsv = get_socket_errno ();
2595
2596             if (errsv == EINTR)
2597               continue;
2598
2599             if (socket->priv->blocking &&
2600                 (errsv == EWOULDBLOCK ||
2601                  errsv == EAGAIN))
2602               continue;
2603
2604             g_set_error (error, G_IO_ERROR,
2605                          socket_io_error_from_errno (errsv),
2606                          _("Error sending message: %s"), socket_strerror (errsv));
2607
2608             return -1;
2609           }
2610         break;
2611       }
2612
2613     return result;
2614   }
2615 #else
2616   {
2617     struct sockaddr_storage addr;
2618     guint addrlen;
2619     DWORD bytes_sent;
2620     int result;
2621     WSABUF *bufs;
2622     gint i;
2623
2624     /* Win32 doesn't support control messages.
2625        Actually this is possible for raw and datagram sockets
2626        via WSASendMessage on Vista or later, but that doesn't
2627        seem very useful */
2628     if (num_messages != 0)
2629       {
2630         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2631                              _("GSocketControlMessage not supported on windows"));
2632         return -1;
2633       }
2634
2635     /* iov */
2636     bufs = g_newa (WSABUF, num_vectors);
2637     for (i = 0; i < num_vectors; i++)
2638       {
2639         bufs[i].buf = (char *)vectors[i].buffer;
2640         bufs[i].len = (gulong)vectors[i].size;
2641       }
2642
2643     /* name */
2644     addrlen = 0; /* Avoid warning */
2645     if (address)
2646       {
2647         addrlen = g_socket_address_get_native_size (address);
2648         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2649           return -1;
2650       }
2651
2652     while (1)
2653       {
2654         if (socket->priv->blocking &&
2655             !g_socket_condition_wait (socket,
2656                                       G_IO_OUT, NULL, error))
2657           return -1;
2658
2659         if (address)
2660           result = WSASendTo (socket->priv->fd,
2661                               bufs, num_vectors,
2662                               &bytes_sent, flags,
2663                               (const struct sockaddr *)&addr, addrlen,
2664                               NULL, NULL);
2665         else
2666           result = WSASend (socket->priv->fd,
2667                             bufs, num_vectors,
2668                             &bytes_sent, flags,
2669                             NULL, NULL);
2670
2671         if (result != 0)
2672           {
2673             int errsv = get_socket_errno ();
2674
2675             if (errsv == WSAEINTR)
2676               continue;
2677
2678             if (errsv == WSAEWOULDBLOCK)
2679               win32_unset_event_mask (socket, FD_WRITE);
2680
2681             if (socket->priv->blocking &&
2682                 errsv == WSAEWOULDBLOCK)
2683               continue;
2684
2685             g_set_error (error, G_IO_ERROR,
2686                          socket_io_error_from_errno (errsv),
2687                          _("Error sending message: %s"), socket_strerror (errsv));
2688
2689             return -1;
2690           }
2691         break;
2692       }
2693
2694     return bytes_sent;
2695   }
2696 #endif
2697 }
2698
2699 /**
2700  * g_socket_receive_message:
2701  * @socket: a #GSocket
2702  * @address: a pointer to a #GSocketAddress pointer, or %NULL
2703  * @vectors: an array of #GInputVector structs
2704  * @num_vectors: the number of elements in @vectors, or -1
2705  * @messages: a pointer which will be filled with an array of
2706  *     #GSocketControlMessages, or %NULL
2707  * @num_messages: a pointer which will be filled with the number of
2708  *    elements in @messages, or %NULL
2709  * @flags: a pointer to an int containing #GSocketMsgFlags flags
2710  * @error: a #GError pointer, or %NULL
2711  *
2712  * Receive data from a socket.  This is the most complicated and
2713  * fully-featured version of this call. For easier use, see
2714  * g_socket_receive() and g_socket_receive_from().
2715  *
2716  * If @address is non-%NULL then @address will be set equal to the
2717  * source address of the received packet.
2718  * @address is owned by the caller.
2719  *
2720  * @vector must point to an array of #GInputVector structs and
2721  * @num_vectors must be the length of this array.  These structs
2722  * describe the buffers that received data will be scattered into.
2723  * If @num_vector is -1, then @vector is assumed to be terminated
2724  * by a #GInputVector with a %NULL buffer pointer.
2725  *
2726  * As a special case, if the size of the array is zero (in which case,
2727  * @vectors may of course be %NULL), then a single byte is received
2728  * and discarded.  This is to facilitate the common practice of
2729  * sending a single '\0' byte for the purposes of transferring
2730  * ancillary data.
2731  *
2732  * @messages, if non-%NULL, is taken to point to a pointer that will
2733  * be set to point to a newly-allocated array of
2734  * #GSocketControlMessage instances.  These correspond to the control
2735  * messages received from the kernel, one #GSocketControlMessage per
2736  * message from the kernel.  This array is %NULL-terminated and must be
2737  * freed by the caller using g_free().
2738  *
2739  * @num_messages, if non-%NULL, will be set to the number of control
2740  * messages received.
2741  *
2742  * If both @messages and @num_messages are non-%NULL, then
2743  * @num_messages gives the number of #GSocketControlMessage instances
2744  * in @messages (ie: not including the %NULL terminator).
2745  *
2746  * @flags is an in/out parameter. The commonly available arguments
2747  * for this is available in the #GSocketMsgFlags enum, but the
2748  * values there are the same as the system values, and the flags
2749  * are passed in as-is, so you can pass in system specific flags too.
2750  *
2751  * If the socket is in blocking mode the call will block until there is
2752  * some data to receive or there is an error. If there is no data available
2753  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2754  * will be returned. To be notified of available data, wait for the %G_IO_IN
2755  * condition.
2756  *
2757  * On error -1 is returned and @error is set accordingly.
2758  *
2759  * Returns: Number of bytes read, or -1 on error
2760  *
2761  * Since: 2.22
2762  */
2763 gssize
2764 g_socket_receive_message (GSocket                 *socket,
2765                           GSocketAddress         **address,
2766                           GInputVector            *vectors,
2767                           gint                     num_vectors,
2768                           GSocketControlMessage ***messages,
2769                           gint                    *num_messages,
2770                           gint                    *flags,
2771                           GError                 **error)
2772 {
2773   GInputVector one_vector;
2774   char one_byte;
2775
2776   if (!check_socket (socket, error))
2777     return -1;
2778
2779   if (num_vectors == -1)
2780     {
2781       for (num_vectors = 0;
2782            vectors[num_vectors].buffer != NULL;
2783            num_vectors++)
2784         ;
2785     }
2786
2787   if (num_vectors == 0)
2788     {
2789       one_vector.buffer = &one_byte;
2790       one_vector.size = 1;
2791       num_vectors = 1;
2792       vectors = &one_vector;
2793     }
2794
2795 #ifndef G_OS_WIN32
2796   {
2797     struct msghdr msg;
2798     gssize result;
2799     struct sockaddr_storage one_sockaddr;
2800
2801     /* name */
2802     if (address)
2803       {
2804         msg.msg_name = &one_sockaddr;
2805         msg.msg_namelen = sizeof (struct sockaddr_storage);
2806       }
2807     else
2808       {
2809         msg.msg_name = NULL;
2810         msg.msg_namelen = 0;
2811       }
2812
2813     /* iov */
2814     /* this entire expression will be evaluated at compile time */
2815     if (sizeof *msg.msg_iov == sizeof *vectors &&
2816         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2817         G_STRUCT_OFFSET (struct iovec, iov_base) ==
2818         G_STRUCT_OFFSET (GInputVector, buffer) &&
2819         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2820         G_STRUCT_OFFSET (struct iovec, iov_len) ==
2821         G_STRUCT_OFFSET (GInputVector, size))
2822       /* ABI is compatible */
2823       {
2824         msg.msg_iov = (struct iovec *) vectors;
2825         msg.msg_iovlen = num_vectors;
2826       }
2827     else
2828       /* ABI is incompatible */
2829       {
2830         gint i;
2831
2832         msg.msg_iov = g_newa (struct iovec, num_vectors);
2833         for (i = 0; i < num_vectors; i++)
2834           {
2835             msg.msg_iov[i].iov_base = vectors[i].buffer;
2836             msg.msg_iov[i].iov_len = vectors[i].size;
2837           }
2838         msg.msg_iovlen = num_vectors;
2839       }
2840
2841     /* control */
2842     msg.msg_control = g_alloca (2048);
2843     msg.msg_controllen = 2048;
2844
2845     /* flags */
2846     if (flags != NULL)
2847       msg.msg_flags = *flags;
2848     else
2849       msg.msg_flags = 0;
2850
2851     /* do it */
2852     while (1)
2853       {
2854         if (socket->priv->blocking &&
2855             !g_socket_condition_wait (socket,
2856                                       G_IO_IN, NULL, error))
2857           return -1;
2858
2859         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2860
2861         if (result < 0)
2862           {
2863             int errsv = get_socket_errno ();
2864
2865             if (errsv == EINTR)
2866               continue;
2867
2868             if (socket->priv->blocking &&
2869                 (errsv == EWOULDBLOCK ||
2870                  errsv == EAGAIN))
2871               continue;
2872
2873             g_set_error (error, G_IO_ERROR,
2874                          socket_io_error_from_errno (errsv),
2875                          _("Error receiving message: %s"), socket_strerror (errsv));
2876
2877             return -1;
2878           }
2879         break;
2880       }
2881
2882     /* decode address */
2883     if (address != NULL)
2884       {
2885         if (msg.msg_namelen > 0)
2886           *address = g_socket_address_new_from_native (msg.msg_name,
2887                                                        msg.msg_namelen);
2888         else
2889           *address = NULL;
2890       }
2891
2892     /* decode control messages */
2893     {
2894       GSocketControlMessage **my_messages = NULL;
2895       gint allocated = 0, index = 0;
2896       const gchar *scm_pointer;
2897       struct cmsghdr *cmsg;
2898       gsize scm_size;
2899
2900       scm_pointer = (const gchar *) msg.msg_control;
2901       scm_size = msg.msg_controllen;
2902
2903       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2904         {
2905           GSocketControlMessage *message;
2906
2907           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2908                                                           cmsg->cmsg_type,
2909                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2910                                                           CMSG_DATA (cmsg));
2911           if (message == NULL)
2912             /* We've already spewed about the problem in the
2913                deserialization code, so just continue */
2914             continue;
2915
2916           if (index == allocated)
2917             {
2918               /* estimated 99% case: exactly 1 control message */
2919               allocated = MIN (allocated * 2, 1);
2920               my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2921               allocated = 1;
2922             }
2923
2924           my_messages[index++] = message;
2925         }
2926
2927       if (num_messages)
2928         *num_messages = index;
2929
2930       if (messages)
2931         {
2932           my_messages[index++] = NULL;
2933           *messages = my_messages;
2934         }
2935       else
2936         {
2937           gint i;
2938
2939           /* free all those messages we just constructed.
2940            * we have to do it this way if the user ignores the
2941            * messages so that we will close any received fds.
2942            */
2943           for (i = 0; i < index; i++)
2944             g_object_unref (my_messages[i]);
2945           g_free (my_messages);
2946         }
2947     }
2948
2949     /* capture the flags */
2950     if (flags != NULL)
2951       *flags = msg.msg_flags;
2952
2953     return result;
2954   }
2955 #else
2956   {
2957     struct sockaddr_storage addr;
2958     int addrlen;
2959     DWORD bytes_received;
2960     DWORD win_flags;
2961     int result;
2962     WSABUF *bufs;
2963     gint i;
2964
2965     /* iov */
2966     bufs = g_newa (WSABUF, num_vectors);
2967     for (i = 0; i < num_vectors; i++)
2968       {
2969         bufs[i].buf = (char *)vectors[i].buffer;
2970         bufs[i].len = (gulong)vectors[i].size;
2971       }
2972
2973     /* flags */
2974     if (flags != NULL)
2975       win_flags = *flags;
2976     else
2977       win_flags = 0;
2978
2979     /* do it */
2980     while (1)
2981       {
2982         if (socket->priv->blocking &&
2983             !g_socket_condition_wait (socket,
2984                                       G_IO_IN, NULL, error))
2985           return -1;
2986
2987         addrlen = sizeof addr;
2988         if (address)
2989           result = WSARecvFrom (socket->priv->fd,
2990                                 bufs, num_vectors,
2991                                 &bytes_received, &win_flags,
2992                                 (struct sockaddr *)&addr, &addrlen,
2993                                 NULL, NULL);
2994         else
2995           result = WSARecv (socket->priv->fd,
2996                             bufs, num_vectors,
2997                             &bytes_received, &win_flags,
2998                             NULL, NULL);
2999         if (result != 0)
3000           {
3001             int errsv = get_socket_errno ();
3002
3003             if (errsv == WSAEINTR)
3004               continue;
3005
3006             win32_unset_event_mask (socket, FD_READ);
3007
3008             if (socket->priv->blocking &&
3009                 errsv == WSAEWOULDBLOCK)
3010               continue;
3011
3012             g_set_error (error, G_IO_ERROR,
3013                          socket_io_error_from_errno (errsv),
3014                          _("Error receiving message: %s"), socket_strerror (errsv));
3015
3016             return -1;
3017           }
3018         win32_unset_event_mask (socket, FD_READ);
3019         break;
3020       }
3021
3022     /* decode address */
3023     if (address != NULL)
3024       {
3025         if (addrlen > 0)
3026           *address = g_socket_address_new_from_native (&addr, addrlen);
3027         else
3028           *address = NULL;
3029       }
3030
3031     /* capture the flags */
3032     if (flags != NULL)
3033       *flags = win_flags;
3034
3035     return bytes_received;
3036   }
3037 #endif
3038 }
3039
3040 #define __G_SOCKET_C__
3041 #include "gioaliasdef.c"