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