GSocket – GSocketSource finalizing not threadsafe on Windows
[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
30 #include "gsocket.h"
31
32 #ifdef G_OS_UNIX
33 #include "glib-unix.h"
34 #endif
35
36 #include <errno.h>
37 #include <signal.h>
38 #include <string.h>
39 #include <stdlib.h>
40
41 #ifndef G_OS_WIN32
42 # include <fcntl.h>
43 # include <unistd.h>
44 # include <sys/ioctl.h>
45 #endif
46
47 #ifdef HAVE_SYS_FILIO_H
48 # include <sys/filio.h>
49 #endif
50
51 #ifdef HAVE_SYS_UIO_H
52 #include <sys/uio.h>
53 #endif
54
55 #include "gcancellable.h"
56 #include "gioenumtypes.h"
57 #include "ginetaddress.h"
58 #include "ginitable.h"
59 #include "gioerror.h"
60 #include "gioenums.h"
61 #include "gioerror.h"
62 #include "gnetworkingprivate.h"
63 #include "gsocketaddress.h"
64 #include "gsocketcontrolmessage.h"
65 #include "gcredentials.h"
66 #include "glibintl.h"
67
68 /**
69  * SECTION:gsocket
70  * @short_description: Low-level socket object
71  * @include: gio/gio.h
72  * @see_also: #GInitable, <link linkend="gio-gnetworking.h">gnetworking.h</link>
73  *
74  * A #GSocket is a low-level networking primitive. It is a more or less
75  * direct mapping of the BSD socket API in a portable GObject based API.
76  * It supports both the UNIX socket implementations and winsock2 on Windows.
77  *
78  * #GSocket is the platform independent base upon which the higher level
79  * network primitives are based. Applications are not typically meant to
80  * use it directly, but rather through classes like #GSocketClient,
81  * #GSocketService and #GSocketConnection. However there may be cases where
82  * direct use of #GSocket is useful.
83  *
84  * #GSocket implements the #GInitable interface, so if it is manually constructed
85  * by e.g. g_object_new() you must call g_initable_init() and check the
86  * results before using the object. This is done automatically in
87  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
88  * %NULL.
89  *
90  * Sockets operate in two general modes, blocking or non-blocking. When
91  * in blocking mode all operations block until the requested operation
92  * is finished or there is an error. In non-blocking mode all calls that
93  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
94  * To know when a call would successfully run you can call g_socket_condition_check(),
95  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
96  * attach it to a #GMainContext to get callbacks when I/O is possible.
97  * Note that all sockets are always set to non blocking mode in the system, and
98  * blocking mode is emulated in GSocket.
99  *
100  * When working in non-blocking mode applications should always be able to
101  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
102  * function said that I/O was possible. This can easily happen in case
103  * of a race condition in the application, but it can also happen for other
104  * reasons. For instance, on Windows a socket is always seen as writable
105  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
106  *
107  * #GSocket<!-- -->s can be either connection oriented or datagram based.
108  * For connection oriented types you must first establish a connection by
109  * either connecting to an address or accepting a connection from another
110  * address. For connectionless socket types the target/source address is
111  * specified or received in each I/O operation.
112  *
113  * All socket file descriptors are set to be close-on-exec.
114  *
115  * Note that creating a #GSocket causes the signal %SIGPIPE to be
116  * ignored for the remainder of the program. If you are writing a
117  * command-line utility that uses #GSocket, you may need to take into
118  * account the fact that your program will not automatically be killed
119  * if it tries to write to %stdout after it has been closed.
120  *
121  * Since: 2.22
122  */
123
124 static void     g_socket_initable_iface_init (GInitableIface  *iface);
125 static gboolean g_socket_initable_init       (GInitable       *initable,
126                                               GCancellable    *cancellable,
127                                               GError         **error);
128
129 enum
130 {
131   PROP_0,
132   PROP_FAMILY,
133   PROP_TYPE,
134   PROP_PROTOCOL,
135   PROP_FD,
136   PROP_BLOCKING,
137   PROP_LISTEN_BACKLOG,
138   PROP_KEEPALIVE,
139   PROP_LOCAL_ADDRESS,
140   PROP_REMOTE_ADDRESS,
141   PROP_TIMEOUT,
142   PROP_TTL,
143   PROP_BROADCAST,
144   PROP_MULTICAST_LOOPBACK,
145   PROP_MULTICAST_TTL
146 };
147
148 /* Size of the receiver cache for g_socket_receive_from() */
149 #define RECV_ADDR_CACHE_SIZE 8
150
151 struct _GSocketPrivate
152 {
153   GSocketFamily   family;
154   GSocketType     type;
155   GSocketProtocol protocol;
156   gint            fd;
157   gint            listen_backlog;
158   guint           timeout;
159   GError         *construct_error;
160   GSocketAddress *remote_address;
161   guint           inited : 1;
162   guint           blocking : 1;
163   guint           keepalive : 1;
164   guint           closed : 1;
165   guint           connected : 1;
166   guint           listening : 1;
167   guint           timed_out : 1;
168   guint           connect_pending : 1;
169 #ifdef G_OS_WIN32
170   WSAEVENT        event;
171   int             current_events;
172   int             current_errors;
173   int             selected_events;
174   GList          *requested_conditions; /* list of requested GIOCondition * */
175   GMutex          win32_source_lock;
176 #endif
177
178   struct {
179     GSocketAddress *addr;
180     struct sockaddr *native;
181     gint native_len;
182     guint64 last_used;
183   } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
184 };
185
186 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
187                          G_ADD_PRIVATE (GSocket)
188                          g_networking_init ();
189                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
190                                                 g_socket_initable_iface_init));
191
192 static int
193 get_socket_errno (void)
194 {
195 #ifndef G_OS_WIN32
196   return errno;
197 #else
198   return WSAGetLastError ();
199 #endif
200 }
201
202 static GIOErrorEnum
203 socket_io_error_from_errno (int err)
204 {
205 #ifndef G_OS_WIN32
206   return g_io_error_from_errno (err);
207 #else
208   switch (err)
209     {
210     case WSAEADDRINUSE:
211       return G_IO_ERROR_ADDRESS_IN_USE;
212     case WSAEWOULDBLOCK:
213       return G_IO_ERROR_WOULD_BLOCK;
214     case WSAEACCES:
215       return G_IO_ERROR_PERMISSION_DENIED;
216     case WSA_INVALID_HANDLE:
217     case WSA_INVALID_PARAMETER:
218     case WSAEBADF:
219     case WSAENOTSOCK:
220       return G_IO_ERROR_INVALID_ARGUMENT;
221     case WSAEPROTONOSUPPORT:
222       return G_IO_ERROR_NOT_SUPPORTED;
223     case WSAECANCELLED:
224       return G_IO_ERROR_CANCELLED;
225     case WSAESOCKTNOSUPPORT:
226     case WSAEOPNOTSUPP:
227     case WSAEPFNOSUPPORT:
228     case WSAEAFNOSUPPORT:
229       return G_IO_ERROR_NOT_SUPPORTED;
230     default:
231       return G_IO_ERROR_FAILED;
232     }
233 #endif
234 }
235
236 static const char *
237 socket_strerror (int err)
238 {
239 #ifndef G_OS_WIN32
240   return g_strerror (err);
241 #else
242   const char *msg_ret;
243   char *msg;
244
245   msg = g_win32_error_message (err);
246
247   msg_ret = g_intern_string (msg);
248   g_free (msg);
249
250   return msg_ret;
251 #endif
252 }
253
254 #ifdef G_OS_WIN32
255 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
256 static void
257 _win32_unset_event_mask (GSocket *socket, int mask)
258 {
259   socket->priv->current_events &= ~mask;
260   socket->priv->current_errors &= ~mask;
261 }
262 #else
263 #define win32_unset_event_mask(_socket, _mask)
264 #endif
265
266 /* Windows has broken prototypes... */
267 #ifdef G_OS_WIN32
268 #define getsockopt(sockfd, level, optname, optval, optlen) \
269   getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
270 #define setsockopt(sockfd, level, optname, optval, optlen) \
271   setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
272 #define getsockname(sockfd, addr, addrlen) \
273   getsockname (sockfd, addr, (int *)addrlen)
274 #define getpeername(sockfd, addr, addrlen) \
275   getpeername (sockfd, addr, (int *)addrlen)
276 #define recv(sockfd, buf, len, flags) \
277   recv (sockfd, (gpointer)buf, len, flags)
278 #endif
279
280 static void
281 set_fd_nonblocking (int fd)
282 {
283 #ifndef G_OS_WIN32
284   GError *error = NULL;
285 #else
286   gulong arg;
287 #endif
288
289 #ifndef G_OS_WIN32
290   if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
291     {
292       g_warning ("Error setting socket nonblocking: %s", error->message);
293       g_clear_error (&error);
294     }
295 #else
296   arg = TRUE;
297
298   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
299     {
300       int errsv = get_socket_errno ();
301       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
302     }
303 #endif
304 }
305
306 static gboolean
307 check_socket (GSocket *socket,
308               GError **error)
309 {
310   if (!socket->priv->inited)
311     {
312       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
313                            _("Invalid socket, not initialized"));
314       return FALSE;
315     }
316
317   if (socket->priv->construct_error)
318     {
319       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
320                    _("Invalid socket, initialization failed due to: %s"),
321                    socket->priv->construct_error->message);
322       return FALSE;
323     }
324
325   if (socket->priv->closed)
326     {
327       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
328                            _("Socket is already closed"));
329       return FALSE;
330     }
331
332   if (socket->priv->timed_out)
333     {
334       socket->priv->timed_out = FALSE;
335       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
336                            _("Socket I/O timed out"));
337       return FALSE;
338     }
339
340   return TRUE;
341 }
342
343 static void
344 g_socket_details_from_fd (GSocket *socket)
345 {
346   struct sockaddr_storage address;
347   gint fd;
348   guint addrlen;
349   int value, family;
350   int errsv;
351
352   fd = socket->priv->fd;
353   if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
354     {
355       errsv = get_socket_errno ();
356
357       switch (errsv)
358         {
359 #ifdef ENOTSOCK
360          case ENOTSOCK:
361 #else
362 #ifdef WSAENOTSOCK
363          case WSAENOTSOCK:
364 #endif
365 #endif
366          case EBADF:
367           /* programmer error */
368           g_error ("creating GSocket from fd %d: %s\n",
369                    fd, socket_strerror (errsv));
370          default:
371            break;
372         }
373
374       goto err;
375     }
376
377   switch (value)
378     {
379      case SOCK_STREAM:
380       socket->priv->type = G_SOCKET_TYPE_STREAM;
381       break;
382
383      case SOCK_DGRAM:
384       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
385       break;
386
387      case SOCK_SEQPACKET:
388       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
389       break;
390
391      default:
392       socket->priv->type = G_SOCKET_TYPE_INVALID;
393       break;
394     }
395
396   addrlen = sizeof address;
397   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
398     {
399       errsv = get_socket_errno ();
400       goto err;
401     }
402
403   if (addrlen > 0)
404     {
405       g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
406                 sizeof address.ss_family <= addrlen);
407       family = address.ss_family;
408     }
409   else
410     {
411       /* On Solaris, this happens if the socket is not yet connected.
412        * But we can use SO_DOMAIN as a workaround there.
413        */
414 #ifdef SO_DOMAIN
415       if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
416         {
417           errsv = get_socket_errno ();
418           goto err;
419         }
420 #else
421       /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
422       errsv = -1;
423       goto err;
424 #endif
425     }
426
427   switch (family)
428     {
429      case G_SOCKET_FAMILY_IPV4:
430      case G_SOCKET_FAMILY_IPV6:
431        socket->priv->family = address.ss_family;
432        switch (socket->priv->type)
433          {
434          case G_SOCKET_TYPE_STREAM:
435            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
436            break;
437
438          case G_SOCKET_TYPE_DATAGRAM:
439            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
440            break;
441
442          case G_SOCKET_TYPE_SEQPACKET:
443            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
444            break;
445
446          default:
447            break;
448          }
449        break;
450
451      case G_SOCKET_FAMILY_UNIX:
452        socket->priv->family = G_SOCKET_FAMILY_UNIX;
453        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
454        break;
455
456      default:
457        socket->priv->family = G_SOCKET_FAMILY_INVALID;
458        break;
459     }
460
461   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
462     {
463       addrlen = sizeof address;
464       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
465         socket->priv->connected = TRUE;
466     }
467
468   if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
469     {
470       socket->priv->keepalive = !!value;
471     }
472   else
473     {
474       /* Can't read, maybe not supported, assume FALSE */
475       socket->priv->keepalive = FALSE;
476     }
477
478   return;
479
480  err:
481   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
482                socket_io_error_from_errno (errsv),
483                _("creating GSocket from fd: %s"),
484                socket_strerror (errsv));
485 }
486
487 /* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
488 gint
489 g_socket (gint     domain,
490           gint     type,
491           gint     protocol,
492           GError **error)
493 {
494   int fd;
495
496 #ifdef SOCK_CLOEXEC
497   fd = socket (domain, type | SOCK_CLOEXEC, protocol);
498   if (fd != -1)
499     return fd;
500
501   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
502   if (fd < 0 && errno == EINVAL)
503 #endif
504     fd = socket (domain, type, protocol);
505
506   if (fd < 0)
507     {
508       int errsv = get_socket_errno ();
509
510       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
511                    _("Unable to create socket: %s"), socket_strerror (errsv));
512       errno = errsv;
513       return -1;
514     }
515
516 #ifndef G_OS_WIN32
517   {
518     int flags;
519
520     /* We always want to set close-on-exec to protect users. If you
521        need to so some weird inheritance to exec you can re-enable this
522        using lower level hacks with g_socket_get_fd(). */
523     flags = fcntl (fd, F_GETFD, 0);
524     if (flags != -1 &&
525         (flags & FD_CLOEXEC) == 0)
526       {
527         flags |= FD_CLOEXEC;
528         fcntl (fd, F_SETFD, flags);
529       }
530   }
531 #endif
532
533   return fd;
534 }
535
536 static gint
537 g_socket_create_socket (GSocketFamily   family,
538                         GSocketType     type,
539                         int             protocol,
540                         GError        **error)
541 {
542   gint native_type;
543
544   switch (type)
545     {
546      case G_SOCKET_TYPE_STREAM:
547       native_type = SOCK_STREAM;
548       break;
549
550      case G_SOCKET_TYPE_DATAGRAM:
551       native_type = SOCK_DGRAM;
552       break;
553
554      case G_SOCKET_TYPE_SEQPACKET:
555       native_type = SOCK_SEQPACKET;
556       break;
557
558      default:
559       g_assert_not_reached ();
560     }
561
562   if (family <= 0)
563     {
564       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
565                    _("Unable to create socket: %s"), _("Unknown family was specified"));
566       return -1;
567     }
568
569   if (protocol == -1)
570     {
571       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
572                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
573       return -1;
574     }
575
576   return g_socket (family, native_type, protocol, error);
577 }
578
579 static void
580 g_socket_constructed (GObject *object)
581 {
582   GSocket *socket = G_SOCKET (object);
583
584   if (socket->priv->fd >= 0)
585     /* create socket->priv info from the fd */
586     g_socket_details_from_fd (socket);
587
588   else
589     /* create the fd from socket->priv info */
590     socket->priv->fd = g_socket_create_socket (socket->priv->family,
591                                                socket->priv->type,
592                                                socket->priv->protocol,
593                                                &socket->priv->construct_error);
594
595   /* Always use native nonblocking sockets, as
596      windows sets sockets to nonblocking automatically
597      in certain operations. This way we make things work
598      the same on all platforms */
599   if (socket->priv->fd != -1)
600     set_fd_nonblocking (socket->priv->fd);
601 }
602
603 static void
604 g_socket_get_property (GObject    *object,
605                        guint       prop_id,
606                        GValue     *value,
607                        GParamSpec *pspec)
608 {
609   GSocket *socket = G_SOCKET (object);
610   GSocketAddress *address;
611
612   switch (prop_id)
613     {
614       case PROP_FAMILY:
615         g_value_set_enum (value, socket->priv->family);
616         break;
617
618       case PROP_TYPE:
619         g_value_set_enum (value, socket->priv->type);
620         break;
621
622       case PROP_PROTOCOL:
623         g_value_set_enum (value, socket->priv->protocol);
624         break;
625
626       case PROP_FD:
627         g_value_set_int (value, socket->priv->fd);
628         break;
629
630       case PROP_BLOCKING:
631         g_value_set_boolean (value, socket->priv->blocking);
632         break;
633
634       case PROP_LISTEN_BACKLOG:
635         g_value_set_int (value, socket->priv->listen_backlog);
636         break;
637
638       case PROP_KEEPALIVE:
639         g_value_set_boolean (value, socket->priv->keepalive);
640         break;
641
642       case PROP_LOCAL_ADDRESS:
643         address = g_socket_get_local_address (socket, NULL);
644         g_value_take_object (value, address);
645         break;
646
647       case PROP_REMOTE_ADDRESS:
648         address = g_socket_get_remote_address (socket, NULL);
649         g_value_take_object (value, address);
650         break;
651
652       case PROP_TIMEOUT:
653         g_value_set_uint (value, socket->priv->timeout);
654         break;
655
656       case PROP_TTL:
657         g_value_set_uint (value, g_socket_get_ttl (socket));
658         break;
659
660       case PROP_BROADCAST:
661         g_value_set_boolean (value, g_socket_get_broadcast (socket));
662         break;
663
664       case PROP_MULTICAST_LOOPBACK:
665         g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
666         break;
667
668       case PROP_MULTICAST_TTL:
669         g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
670         break;
671
672       default:
673         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
674     }
675 }
676
677 static void
678 g_socket_set_property (GObject      *object,
679                        guint         prop_id,
680                        const GValue *value,
681                        GParamSpec   *pspec)
682 {
683   GSocket *socket = G_SOCKET (object);
684
685   switch (prop_id)
686     {
687       case PROP_FAMILY:
688         socket->priv->family = g_value_get_enum (value);
689         break;
690
691       case PROP_TYPE:
692         socket->priv->type = g_value_get_enum (value);
693         break;
694
695       case PROP_PROTOCOL:
696         socket->priv->protocol = g_value_get_enum (value);
697         break;
698
699       case PROP_FD:
700         socket->priv->fd = g_value_get_int (value);
701         break;
702
703       case PROP_BLOCKING:
704         g_socket_set_blocking (socket, g_value_get_boolean (value));
705         break;
706
707       case PROP_LISTEN_BACKLOG:
708         g_socket_set_listen_backlog (socket, g_value_get_int (value));
709         break;
710
711       case PROP_KEEPALIVE:
712         g_socket_set_keepalive (socket, g_value_get_boolean (value));
713         break;
714
715       case PROP_TIMEOUT:
716         g_socket_set_timeout (socket, g_value_get_uint (value));
717         break;
718
719       case PROP_TTL:
720         g_socket_set_ttl (socket, g_value_get_uint (value));
721         break;
722
723       case PROP_BROADCAST:
724         g_socket_set_broadcast (socket, g_value_get_boolean (value));
725         break;
726
727       case PROP_MULTICAST_LOOPBACK:
728         g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
729         break;
730
731       case PROP_MULTICAST_TTL:
732         g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
733         break;
734
735       default:
736         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
737     }
738 }
739
740 static void
741 g_socket_finalize (GObject *object)
742 {
743   GSocket *socket = G_SOCKET (object);
744   gint i;
745
746   g_clear_error (&socket->priv->construct_error);
747
748   if (socket->priv->fd != -1 &&
749       !socket->priv->closed)
750     g_socket_close (socket, NULL);
751
752   if (socket->priv->remote_address)
753     g_object_unref (socket->priv->remote_address);
754
755 #ifdef G_OS_WIN32
756   if (socket->priv->event != WSA_INVALID_EVENT)
757     {
758       WSACloseEvent (socket->priv->event);
759       socket->priv->event = WSA_INVALID_EVENT;
760     }
761
762   g_assert (socket->priv->requested_conditions == NULL);
763   g_mutex_clear (&socket->priv->win32_source_lock);
764 #endif
765
766   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
767     {
768       if (socket->priv->recv_addr_cache[i].addr)
769         {
770           g_object_unref (socket->priv->recv_addr_cache[i].addr);
771           g_free (socket->priv->recv_addr_cache[i].native);
772         }
773     }
774
775   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
776     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
777 }
778
779 static void
780 g_socket_class_init (GSocketClass *klass)
781 {
782   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
783
784 #ifdef SIGPIPE
785   /* There is no portable, thread-safe way to avoid having the process
786    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
787    * forced to simply ignore the signal process-wide.
788    */
789   signal (SIGPIPE, SIG_IGN);
790 #endif
791
792   gobject_class->finalize = g_socket_finalize;
793   gobject_class->constructed = g_socket_constructed;
794   gobject_class->set_property = g_socket_set_property;
795   gobject_class->get_property = g_socket_get_property;
796
797   g_object_class_install_property (gobject_class, PROP_FAMILY,
798                                    g_param_spec_enum ("family",
799                                                       P_("Socket family"),
800                                                       P_("The sockets address family"),
801                                                       G_TYPE_SOCKET_FAMILY,
802                                                       G_SOCKET_FAMILY_INVALID,
803                                                       G_PARAM_CONSTRUCT_ONLY |
804                                                       G_PARAM_READWRITE |
805                                                       G_PARAM_STATIC_STRINGS));
806
807   g_object_class_install_property (gobject_class, PROP_TYPE,
808                                    g_param_spec_enum ("type",
809                                                       P_("Socket type"),
810                                                       P_("The sockets type"),
811                                                       G_TYPE_SOCKET_TYPE,
812                                                       G_SOCKET_TYPE_STREAM,
813                                                       G_PARAM_CONSTRUCT_ONLY |
814                                                       G_PARAM_READWRITE |
815                                                       G_PARAM_STATIC_STRINGS));
816
817   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
818                                    g_param_spec_enum ("protocol",
819                                                       P_("Socket protocol"),
820                                                       P_("The id of the protocol to use, or -1 for unknown"),
821                                                       G_TYPE_SOCKET_PROTOCOL,
822                                                       G_SOCKET_PROTOCOL_UNKNOWN,
823                                                       G_PARAM_CONSTRUCT_ONLY |
824                                                       G_PARAM_READWRITE |
825                                                       G_PARAM_STATIC_STRINGS));
826
827   g_object_class_install_property (gobject_class, PROP_FD,
828                                    g_param_spec_int ("fd",
829                                                      P_("File descriptor"),
830                                                      P_("The sockets file descriptor"),
831                                                      G_MININT,
832                                                      G_MAXINT,
833                                                      -1,
834                                                      G_PARAM_CONSTRUCT_ONLY |
835                                                      G_PARAM_READWRITE |
836                                                      G_PARAM_STATIC_STRINGS));
837
838   g_object_class_install_property (gobject_class, PROP_BLOCKING,
839                                    g_param_spec_boolean ("blocking",
840                                                          P_("blocking"),
841                                                          P_("Whether or not I/O on this socket is blocking"),
842                                                          TRUE,
843                                                          G_PARAM_READWRITE |
844                                                          G_PARAM_STATIC_STRINGS));
845
846   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
847                                    g_param_spec_int ("listen-backlog",
848                                                      P_("Listen backlog"),
849                                                      P_("Outstanding connections in the listen queue"),
850                                                      0,
851                                                      SOMAXCONN,
852                                                      10,
853                                                      G_PARAM_READWRITE |
854                                                      G_PARAM_STATIC_STRINGS));
855
856   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
857                                    g_param_spec_boolean ("keepalive",
858                                                          P_("Keep connection alive"),
859                                                          P_("Keep connection alive by sending periodic pings"),
860                                                          FALSE,
861                                                          G_PARAM_READWRITE |
862                                                          G_PARAM_STATIC_STRINGS));
863
864   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
865                                    g_param_spec_object ("local-address",
866                                                         P_("Local address"),
867                                                         P_("The local address the socket is bound to"),
868                                                         G_TYPE_SOCKET_ADDRESS,
869                                                         G_PARAM_READABLE |
870                                                         G_PARAM_STATIC_STRINGS));
871
872   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
873                                    g_param_spec_object ("remote-address",
874                                                         P_("Remote address"),
875                                                         P_("The remote address the socket is connected to"),
876                                                         G_TYPE_SOCKET_ADDRESS,
877                                                         G_PARAM_READABLE |
878                                                         G_PARAM_STATIC_STRINGS));
879
880   /**
881    * GSocket:timeout:
882    *
883    * The timeout in seconds on socket I/O
884    *
885    * Since: 2.26
886    */
887   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
888                                    g_param_spec_uint ("timeout",
889                                                       P_("Timeout"),
890                                                       P_("The timeout in seconds on socket I/O"),
891                                                       0,
892                                                       G_MAXUINT,
893                                                       0,
894                                                       G_PARAM_READWRITE |
895                                                       G_PARAM_STATIC_STRINGS));
896
897   /**
898    * GSocket:broadcast:
899    *
900    * Whether the socket should allow sending to broadcast addresses.
901    *
902    * Since: 2.32
903    */
904   g_object_class_install_property (gobject_class, PROP_BROADCAST,
905                                    g_param_spec_boolean ("broadcast",
906                                                          P_("Broadcast"),
907                                                          P_("Whether to allow sending to broadcast addresses"),
908                                                          FALSE,
909                                                          G_PARAM_READWRITE |
910                                                          G_PARAM_STATIC_STRINGS));
911
912   /**
913    * GSocket:ttl:
914    *
915    * Time-to-live for outgoing unicast packets
916    *
917    * Since: 2.32
918    */
919   g_object_class_install_property (gobject_class, PROP_TTL,
920                                    g_param_spec_uint ("ttl",
921                                                       P_("TTL"),
922                                                       P_("Time-to-live of outgoing unicast packets"),
923                                                       0, G_MAXUINT, 0,
924                                                       G_PARAM_READWRITE |
925                                                       G_PARAM_STATIC_STRINGS));
926
927   /**
928    * GSocket:multicast-loopback:
929    *
930    * Whether outgoing multicast packets loop back to the local host.
931    *
932    * Since: 2.32
933    */
934   g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
935                                    g_param_spec_boolean ("multicast-loopback",
936                                                          P_("Multicast loopback"),
937                                                          P_("Whether outgoing multicast packets loop back to the local host"),
938                                                          TRUE,
939                                                          G_PARAM_READWRITE |
940                                                          G_PARAM_STATIC_STRINGS));
941
942   /**
943    * GSocket:multicast-ttl:
944    *
945    * Time-to-live out outgoing multicast packets
946    *
947    * Since: 2.32
948    */
949   g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
950                                    g_param_spec_uint ("multicast-ttl",
951                                                       P_("Multicast TTL"),
952                                                       P_("Time-to-live of outgoing multicast packets"),
953                                                       0, G_MAXUINT, 1,
954                                                       G_PARAM_READWRITE |
955                                                       G_PARAM_STATIC_STRINGS));
956 }
957
958 static void
959 g_socket_initable_iface_init (GInitableIface *iface)
960 {
961   iface->init = g_socket_initable_init;
962 }
963
964 static void
965 g_socket_init (GSocket *socket)
966 {
967   socket->priv = g_socket_get_instance_private (socket);
968
969   socket->priv->fd = -1;
970   socket->priv->blocking = TRUE;
971   socket->priv->listen_backlog = 10;
972   socket->priv->construct_error = NULL;
973 #ifdef G_OS_WIN32
974   socket->priv->event = WSA_INVALID_EVENT;
975   g_mutex_init (&socket->priv->win32_source_lock);
976 #endif
977 }
978
979 static gboolean
980 g_socket_initable_init (GInitable *initable,
981                         GCancellable *cancellable,
982                         GError  **error)
983 {
984   GSocket  *socket;
985
986   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
987
988   socket = G_SOCKET (initable);
989
990   if (cancellable != NULL)
991     {
992       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
993                            _("Cancellable initialization not supported"));
994       return FALSE;
995     }
996
997   socket->priv->inited = TRUE;
998
999   if (socket->priv->construct_error)
1000     {
1001       if (error)
1002         *error = g_error_copy (socket->priv->construct_error);
1003       return FALSE;
1004     }
1005
1006
1007   return TRUE;
1008 }
1009
1010 /**
1011  * g_socket_new:
1012  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1013  * @type: the socket type to use.
1014  * @protocol: the id of the protocol to use, or 0 for default.
1015  * @error: #GError for error reporting, or %NULL to ignore.
1016  *
1017  * Creates a new #GSocket with the defined family, type and protocol.
1018  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1019  * for the family and type is used.
1020  *
1021  * The @protocol is a family and type specific int that specifies what
1022  * kind of protocol to use. #GSocketProtocol lists several common ones.
1023  * Many families only support one protocol, and use 0 for this, others
1024  * support several and using 0 means to use the default protocol for
1025  * the family and type.
1026  *
1027  * The protocol id is passed directly to the operating
1028  * system, so you can use protocols not listed in #GSocketProtocol if you
1029  * know the protocol number used for it.
1030  *
1031  * Returns: a #GSocket or %NULL on error.
1032  *     Free the returned object with g_object_unref().
1033  *
1034  * Since: 2.22
1035  */
1036 GSocket *
1037 g_socket_new (GSocketFamily     family,
1038               GSocketType       type,
1039               GSocketProtocol   protocol,
1040               GError          **error)
1041 {
1042   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1043                                    NULL, error,
1044                                    "family", family,
1045                                    "type", type,
1046                                    "protocol", protocol,
1047                                    NULL));
1048 }
1049
1050 /**
1051  * g_socket_new_from_fd:
1052  * @fd: a native socket file descriptor.
1053  * @error: #GError for error reporting, or %NULL to ignore.
1054  *
1055  * Creates a new #GSocket from a native file descriptor
1056  * or winsock SOCKET handle.
1057  *
1058  * This reads all the settings from the file descriptor so that
1059  * all properties should work. Note that the file descriptor
1060  * will be set to non-blocking mode, independent on the blocking
1061  * mode of the #GSocket.
1062  *
1063  * Returns: a #GSocket or %NULL on error.
1064  *     Free the returned object with g_object_unref().
1065  *
1066  * Since: 2.22
1067  */
1068 GSocket *
1069 g_socket_new_from_fd (gint     fd,
1070                       GError **error)
1071 {
1072   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1073                                    NULL, error,
1074                                    "fd", fd,
1075                                    NULL));
1076 }
1077
1078 /**
1079  * g_socket_set_blocking:
1080  * @socket: a #GSocket.
1081  * @blocking: Whether to use blocking I/O or not.
1082  *
1083  * Sets the blocking mode of the socket. In blocking mode
1084  * all operations block until they succeed or there is an error. In
1085  * non-blocking mode all functions return results immediately or
1086  * with a %G_IO_ERROR_WOULD_BLOCK error.
1087  *
1088  * All sockets are created in blocking mode. However, note that the
1089  * platform level socket is always non-blocking, and blocking mode
1090  * is a GSocket level feature.
1091  *
1092  * Since: 2.22
1093  */
1094 void
1095 g_socket_set_blocking (GSocket  *socket,
1096                        gboolean  blocking)
1097 {
1098   g_return_if_fail (G_IS_SOCKET (socket));
1099
1100   blocking = !!blocking;
1101
1102   if (socket->priv->blocking == blocking)
1103     return;
1104
1105   socket->priv->blocking = blocking;
1106   g_object_notify (G_OBJECT (socket), "blocking");
1107 }
1108
1109 /**
1110  * g_socket_get_blocking:
1111  * @socket: a #GSocket.
1112  *
1113  * Gets the blocking mode of the socket. For details on blocking I/O,
1114  * see g_socket_set_blocking().
1115  *
1116  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1117  *
1118  * Since: 2.22
1119  */
1120 gboolean
1121 g_socket_get_blocking (GSocket *socket)
1122 {
1123   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1124
1125   return socket->priv->blocking;
1126 }
1127
1128 /**
1129  * g_socket_set_keepalive:
1130  * @socket: a #GSocket.
1131  * @keepalive: Value for the keepalive flag
1132  *
1133  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1134  * this flag is set on a socket, the system will attempt to verify that the
1135  * remote socket endpoint is still present if a sufficiently long period of
1136  * time passes with no data being exchanged. If the system is unable to
1137  * verify the presence of the remote endpoint, it will automatically close
1138  * the connection.
1139  *
1140  * This option is only functional on certain kinds of sockets. (Notably,
1141  * %G_SOCKET_PROTOCOL_TCP sockets.)
1142  *
1143  * The exact time between pings is system- and protocol-dependent, but will
1144  * normally be at least two hours. Most commonly, you would set this flag
1145  * on a server socket if you want to allow clients to remain idle for long
1146  * periods of time, but also want to ensure that connections are eventually
1147  * garbage-collected if clients crash or become unreachable.
1148  *
1149  * Since: 2.22
1150  */
1151 void
1152 g_socket_set_keepalive (GSocket  *socket,
1153                         gboolean  keepalive)
1154 {
1155   GError *error = NULL;
1156
1157   g_return_if_fail (G_IS_SOCKET (socket));
1158
1159   keepalive = !!keepalive;
1160   if (socket->priv->keepalive == keepalive)
1161     return;
1162
1163   if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1164                             keepalive, &error))
1165     {
1166       g_warning ("error setting keepalive: %s", error->message);
1167       g_error_free (error);
1168       return;
1169     }
1170
1171   socket->priv->keepalive = keepalive;
1172   g_object_notify (G_OBJECT (socket), "keepalive");
1173 }
1174
1175 /**
1176  * g_socket_get_keepalive:
1177  * @socket: a #GSocket.
1178  *
1179  * Gets the keepalive mode of the socket. For details on this,
1180  * see g_socket_set_keepalive().
1181  *
1182  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1183  *
1184  * Since: 2.22
1185  */
1186 gboolean
1187 g_socket_get_keepalive (GSocket *socket)
1188 {
1189   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1190
1191   return socket->priv->keepalive;
1192 }
1193
1194 /**
1195  * g_socket_get_listen_backlog:
1196  * @socket: a #GSocket.
1197  *
1198  * Gets the listen backlog setting of the socket. For details on this,
1199  * see g_socket_set_listen_backlog().
1200  *
1201  * Returns: the maximum number of pending connections.
1202  *
1203  * Since: 2.22
1204  */
1205 gint
1206 g_socket_get_listen_backlog  (GSocket *socket)
1207 {
1208   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1209
1210   return socket->priv->listen_backlog;
1211 }
1212
1213 /**
1214  * g_socket_set_listen_backlog:
1215  * @socket: a #GSocket.
1216  * @backlog: the maximum number of pending connections.
1217  *
1218  * Sets the maximum number of outstanding connections allowed
1219  * when listening on this socket. If more clients than this are
1220  * connecting to the socket and the application is not handling them
1221  * on time then the new connections will be refused.
1222  *
1223  * Note that this must be called before g_socket_listen() and has no
1224  * effect if called after that.
1225  *
1226  * Since: 2.22
1227  */
1228 void
1229 g_socket_set_listen_backlog (GSocket *socket,
1230                              gint     backlog)
1231 {
1232   g_return_if_fail (G_IS_SOCKET (socket));
1233   g_return_if_fail (!socket->priv->listening);
1234
1235   if (backlog != socket->priv->listen_backlog)
1236     {
1237       socket->priv->listen_backlog = backlog;
1238       g_object_notify (G_OBJECT (socket), "listen-backlog");
1239     }
1240 }
1241
1242 /**
1243  * g_socket_get_timeout:
1244  * @socket: a #GSocket.
1245  *
1246  * Gets the timeout setting of the socket. For details on this, see
1247  * g_socket_set_timeout().
1248  *
1249  * Returns: the timeout in seconds
1250  *
1251  * Since: 2.26
1252  */
1253 guint
1254 g_socket_get_timeout (GSocket *socket)
1255 {
1256   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1257
1258   return socket->priv->timeout;
1259 }
1260
1261 /**
1262  * g_socket_set_timeout:
1263  * @socket: a #GSocket.
1264  * @timeout: the timeout for @socket, in seconds, or 0 for none
1265  *
1266  * Sets the time in seconds after which I/O operations on @socket will
1267  * time out if they have not yet completed.
1268  *
1269  * On a blocking socket, this means that any blocking #GSocket
1270  * operation will time out after @timeout seconds of inactivity,
1271  * returning %G_IO_ERROR_TIMED_OUT.
1272  *
1273  * On a non-blocking socket, calls to g_socket_condition_wait() will
1274  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1275  * created with g_socket_create_source() will trigger after
1276  * @timeout seconds of inactivity, with the requested condition
1277  * set, at which point calling g_socket_receive(), g_socket_send(),
1278  * g_socket_check_connect_result(), etc, will fail with
1279  * %G_IO_ERROR_TIMED_OUT.
1280  *
1281  * If @timeout is 0 (the default), operations will never time out
1282  * on their own.
1283  *
1284  * Note that if an I/O operation is interrupted by a signal, this may
1285  * cause the timeout to be reset.
1286  *
1287  * Since: 2.26
1288  */
1289 void
1290 g_socket_set_timeout (GSocket *socket,
1291                       guint    timeout)
1292 {
1293   g_return_if_fail (G_IS_SOCKET (socket));
1294
1295   if (timeout != socket->priv->timeout)
1296     {
1297       socket->priv->timeout = timeout;
1298       g_object_notify (G_OBJECT (socket), "timeout");
1299     }
1300 }
1301
1302 /**
1303  * g_socket_get_ttl:
1304  * @socket: a #GSocket.
1305  *
1306  * Gets the unicast time-to-live setting on @socket; see
1307  * g_socket_set_ttl() for more details.
1308  *
1309  * Returns: the time-to-live setting on @socket
1310  *
1311  * Since: 2.32
1312  */
1313 guint
1314 g_socket_get_ttl (GSocket *socket)
1315 {
1316   GError *error = NULL;
1317   gint value;
1318
1319   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1320
1321   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1322     {
1323       g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1324                            &value, &error);
1325     }
1326   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1327     {
1328       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1329                            &value, &error);
1330     }
1331   else
1332     g_return_val_if_reached (0);
1333
1334   if (error)
1335     {
1336       g_warning ("error getting unicast ttl: %s", error->message);
1337       g_error_free (error);
1338       return 0;
1339     }
1340
1341   return value;
1342 }
1343
1344 /**
1345  * g_socket_set_ttl:
1346  * @socket: a #GSocket.
1347  * @ttl: the time-to-live value for all unicast packets on @socket
1348  *
1349  * Sets the time-to-live for outgoing unicast packets on @socket.
1350  * By default the platform-specific default value is used.
1351  *
1352  * Since: 2.32
1353  */
1354 void
1355 g_socket_set_ttl (GSocket  *socket,
1356                   guint     ttl)
1357 {
1358   GError *error = NULL;
1359
1360   g_return_if_fail (G_IS_SOCKET (socket));
1361
1362   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1363     {
1364       g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1365                            ttl, &error);
1366     }
1367   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1368     {
1369       g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1370                            ttl, NULL);
1371       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1372                            ttl, &error);
1373     }
1374   else
1375     g_return_if_reached ();
1376
1377   if (error)
1378     {
1379       g_warning ("error setting unicast ttl: %s", error->message);
1380       g_error_free (error);
1381       return;
1382     }
1383
1384   g_object_notify (G_OBJECT (socket), "ttl");
1385 }
1386
1387 /**
1388  * g_socket_get_broadcast:
1389  * @socket: a #GSocket.
1390  *
1391  * Gets the broadcast setting on @socket; if %TRUE,
1392  * it is possible to send packets to broadcast
1393  * addresses.
1394  *
1395  * Returns: the broadcast setting on @socket
1396  *
1397  * Since: 2.32
1398  */
1399 gboolean
1400 g_socket_get_broadcast (GSocket *socket)
1401 {
1402   GError *error = NULL;
1403   gint value;
1404
1405   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1406
1407   if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1408                             &value, &error))
1409     {
1410       g_warning ("error getting broadcast: %s", error->message);
1411       g_error_free (error);
1412       return FALSE;
1413     }
1414
1415   return !!value;
1416 }
1417
1418 /**
1419  * g_socket_set_broadcast:
1420  * @socket: a #GSocket.
1421  * @broadcast: whether @socket should allow sending to broadcast
1422  *     addresses
1423  *
1424  * Sets whether @socket should allow sending to broadcast addresses.
1425  * This is %FALSE by default.
1426  *
1427  * Since: 2.32
1428  */
1429 void
1430 g_socket_set_broadcast (GSocket    *socket,
1431                         gboolean    broadcast)
1432 {
1433   GError *error = NULL;
1434
1435   g_return_if_fail (G_IS_SOCKET (socket));
1436
1437   broadcast = !!broadcast;
1438
1439   if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1440                             broadcast, &error))
1441     {
1442       g_warning ("error setting broadcast: %s", error->message);
1443       g_error_free (error);
1444       return;
1445     }
1446
1447   g_object_notify (G_OBJECT (socket), "broadcast");
1448 }
1449
1450 /**
1451  * g_socket_get_multicast_loopback:
1452  * @socket: a #GSocket.
1453  *
1454  * Gets the multicast loopback setting on @socket; if %TRUE (the
1455  * default), outgoing multicast packets will be looped back to
1456  * multicast listeners on the same host.
1457  *
1458  * Returns: the multicast loopback setting on @socket
1459  *
1460  * Since: 2.32
1461  */
1462 gboolean
1463 g_socket_get_multicast_loopback (GSocket *socket)
1464 {
1465   GError *error = NULL;
1466   gint value;
1467
1468   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1469
1470   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1471     {
1472       g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1473                            &value, &error);
1474     }
1475   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1476     {
1477       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1478                            &value, &error);
1479     }
1480   else
1481     g_return_val_if_reached (FALSE);
1482
1483   if (error)
1484     {
1485       g_warning ("error getting multicast loopback: %s", error->message);
1486       g_error_free (error);
1487       return FALSE;
1488     }
1489
1490   return !!value;
1491 }
1492
1493 /**
1494  * g_socket_set_multicast_loopback:
1495  * @socket: a #GSocket.
1496  * @loopback: whether @socket should receive messages sent to its
1497  *   multicast groups from the local host
1498  *
1499  * Sets whether outgoing multicast packets will be received by sockets
1500  * listening on that multicast address on the same host. This is %TRUE
1501  * by default.
1502  *
1503  * Since: 2.32
1504  */
1505 void
1506 g_socket_set_multicast_loopback (GSocket    *socket,
1507                                  gboolean    loopback)
1508 {
1509   GError *error = NULL;
1510
1511   g_return_if_fail (G_IS_SOCKET (socket));
1512
1513   loopback = !!loopback;
1514
1515   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1516     {
1517       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1518                            loopback, &error);
1519     }
1520   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1521     {
1522       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1523                            loopback, NULL);
1524       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1525                            loopback, &error);
1526     }
1527   else
1528     g_return_if_reached ();
1529
1530   if (error)
1531     {
1532       g_warning ("error setting multicast loopback: %s", error->message);
1533       g_error_free (error);
1534       return;
1535     }
1536
1537   g_object_notify (G_OBJECT (socket), "multicast-loopback");
1538 }
1539
1540 /**
1541  * g_socket_get_multicast_ttl:
1542  * @socket: a #GSocket.
1543  *
1544  * Gets the multicast time-to-live setting on @socket; see
1545  * g_socket_set_multicast_ttl() for more details.
1546  *
1547  * Returns: the multicast time-to-live setting on @socket
1548  *
1549  * Since: 2.32
1550  */
1551 guint
1552 g_socket_get_multicast_ttl (GSocket *socket)
1553 {
1554   GError *error = NULL;
1555   gint value;
1556
1557   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1558
1559   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1560     {
1561       g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1562                            &value, &error);
1563     }
1564   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1565     {
1566       g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1567                            &value, &error);
1568     }
1569   else
1570     g_return_val_if_reached (FALSE);
1571
1572   if (error)
1573     {
1574       g_warning ("error getting multicast ttl: %s", error->message);
1575       g_error_free (error);
1576       return FALSE;
1577     }
1578
1579   return value;
1580 }
1581
1582 /**
1583  * g_socket_set_multicast_ttl:
1584  * @socket: a #GSocket.
1585  * @ttl: the time-to-live value for all multicast datagrams on @socket
1586  *
1587  * Sets the time-to-live for outgoing multicast datagrams on @socket.
1588  * By default, this is 1, meaning that multicast packets will not leave
1589  * the local network.
1590  *
1591  * Since: 2.32
1592  */
1593 void
1594 g_socket_set_multicast_ttl (GSocket  *socket,
1595                             guint     ttl)
1596 {
1597   GError *error = NULL;
1598
1599   g_return_if_fail (G_IS_SOCKET (socket));
1600
1601   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1602     {
1603       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1604                            ttl, &error);
1605     }
1606   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1607     {
1608       g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1609                            ttl, NULL);
1610       g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1611                            ttl, &error);
1612     }
1613   else
1614     g_return_if_reached ();
1615
1616   if (error)
1617     {
1618       g_warning ("error setting multicast ttl: %s", error->message);
1619       g_error_free (error);
1620       return;
1621     }
1622
1623   g_object_notify (G_OBJECT (socket), "multicast-ttl");
1624 }
1625
1626 /**
1627  * g_socket_get_family:
1628  * @socket: a #GSocket.
1629  *
1630  * Gets the socket family of the socket.
1631  *
1632  * Returns: a #GSocketFamily
1633  *
1634  * Since: 2.22
1635  */
1636 GSocketFamily
1637 g_socket_get_family (GSocket *socket)
1638 {
1639   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1640
1641   return socket->priv->family;
1642 }
1643
1644 /**
1645  * g_socket_get_socket_type:
1646  * @socket: a #GSocket.
1647  *
1648  * Gets the socket type of the socket.
1649  *
1650  * Returns: a #GSocketType
1651  *
1652  * Since: 2.22
1653  */
1654 GSocketType
1655 g_socket_get_socket_type (GSocket *socket)
1656 {
1657   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1658
1659   return socket->priv->type;
1660 }
1661
1662 /**
1663  * g_socket_get_protocol:
1664  * @socket: a #GSocket.
1665  *
1666  * Gets the socket protocol id the socket was created with.
1667  * In case the protocol is unknown, -1 is returned.
1668  *
1669  * Returns: a protocol id, or -1 if unknown
1670  *
1671  * Since: 2.22
1672  */
1673 GSocketProtocol
1674 g_socket_get_protocol (GSocket *socket)
1675 {
1676   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1677
1678   return socket->priv->protocol;
1679 }
1680
1681 /**
1682  * g_socket_get_fd:
1683  * @socket: a #GSocket.
1684  *
1685  * Returns the underlying OS socket object. On unix this
1686  * is a socket file descriptor, and on Windows this is
1687  * a Winsock2 SOCKET handle. This may be useful for
1688  * doing platform specific or otherwise unusual operations
1689  * on the socket.
1690  *
1691  * Returns: the file descriptor of the socket.
1692  *
1693  * Since: 2.22
1694  */
1695 int
1696 g_socket_get_fd (GSocket *socket)
1697 {
1698   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1699
1700   return socket->priv->fd;
1701 }
1702
1703 /**
1704  * g_socket_get_local_address:
1705  * @socket: a #GSocket.
1706  * @error: #GError for error reporting, or %NULL to ignore.
1707  *
1708  * Try to get the local address of a bound socket. This is only
1709  * useful if the socket has been bound to a local address,
1710  * either explicitly or implicitly when connecting.
1711  *
1712  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1713  *     Free the returned object with g_object_unref().
1714  *
1715  * Since: 2.22
1716  */
1717 GSocketAddress *
1718 g_socket_get_local_address (GSocket  *socket,
1719                             GError  **error)
1720 {
1721   struct sockaddr_storage buffer;
1722   guint len = sizeof (buffer);
1723
1724   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1725
1726   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1727     {
1728       int errsv = get_socket_errno ();
1729       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1730                    _("could not get local address: %s"), socket_strerror (errsv));
1731       return NULL;
1732     }
1733
1734   return g_socket_address_new_from_native (&buffer, len);
1735 }
1736
1737 /**
1738  * g_socket_get_remote_address:
1739  * @socket: a #GSocket.
1740  * @error: #GError for error reporting, or %NULL to ignore.
1741  *
1742  * Try to get the remove address of a connected socket. This is only
1743  * useful for connection oriented sockets that have been connected.
1744  *
1745  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1746  *     Free the returned object with g_object_unref().
1747  *
1748  * Since: 2.22
1749  */
1750 GSocketAddress *
1751 g_socket_get_remote_address (GSocket  *socket,
1752                              GError  **error)
1753 {
1754   struct sockaddr_storage buffer;
1755   guint len = sizeof (buffer);
1756
1757   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1758
1759   if (socket->priv->connect_pending)
1760     {
1761       if (!g_socket_check_connect_result (socket, error))
1762         return NULL;
1763       else
1764         socket->priv->connect_pending = FALSE;
1765     }
1766
1767   if (!socket->priv->remote_address)
1768     {
1769       if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1770         {
1771           int errsv = get_socket_errno ();
1772           g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1773                        _("could not get remote address: %s"), socket_strerror (errsv));
1774           return NULL;
1775         }
1776
1777       socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1778     }
1779
1780   return g_object_ref (socket->priv->remote_address);
1781 }
1782
1783 /**
1784  * g_socket_is_connected:
1785  * @socket: a #GSocket.
1786  *
1787  * Check whether the socket is connected. This is only useful for
1788  * connection-oriented sockets.
1789  *
1790  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1791  *
1792  * Since: 2.22
1793  */
1794 gboolean
1795 g_socket_is_connected (GSocket *socket)
1796 {
1797   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1798
1799   return socket->priv->connected;
1800 }
1801
1802 /**
1803  * g_socket_listen:
1804  * @socket: a #GSocket.
1805  * @error: #GError for error reporting, or %NULL to ignore.
1806  *
1807  * Marks the socket as a server socket, i.e. a socket that is used
1808  * to accept incoming requests using g_socket_accept().
1809  *
1810  * Before calling this the socket must be bound to a local address using
1811  * g_socket_bind().
1812  *
1813  * To set the maximum amount of outstanding clients, use
1814  * g_socket_set_listen_backlog().
1815  *
1816  * Returns: %TRUE on success, %FALSE on error.
1817  *
1818  * Since: 2.22
1819  */
1820 gboolean
1821 g_socket_listen (GSocket  *socket,
1822                  GError  **error)
1823 {
1824   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1825
1826   if (!check_socket (socket, error))
1827     return FALSE;
1828
1829   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1830     {
1831       int errsv = get_socket_errno ();
1832
1833       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1834                    _("could not listen: %s"), socket_strerror (errsv));
1835       return FALSE;
1836     }
1837
1838   socket->priv->listening = TRUE;
1839
1840   return TRUE;
1841 }
1842
1843 /**
1844  * g_socket_bind:
1845  * @socket: a #GSocket.
1846  * @address: a #GSocketAddress specifying the local address.
1847  * @allow_reuse: whether to allow reusing this address
1848  * @error: #GError for error reporting, or %NULL to ignore.
1849  *
1850  * When a socket is created it is attached to an address family, but it
1851  * doesn't have an address in this family. g_socket_bind() assigns the
1852  * address (sometimes called name) of the socket.
1853  *
1854  * It is generally required to bind to a local address before you can
1855  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1856  * In certain situations, you may also want to bind a socket that will be
1857  * used to initiate connections, though this is not normally required.
1858  *
1859  * If @socket is a TCP socket, then @allow_reuse controls the setting
1860  * of the <literal>SO_REUSEADDR</literal> socket option; normally it
1861  * should be %TRUE for server sockets (sockets that you will
1862  * eventually call g_socket_accept() on), and %FALSE for client
1863  * sockets. (Failing to set this flag on a server socket may cause
1864  * g_socket_bind() to return %G_IO_ERROR_ADDRESS_IN_USE if the server
1865  * program is stopped and then immediately restarted.)
1866  *
1867  * If @socket is a UDP socket, then @allow_reuse determines whether or
1868  * not other UDP sockets can be bound to the same address at the same
1869  * time. In particular, you can have several UDP sockets bound to the
1870  * same address, and they will all receive all of the multicast and
1871  * broadcast packets sent to that address. (The behavior of unicast
1872  * UDP packets to an address with multiple listeners is not defined.)
1873  *
1874  * Returns: %TRUE on success, %FALSE on error.
1875  *
1876  * Since: 2.22
1877  */
1878 gboolean
1879 g_socket_bind (GSocket         *socket,
1880                GSocketAddress  *address,
1881                gboolean         reuse_address,
1882                GError         **error)
1883 {
1884   struct sockaddr_storage addr;
1885   gboolean so_reuseaddr;
1886 #ifdef SO_REUSEPORT
1887   gboolean so_reuseport;
1888 #endif
1889
1890   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1891
1892   if (!check_socket (socket, error))
1893     return FALSE;
1894
1895   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1896     return FALSE;
1897
1898   /* On Windows, SO_REUSEADDR has the semantics we want for UDP
1899    * sockets, but has nasty side effects we don't want for TCP
1900    * sockets.
1901    *
1902    * On other platforms, we set SO_REUSEPORT, if it exists, for
1903    * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
1904    * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
1905    * the desired semantics on UDP (as it does on Linux, although
1906    * Linux has SO_REUSEPORT too as of 3.9).
1907    */
1908
1909 #ifdef G_OS_WIN32
1910   so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1911 #else
1912   so_reuseaddr = !!reuse_address;
1913 #endif
1914
1915 #ifdef SO_REUSEPORT
1916   so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
1917 #endif
1918
1919   /* Ignore errors here, the only likely error is "not supported", and
1920    * this is a "best effort" thing mainly.
1921    */
1922   g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
1923 #ifdef SO_REUSEPORT
1924   g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
1925 #endif
1926
1927   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1928             g_socket_address_get_native_size (address)) < 0)
1929     {
1930       int errsv = get_socket_errno ();
1931       g_set_error (error,
1932                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1933                    _("Error binding to address: %s"), socket_strerror (errsv));
1934       return FALSE;
1935     }
1936
1937   return TRUE;
1938 }
1939
1940 #if !defined(HAVE_IF_NAMETOINDEX) && defined(G_OS_WIN32)
1941 static guint
1942 if_nametoindex (const gchar *iface)
1943 {
1944   PIP_ADAPTER_ADDRESSES addresses = NULL, p;
1945   gulong addresses_len = 0;
1946   guint idx = 0;
1947   DWORD res;
1948
1949   res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, NULL, &addresses_len);
1950   if (res != NO_ERROR && res != ERROR_BUFFER_OVERFLOW)
1951     {
1952       if (res == ERROR_NO_DATA)
1953         errno = ENXIO;
1954       else
1955         errno = EINVAL;
1956       return 0;
1957     }
1958
1959   addresses = g_malloc (addresses_len);
1960   res = GetAdaptersAddresses (AF_UNSPEC, 0, NULL, addresses, &addresses_len);
1961
1962   if (res != NO_ERROR)
1963     {
1964       g_free (addresses);
1965       if (res == ERROR_NO_DATA)
1966         errno = ENXIO;
1967       else
1968         errno = EINVAL;
1969       return 0;
1970     }
1971
1972   p = addresses;
1973   while (p)
1974     {
1975       if (strcmp (p->AdapterName, iface) == 0)
1976         {
1977           idx = p->IfIndex;
1978           break;
1979         }
1980       p = p->Next;
1981     }
1982
1983   if (p == NULL)
1984     errno = ENXIO;
1985
1986   g_free (addresses);
1987
1988   return idx;
1989 }
1990
1991 #define HAVE_IF_NAMETOINDEX 1
1992 #endif
1993
1994 static gboolean
1995 g_socket_multicast_group_operation (GSocket       *socket,
1996                                     GInetAddress  *group,
1997                                     gboolean       source_specific,
1998                                     const gchar   *iface,
1999                                     gboolean       join_group,
2000                                     GError       **error)
2001 {
2002   const guint8 *native_addr;
2003   gint optname, result;
2004
2005   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2006   g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2007   g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2008
2009   if (!check_socket (socket, error))
2010     return FALSE;
2011
2012   native_addr = g_inet_address_to_bytes (group);
2013   if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2014     {
2015 #ifdef HAVE_IP_MREQN
2016       struct ip_mreqn mc_req;
2017 #else
2018       struct ip_mreq mc_req;
2019 #endif
2020
2021       memset (&mc_req, 0, sizeof (mc_req));
2022       memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2023
2024 #ifdef HAVE_IP_MREQN
2025       if (iface)
2026         mc_req.imr_ifindex = if_nametoindex (iface);
2027       else
2028         mc_req.imr_ifindex = 0;  /* Pick any.  */
2029 #elif defined(G_OS_WIN32)
2030       if (iface)
2031         mc_req.imr_interface.s_addr = g_htonl (if_nametoindex (iface));
2032       else
2033         mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2034 #else
2035       mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2036 #endif
2037
2038       if (source_specific)
2039         {
2040 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2041           optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2042 #else
2043           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2044                        join_group ?
2045                        _("Error joining multicast group: %s") :
2046                        _("Error leaving multicast group: %s"),
2047                        _("No support for source-specific multicast"));
2048           return FALSE;
2049 #endif
2050         }
2051       else
2052         optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2053       result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2054                            &mc_req, sizeof (mc_req));
2055     }
2056   else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2057     {
2058       struct ipv6_mreq mc_req_ipv6;
2059
2060       memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2061       memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2062 #ifdef HAVE_IF_NAMETOINDEX
2063       if (iface)
2064         mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2065       else
2066 #endif
2067         mc_req_ipv6.ipv6mr_interface = 0;
2068
2069       optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2070       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2071                            &mc_req_ipv6, sizeof (mc_req_ipv6));
2072     }
2073   else
2074     g_return_val_if_reached (FALSE);
2075
2076   if (result < 0)
2077     {
2078       int errsv = get_socket_errno ();
2079
2080       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2081                    join_group ?
2082                    _("Error joining multicast group: %s") :
2083                    _("Error leaving multicast group: %s"),
2084                    socket_strerror (errsv));
2085       return FALSE;
2086     }
2087
2088   return TRUE;
2089 }
2090
2091 /**
2092  * g_socket_join_multicast_group:
2093  * @socket: a #GSocket.
2094  * @group: a #GInetAddress specifying the group address to join.
2095  * @iface: (allow-none): Name of the interface to use, or %NULL
2096  * @source_specific: %TRUE if source-specific multicast should be used
2097  * @error: #GError for error reporting, or %NULL to ignore.
2098  *
2099  * Registers @socket to receive multicast messages sent to @group.
2100  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2101  * been bound to an appropriate interface and port with
2102  * g_socket_bind().
2103  *
2104  * If @iface is %NULL, the system will automatically pick an interface
2105  * to bind to based on @group.
2106  *
2107  * If @source_specific is %TRUE, source-specific multicast as defined
2108  * in RFC 4604 is used. Note that on older platforms this may fail
2109  * with a %G_IO_ERROR_NOT_SUPPORTED error.
2110  *
2111  * Returns: %TRUE on success, %FALSE on error.
2112  *
2113  * Since: 2.32
2114  */
2115 gboolean
2116 g_socket_join_multicast_group (GSocket       *socket,
2117                                GInetAddress  *group,
2118                                gboolean       source_specific,
2119                                const gchar   *iface,
2120                                GError       **error)
2121 {
2122   return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2123 }
2124
2125 /**
2126  * g_socket_leave_multicast_group:
2127  * @socket: a #GSocket.
2128  * @group: a #GInetAddress specifying the group address to leave.
2129  * @iface: (allow-none): Interface used
2130  * @source_specific: %TRUE if source-specific multicast was used
2131  * @error: #GError for error reporting, or %NULL to ignore.
2132  *
2133  * Removes @socket from the multicast group defined by @group, @iface,
2134  * and @source_specific (which must all have the same values they had
2135  * when you joined the group).
2136  *
2137  * @socket remains bound to its address and port, and can still receive
2138  * unicast messages after calling this.
2139  *
2140  * Returns: %TRUE on success, %FALSE on error.
2141  *
2142  * Since: 2.32
2143  */
2144 gboolean
2145 g_socket_leave_multicast_group (GSocket       *socket,
2146                                 GInetAddress  *group,
2147                                 gboolean       source_specific,
2148                                 const gchar   *iface,
2149                                 GError       **error)
2150 {
2151   return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2152 }
2153
2154 /**
2155  * g_socket_speaks_ipv4:
2156  * @socket: a #GSocket
2157  *
2158  * Checks if a socket is capable of speaking IPv4.
2159  *
2160  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2161  * and under some combinations of circumstances IPv6 sockets are also
2162  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2163  * information.
2164  *
2165  * No other types of sockets are currently considered as being capable
2166  * of speaking IPv4.
2167  *
2168  * Returns: %TRUE if this socket can be used with IPv4.
2169  *
2170  * Since: 2.22
2171  **/
2172 gboolean
2173 g_socket_speaks_ipv4 (GSocket *socket)
2174 {
2175   switch (socket->priv->family)
2176     {
2177     case G_SOCKET_FAMILY_IPV4:
2178       return TRUE;
2179
2180     case G_SOCKET_FAMILY_IPV6:
2181 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2182       {
2183         gint v6_only;
2184
2185         if (!g_socket_get_option (socket,
2186                                   IPPROTO_IPV6, IPV6_V6ONLY,
2187                                   &v6_only, NULL))
2188           return FALSE;
2189
2190         return !v6_only;
2191       }
2192 #else
2193       return FALSE;
2194 #endif
2195
2196     default:
2197       return FALSE;
2198     }
2199 }
2200
2201 /**
2202  * g_socket_accept:
2203  * @socket: a #GSocket.
2204  * @cancellable: (allow-none): a %GCancellable or %NULL
2205  * @error: #GError for error reporting, or %NULL to ignore.
2206  *
2207  * Accept incoming connections on a connection-based socket. This removes
2208  * the first outstanding connection request from the listening socket and
2209  * creates a #GSocket object for it.
2210  *
2211  * The @socket must be bound to a local address with g_socket_bind() and
2212  * must be listening for incoming connections (g_socket_listen()).
2213  *
2214  * If there are no outstanding connections then the operation will block
2215  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2216  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2217  *
2218  * Returns: (transfer full): a new #GSocket, or %NULL on error.
2219  *     Free the returned object with g_object_unref().
2220  *
2221  * Since: 2.22
2222  */
2223 GSocket *
2224 g_socket_accept (GSocket       *socket,
2225                  GCancellable  *cancellable,
2226                  GError       **error)
2227 {
2228   GSocket *new_socket;
2229   gint ret;
2230
2231   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2232
2233   if (!check_socket (socket, error))
2234     return NULL;
2235
2236   while (TRUE)
2237     {
2238       if (socket->priv->blocking &&
2239           !g_socket_condition_wait (socket,
2240                                     G_IO_IN, cancellable, error))
2241         return NULL;
2242
2243       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2244         {
2245           int errsv = get_socket_errno ();
2246
2247           win32_unset_event_mask (socket, FD_ACCEPT);
2248
2249           if (errsv == EINTR)
2250             continue;
2251
2252           if (socket->priv->blocking)
2253             {
2254 #ifdef WSAEWOULDBLOCK
2255               if (errsv == WSAEWOULDBLOCK)
2256                 continue;
2257 #else
2258               if (errsv == EWOULDBLOCK ||
2259                   errsv == EAGAIN)
2260                 continue;
2261 #endif
2262             }
2263
2264           g_set_error (error, G_IO_ERROR,
2265                        socket_io_error_from_errno (errsv),
2266                        _("Error accepting connection: %s"), socket_strerror (errsv));
2267           return NULL;
2268         }
2269       break;
2270     }
2271
2272   win32_unset_event_mask (socket, FD_ACCEPT);
2273
2274 #ifdef G_OS_WIN32
2275   {
2276     /* The socket inherits the accepting sockets event mask and even object,
2277        we need to remove that */
2278     WSAEventSelect (ret, NULL, 0);
2279   }
2280 #else
2281   {
2282     int flags;
2283
2284     /* We always want to set close-on-exec to protect users. If you
2285        need to so some weird inheritance to exec you can re-enable this
2286        using lower level hacks with g_socket_get_fd(). */
2287     flags = fcntl (ret, F_GETFD, 0);
2288     if (flags != -1 &&
2289         (flags & FD_CLOEXEC) == 0)
2290       {
2291         flags |= FD_CLOEXEC;
2292         fcntl (ret, F_SETFD, flags);
2293       }
2294   }
2295 #endif
2296
2297   new_socket = g_socket_new_from_fd (ret, error);
2298   if (new_socket == NULL)
2299     {
2300 #ifdef G_OS_WIN32
2301       closesocket (ret);
2302 #else
2303       close (ret);
2304 #endif
2305     }
2306   else
2307     new_socket->priv->protocol = socket->priv->protocol;
2308
2309   return new_socket;
2310 }
2311
2312 /**
2313  * g_socket_connect:
2314  * @socket: a #GSocket.
2315  * @address: a #GSocketAddress specifying the remote address.
2316  * @cancellable: (allow-none): a %GCancellable or %NULL
2317  * @error: #GError for error reporting, or %NULL to ignore.
2318  *
2319  * Connect the socket to the specified remote address.
2320  *
2321  * For connection oriented socket this generally means we attempt to make
2322  * a connection to the @address. For a connection-less socket it sets
2323  * the default address for g_socket_send() and discards all incoming datagrams
2324  * from other sources.
2325  *
2326  * Generally connection oriented sockets can only connect once, but
2327  * connection-less sockets can connect multiple times to change the
2328  * default address.
2329  *
2330  * If the connect call needs to do network I/O it will block, unless
2331  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2332  * and the user can be notified of the connection finishing by waiting
2333  * for the G_IO_OUT condition. The result of the connection must then be
2334  * checked with g_socket_check_connect_result().
2335  *
2336  * Returns: %TRUE if connected, %FALSE on error.
2337  *
2338  * Since: 2.22
2339  */
2340 gboolean
2341 g_socket_connect (GSocket         *socket,
2342                   GSocketAddress  *address,
2343                   GCancellable    *cancellable,
2344                   GError         **error)
2345 {
2346   struct sockaddr_storage buffer;
2347
2348   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2349
2350   if (!check_socket (socket, error))
2351     return FALSE;
2352
2353   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2354     return FALSE;
2355
2356   if (socket->priv->remote_address)
2357     g_object_unref (socket->priv->remote_address);
2358   socket->priv->remote_address = g_object_ref (address);
2359
2360   while (1)
2361     {
2362       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2363                    g_socket_address_get_native_size (address)) < 0)
2364         {
2365           int errsv = get_socket_errno ();
2366
2367           if (errsv == EINTR)
2368             continue;
2369
2370 #ifndef G_OS_WIN32
2371           if (errsv == EINPROGRESS)
2372 #else
2373           if (errsv == WSAEWOULDBLOCK)
2374 #endif
2375             {
2376               if (socket->priv->blocking)
2377                 {
2378                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2379                     {
2380                       if (g_socket_check_connect_result (socket, error))
2381                         break;
2382                     }
2383                 }
2384               else
2385                 {
2386                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2387                                        _("Connection in progress"));
2388                   socket->priv->connect_pending = TRUE;
2389                 }
2390             }
2391           else
2392             g_set_error_literal (error, G_IO_ERROR,
2393                                  socket_io_error_from_errno (errsv),
2394                                  socket_strerror (errsv));
2395
2396           return FALSE;
2397         }
2398       break;
2399     }
2400
2401   win32_unset_event_mask (socket, FD_CONNECT);
2402
2403   socket->priv->connected = TRUE;
2404
2405   return TRUE;
2406 }
2407
2408 /**
2409  * g_socket_check_connect_result:
2410  * @socket: a #GSocket
2411  * @error: #GError for error reporting, or %NULL to ignore.
2412  *
2413  * Checks and resets the pending connect error for the socket.
2414  * This is used to check for errors when g_socket_connect() is
2415  * used in non-blocking mode.
2416  *
2417  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2418  *
2419  * Since: 2.22
2420  */
2421 gboolean
2422 g_socket_check_connect_result (GSocket  *socket,
2423                                GError  **error)
2424 {
2425   int value;
2426
2427   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2428
2429   if (!check_socket (socket, error))
2430     return FALSE;
2431
2432   if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
2433     {
2434       g_prefix_error (error, _("Unable to get pending error: "));
2435       return FALSE;
2436     }
2437
2438   if (value != 0)
2439     {
2440       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2441                            socket_strerror (value));
2442       if (socket->priv->remote_address)
2443         {
2444           g_object_unref (socket->priv->remote_address);
2445           socket->priv->remote_address = NULL;
2446         }
2447       return FALSE;
2448     }
2449
2450   socket->priv->connected = TRUE;
2451   return TRUE;
2452 }
2453
2454 /**
2455  * g_socket_get_available_bytes:
2456  * @socket: a #GSocket
2457  *
2458  * Get the amount of data pending in the OS input buffer.
2459  *
2460  * Returns: the number of bytes that can be read from the socket
2461  * without blocking or -1 on error.
2462  *
2463  * Since: 2.32
2464  */
2465 gssize
2466 g_socket_get_available_bytes (GSocket *socket)
2467 {
2468   gulong avail = 0;
2469
2470   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2471
2472 #ifndef G_OS_WIN32
2473   if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2474     return -1;
2475 #else
2476   if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2477     return -1;
2478 #endif
2479
2480   return avail;
2481 }
2482
2483 /**
2484  * g_socket_receive:
2485  * @socket: a #GSocket
2486  * @buffer: (array length=size) (element-type guint8): a buffer to
2487  *     read data into (which should be at least @size bytes long).
2488  * @size: the number of bytes you want to read from the socket
2489  * @cancellable: (allow-none): a %GCancellable or %NULL
2490  * @error: #GError for error reporting, or %NULL to ignore.
2491  *
2492  * Receive data (up to @size bytes) from a socket. This is mainly used by
2493  * connection-oriented sockets; it is identical to g_socket_receive_from()
2494  * with @address set to %NULL.
2495  *
2496  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2497  * g_socket_receive() will always read either 0 or 1 complete messages from
2498  * the socket. If the received message is too large to fit in @buffer, then
2499  * the data beyond @size bytes will be discarded, without any explicit
2500  * indication that this has occurred.
2501  *
2502  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2503  * number of bytes, up to @size. If more than @size bytes have been
2504  * received, the additional data will be returned in future calls to
2505  * g_socket_receive().
2506  *
2507  * If the socket is in blocking mode the call will block until there
2508  * is some data to receive, the connection is closed, or there is an
2509  * error. If there is no data available and the socket is in
2510  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2511  * returned. To be notified when data is available, wait for the
2512  * %G_IO_IN condition.
2513  *
2514  * On error -1 is returned and @error is set accordingly.
2515  *
2516  * Returns: Number of bytes read, or 0 if the connection was closed by
2517  * the peer, or -1 on error
2518  *
2519  * Since: 2.22
2520  */
2521 gssize
2522 g_socket_receive (GSocket       *socket,
2523                   gchar         *buffer,
2524                   gsize          size,
2525                   GCancellable  *cancellable,
2526                   GError       **error)
2527 {
2528   return g_socket_receive_with_blocking (socket, buffer, size,
2529                                          socket->priv->blocking,
2530                                          cancellable, error);
2531 }
2532
2533 /**
2534  * g_socket_receive_with_blocking:
2535  * @socket: a #GSocket
2536  * @buffer: (array length=size) (element-type guint8): a buffer to
2537  *     read data into (which should be at least @size bytes long).
2538  * @size: the number of bytes you want to read from the socket
2539  * @blocking: whether to do blocking or non-blocking I/O
2540  * @cancellable: (allow-none): a %GCancellable or %NULL
2541  * @error: #GError for error reporting, or %NULL to ignore.
2542  *
2543  * This behaves exactly the same as g_socket_receive(), except that
2544  * the choice of blocking or non-blocking behavior is determined by
2545  * the @blocking argument rather than by @socket's properties.
2546  *
2547  * Returns: Number of bytes read, or 0 if the connection was closed by
2548  * the peer, or -1 on error
2549  *
2550  * Since: 2.26
2551  */
2552 gssize
2553 g_socket_receive_with_blocking (GSocket       *socket,
2554                                 gchar         *buffer,
2555                                 gsize          size,
2556                                 gboolean       blocking,
2557                                 GCancellable  *cancellable,
2558                                 GError       **error)
2559 {
2560   gssize ret;
2561
2562   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2563
2564   if (!check_socket (socket, error))
2565     return -1;
2566
2567   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2568     return -1;
2569
2570   while (1)
2571     {
2572       if (blocking &&
2573           !g_socket_condition_wait (socket,
2574                                     G_IO_IN, cancellable, error))
2575         return -1;
2576
2577       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2578         {
2579           int errsv = get_socket_errno ();
2580
2581           if (errsv == EINTR)
2582             continue;
2583
2584           if (blocking)
2585             {
2586 #ifdef WSAEWOULDBLOCK
2587               if (errsv == WSAEWOULDBLOCK)
2588                 continue;
2589 #else
2590               if (errsv == EWOULDBLOCK ||
2591                   errsv == EAGAIN)
2592                 continue;
2593 #endif
2594             }
2595
2596           win32_unset_event_mask (socket, FD_READ);
2597
2598           g_set_error (error, G_IO_ERROR,
2599                        socket_io_error_from_errno (errsv),
2600                        _("Error receiving data: %s"), socket_strerror (errsv));
2601           return -1;
2602         }
2603
2604       win32_unset_event_mask (socket, FD_READ);
2605
2606       break;
2607     }
2608
2609   return ret;
2610 }
2611
2612 /**
2613  * g_socket_receive_from:
2614  * @socket: a #GSocket
2615  * @address: (out) (allow-none): a pointer to a #GSocketAddress
2616  *     pointer, or %NULL
2617  * @buffer: (array length=size) (element-type guint8): a buffer to
2618  *     read data into (which should be at least @size bytes long).
2619  * @size: the number of bytes you want to read from the socket
2620  * @cancellable: (allow-none): a %GCancellable or %NULL
2621  * @error: #GError for error reporting, or %NULL to ignore.
2622  *
2623  * Receive data (up to @size bytes) from a socket.
2624  *
2625  * If @address is non-%NULL then @address will be set equal to the
2626  * source address of the received packet.
2627  * @address is owned by the caller.
2628  *
2629  * See g_socket_receive() for additional information.
2630  *
2631  * Returns: Number of bytes read, or 0 if the connection was closed by
2632  * the peer, or -1 on error
2633  *
2634  * Since: 2.22
2635  */
2636 gssize
2637 g_socket_receive_from (GSocket         *socket,
2638                        GSocketAddress **address,
2639                        gchar           *buffer,
2640                        gsize            size,
2641                        GCancellable    *cancellable,
2642                        GError         **error)
2643 {
2644   GInputVector v;
2645
2646   v.buffer = buffer;
2647   v.size = size;
2648
2649   return g_socket_receive_message (socket,
2650                                    address,
2651                                    &v, 1,
2652                                    NULL, 0, NULL,
2653                                    cancellable,
2654                                    error);
2655 }
2656
2657 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2658  * one, which can be confusing and annoying. So if possible, we want
2659  * to suppress the signal entirely.
2660  */
2661 #ifdef MSG_NOSIGNAL
2662 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2663 #else
2664 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2665 #endif
2666
2667 /**
2668  * g_socket_send:
2669  * @socket: a #GSocket
2670  * @buffer: (array length=size) (element-type guint8): the buffer
2671  *     containing the data to send.
2672  * @size: the number of bytes to send
2673  * @cancellable: (allow-none): a %GCancellable or %NULL
2674  * @error: #GError for error reporting, or %NULL to ignore.
2675  *
2676  * Tries to send @size bytes from @buffer on the socket. This is
2677  * mainly used by connection-oriented sockets; it is identical to
2678  * g_socket_send_to() with @address set to %NULL.
2679  *
2680  * If the socket is in blocking mode the call will block until there is
2681  * space for the data in the socket queue. If there is no space available
2682  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2683  * will be returned. To be notified when space is available, wait for the
2684  * %G_IO_OUT condition. Note though that you may still receive
2685  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2686  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2687  * very common due to the way the underlying APIs work.)
2688  *
2689  * On error -1 is returned and @error is set accordingly.
2690  *
2691  * Returns: Number of bytes written (which may be less than @size), or -1
2692  * on error
2693  *
2694  * Since: 2.22
2695  */
2696 gssize
2697 g_socket_send (GSocket       *socket,
2698                const gchar   *buffer,
2699                gsize          size,
2700                GCancellable  *cancellable,
2701                GError       **error)
2702 {
2703   return g_socket_send_with_blocking (socket, buffer, size,
2704                                       socket->priv->blocking,
2705                                       cancellable, error);
2706 }
2707
2708 /**
2709  * g_socket_send_with_blocking:
2710  * @socket: a #GSocket
2711  * @buffer: (array length=size) (element-type guint8): the buffer
2712  *     containing the data to send.
2713  * @size: the number of bytes to send
2714  * @blocking: whether to do blocking or non-blocking I/O
2715  * @cancellable: (allow-none): a %GCancellable or %NULL
2716  * @error: #GError for error reporting, or %NULL to ignore.
2717  *
2718  * This behaves exactly the same as g_socket_send(), except that
2719  * the choice of blocking or non-blocking behavior is determined by
2720  * the @blocking argument rather than by @socket's properties.
2721  *
2722  * Returns: Number of bytes written (which may be less than @size), or -1
2723  * on error
2724  *
2725  * Since: 2.26
2726  */
2727 gssize
2728 g_socket_send_with_blocking (GSocket       *socket,
2729                              const gchar   *buffer,
2730                              gsize          size,
2731                              gboolean       blocking,
2732                              GCancellable  *cancellable,
2733                              GError       **error)
2734 {
2735   gssize ret;
2736
2737   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2738
2739   if (!check_socket (socket, error))
2740     return -1;
2741
2742   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2743     return -1;
2744
2745   while (1)
2746     {
2747       if (blocking &&
2748           !g_socket_condition_wait (socket,
2749                                     G_IO_OUT, cancellable, error))
2750         return -1;
2751
2752       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2753         {
2754           int errsv = get_socket_errno ();
2755
2756           if (errsv == EINTR)
2757             continue;
2758
2759 #ifdef WSAEWOULDBLOCK
2760           if (errsv == WSAEWOULDBLOCK)
2761             win32_unset_event_mask (socket, FD_WRITE);
2762 #endif
2763
2764           if (blocking)
2765             {
2766 #ifdef WSAEWOULDBLOCK
2767               if (errsv == WSAEWOULDBLOCK)
2768                 continue;
2769 #else
2770               if (errsv == EWOULDBLOCK ||
2771                   errsv == EAGAIN)
2772                 continue;
2773 #endif
2774             }
2775
2776           g_set_error (error, G_IO_ERROR,
2777                        socket_io_error_from_errno (errsv),
2778                        _("Error sending data: %s"), socket_strerror (errsv));
2779           return -1;
2780         }
2781       break;
2782     }
2783
2784   return ret;
2785 }
2786
2787 /**
2788  * g_socket_send_to:
2789  * @socket: a #GSocket
2790  * @address: (allow-none): a #GSocketAddress, or %NULL
2791  * @buffer: (array length=size) (element-type guint8): the buffer
2792  *     containing the data to send.
2793  * @size: the number of bytes to send
2794  * @cancellable: (allow-none): a %GCancellable or %NULL
2795  * @error: #GError for error reporting, or %NULL to ignore.
2796  *
2797  * Tries to send @size bytes from @buffer to @address. If @address is
2798  * %NULL then the message is sent to the default receiver (set by
2799  * g_socket_connect()).
2800  *
2801  * See g_socket_send() for additional information.
2802  *
2803  * Returns: Number of bytes written (which may be less than @size), or -1
2804  * on error
2805  *
2806  * Since: 2.22
2807  */
2808 gssize
2809 g_socket_send_to (GSocket         *socket,
2810                   GSocketAddress  *address,
2811                   const gchar     *buffer,
2812                   gsize            size,
2813                   GCancellable    *cancellable,
2814                   GError         **error)
2815 {
2816   GOutputVector v;
2817
2818   v.buffer = buffer;
2819   v.size = size;
2820
2821   return g_socket_send_message (socket,
2822                                 address,
2823                                 &v, 1,
2824                                 NULL, 0,
2825                                 0,
2826                                 cancellable,
2827                                 error);
2828 }
2829
2830 /**
2831  * g_socket_shutdown:
2832  * @socket: a #GSocket
2833  * @shutdown_read: whether to shut down the read side
2834  * @shutdown_write: whether to shut down the write side
2835  * @error: #GError for error reporting, or %NULL to ignore.
2836  *
2837  * Shut down part of a full-duplex connection.
2838  *
2839  * If @shutdown_read is %TRUE then the receiving side of the connection
2840  * is shut down, and further reading is disallowed.
2841  *
2842  * If @shutdown_write is %TRUE then the sending side of the connection
2843  * is shut down, and further writing is disallowed.
2844  *
2845  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2846  *
2847  * One example where this is used is graceful disconnect for TCP connections
2848  * where you close the sending side, then wait for the other side to close
2849  * the connection, thus ensuring that the other side saw all sent data.
2850  *
2851  * Returns: %TRUE on success, %FALSE on error
2852  *
2853  * Since: 2.22
2854  */
2855 gboolean
2856 g_socket_shutdown (GSocket   *socket,
2857                    gboolean   shutdown_read,
2858                    gboolean   shutdown_write,
2859                    GError   **error)
2860 {
2861   int how;
2862
2863   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2864
2865   if (!check_socket (socket, error))
2866     return FALSE;
2867
2868   /* Do nothing? */
2869   if (!shutdown_read && !shutdown_write)
2870     return TRUE;
2871
2872 #ifndef G_OS_WIN32
2873   if (shutdown_read && shutdown_write)
2874     how = SHUT_RDWR;
2875   else if (shutdown_read)
2876     how = SHUT_RD;
2877   else
2878     how = SHUT_WR;
2879 #else
2880   if (shutdown_read && shutdown_write)
2881     how = SD_BOTH;
2882   else if (shutdown_read)
2883     how = SD_RECEIVE;
2884   else
2885     how = SD_SEND;
2886 #endif
2887
2888   if (shutdown (socket->priv->fd, how) != 0)
2889     {
2890       int errsv = get_socket_errno ();
2891       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2892                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2893       return FALSE;
2894     }
2895
2896   if (shutdown_read && shutdown_write)
2897     socket->priv->connected = FALSE;
2898
2899   return TRUE;
2900 }
2901
2902 /**
2903  * g_socket_close:
2904  * @socket: a #GSocket
2905  * @error: #GError for error reporting, or %NULL to ignore.
2906  *
2907  * Closes the socket, shutting down any active connection.
2908  *
2909  * Closing a socket does not wait for all outstanding I/O operations
2910  * to finish, so the caller should not rely on them to be guaranteed
2911  * to complete even if the close returns with no error.
2912  *
2913  * Once the socket is closed, all other operations will return
2914  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2915  * return an error.
2916  *
2917  * Sockets will be automatically closed when the last reference
2918  * is dropped, but you might want to call this function to make sure
2919  * resources are released as early as possible.
2920  *
2921  * Beware that due to the way that TCP works, it is possible for
2922  * recently-sent data to be lost if either you close a socket while the
2923  * %G_IO_IN condition is set, or else if the remote connection tries to
2924  * send something to you after you close the socket but before it has
2925  * finished reading all of the data you sent. There is no easy generic
2926  * way to avoid this problem; the easiest fix is to design the network
2927  * protocol such that the client will never send data "out of turn".
2928  * Another solution is for the server to half-close the connection by
2929  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2930  * and then wait for the client to notice this and close its side of the
2931  * connection, after which the server can safely call g_socket_close().
2932  * (This is what #GTcpConnection does if you call
2933  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2934  * only works if the client will close its connection after the server
2935  * does.)
2936  *
2937  * Returns: %TRUE on success, %FALSE on error
2938  *
2939  * Since: 2.22
2940  */
2941 gboolean
2942 g_socket_close (GSocket  *socket,
2943                 GError  **error)
2944 {
2945   int res;
2946
2947   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2948
2949   if (socket->priv->closed)
2950     return TRUE; /* Multiple close not an error */
2951
2952   if (!check_socket (socket, error))
2953     return FALSE;
2954
2955   while (1)
2956     {
2957 #ifdef G_OS_WIN32
2958       res = closesocket (socket->priv->fd);
2959 #else
2960       res = close (socket->priv->fd);
2961 #endif
2962       if (res == -1)
2963         {
2964           int errsv = get_socket_errno ();
2965
2966           if (errsv == EINTR)
2967             continue;
2968
2969           g_set_error (error, G_IO_ERROR,
2970                        socket_io_error_from_errno (errsv),
2971                        _("Error closing socket: %s"),
2972                        socket_strerror (errsv));
2973           return FALSE;
2974         }
2975       break;
2976     }
2977
2978   socket->priv->connected = FALSE;
2979   socket->priv->closed = TRUE;
2980   if (socket->priv->remote_address)
2981     {
2982       g_object_unref (socket->priv->remote_address);
2983       socket->priv->remote_address = NULL;
2984     }
2985
2986   return TRUE;
2987 }
2988
2989 /**
2990  * g_socket_is_closed:
2991  * @socket: a #GSocket
2992  *
2993  * Checks whether a socket is closed.
2994  *
2995  * Returns: %TRUE if socket is closed, %FALSE otherwise
2996  *
2997  * Since: 2.22
2998  */
2999 gboolean
3000 g_socket_is_closed (GSocket *socket)
3001 {
3002   return socket->priv->closed;
3003 }
3004
3005 #ifdef G_OS_WIN32
3006 /* Broken source, used on errors */
3007 static gboolean
3008 broken_dispatch (GSource     *source,
3009                  GSourceFunc  callback,
3010                  gpointer     user_data)
3011 {
3012   return TRUE;
3013 }
3014
3015 static GSourceFuncs broken_funcs =
3016 {
3017   NULL,
3018   NULL,
3019   broken_dispatch,
3020   NULL
3021 };
3022
3023 static gint
3024 network_events_for_condition (GIOCondition condition)
3025 {
3026   int event_mask = 0;
3027
3028   if (condition & G_IO_IN)
3029     event_mask |= (FD_READ | FD_ACCEPT);
3030   if (condition & G_IO_OUT)
3031     event_mask |= (FD_WRITE | FD_CONNECT);
3032   event_mask |= FD_CLOSE;
3033
3034   return event_mask;
3035 }
3036
3037 static void
3038 ensure_event (GSocket *socket)
3039 {
3040   if (socket->priv->event == WSA_INVALID_EVENT)
3041     socket->priv->event = WSACreateEvent();
3042 }
3043
3044 static void
3045 update_select_events (GSocket *socket)
3046 {
3047   int event_mask;
3048   GIOCondition *ptr;
3049   GList *l;
3050   WSAEVENT event;
3051
3052   ensure_event (socket);
3053
3054   event_mask = 0;
3055   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3056     {
3057       ptr = l->data;
3058       event_mask |= network_events_for_condition (*ptr);
3059     }
3060
3061   if (event_mask != socket->priv->selected_events)
3062     {
3063       /* If no events selected, disable event so we can unset
3064          nonblocking mode */
3065
3066       if (event_mask == 0)
3067         event = NULL;
3068       else
3069         event = socket->priv->event;
3070
3071       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3072         socket->priv->selected_events = event_mask;
3073     }
3074 }
3075
3076 static void
3077 add_condition_watch (GSocket      *socket,
3078                      GIOCondition *condition)
3079 {
3080   g_mutex_lock (&socket->priv->win32_source_lock);
3081   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3082
3083   socket->priv->requested_conditions =
3084     g_list_prepend (socket->priv->requested_conditions, condition);
3085
3086   update_select_events (socket);
3087   g_mutex_unlock (&socket->priv->win32_source_lock);
3088 }
3089
3090 static void
3091 remove_condition_watch (GSocket      *socket,
3092                         GIOCondition *condition)
3093 {
3094   g_mutex_lock (&socket->priv->win32_source_lock);
3095   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3096
3097   socket->priv->requested_conditions =
3098     g_list_remove (socket->priv->requested_conditions, condition);
3099
3100   update_select_events (socket);
3101   g_mutex_unlock (&socket->priv->win32_source_lock);
3102 }
3103
3104 static GIOCondition
3105 update_condition (GSocket *socket)
3106 {
3107   WSANETWORKEVENTS events;
3108   GIOCondition condition;
3109
3110   if (WSAEnumNetworkEvents (socket->priv->fd,
3111                             socket->priv->event,
3112                             &events) == 0)
3113     {
3114       socket->priv->current_events |= events.lNetworkEvents;
3115       if (events.lNetworkEvents & FD_WRITE &&
3116           events.iErrorCode[FD_WRITE_BIT] != 0)
3117         socket->priv->current_errors |= FD_WRITE;
3118       if (events.lNetworkEvents & FD_CONNECT &&
3119           events.iErrorCode[FD_CONNECT_BIT] != 0)
3120         socket->priv->current_errors |= FD_CONNECT;
3121     }
3122
3123   condition = 0;
3124   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3125     condition |= G_IO_IN;
3126
3127   if (socket->priv->current_events & FD_CLOSE)
3128     {
3129       int r, errsv, buffer;
3130
3131       r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3132       if (r < 0)
3133           errsv = get_socket_errno ();
3134
3135       if (r > 0 ||
3136           (r < 0 && errsv == WSAENOTCONN))
3137         condition |= G_IO_IN;
3138       else if (r == 0 ||
3139                (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3140                           errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3141         condition |= G_IO_HUP;
3142       else
3143         condition |= G_IO_ERR;
3144     }
3145
3146   if (socket->priv->closed)
3147     condition |= G_IO_HUP;
3148
3149   /* Never report both G_IO_OUT and HUP, these are
3150      mutually exclusive (can't write to a closed socket) */
3151   if ((condition & G_IO_HUP) == 0 &&
3152       socket->priv->current_events & FD_WRITE)
3153     {
3154       if (socket->priv->current_errors & FD_WRITE)
3155         condition |= G_IO_ERR;
3156       else
3157         condition |= G_IO_OUT;
3158     }
3159   else
3160     {
3161       if (socket->priv->current_events & FD_CONNECT)
3162         {
3163           if (socket->priv->current_errors & FD_CONNECT)
3164             condition |= (G_IO_HUP | G_IO_ERR);
3165           else
3166             condition |= G_IO_OUT;
3167         }
3168     }
3169
3170   return condition;
3171 }
3172 #endif
3173
3174 typedef struct {
3175   GSource       source;
3176   GPollFD       pollfd;
3177   GSocket      *socket;
3178   GIOCondition  condition;
3179   GCancellable *cancellable;
3180   GPollFD       cancel_pollfd;
3181   gint64        timeout_time;
3182 } GSocketSource;
3183
3184 static gboolean
3185 socket_source_prepare (GSource *source,
3186                        gint    *timeout)
3187 {
3188   GSocketSource *socket_source = (GSocketSource *)source;
3189
3190   if (g_cancellable_is_cancelled (socket_source->cancellable))
3191     return TRUE;
3192
3193   if (socket_source->timeout_time)
3194     {
3195       gint64 now;
3196
3197       now = g_source_get_time (source);
3198       /* Round up to ensure that we don't try again too early */
3199       *timeout = (socket_source->timeout_time - now + 999) / 1000;
3200       if (*timeout < 0)
3201         {
3202           socket_source->socket->priv->timed_out = TRUE;
3203           *timeout = 0;
3204           return TRUE;
3205         }
3206     }
3207   else
3208     *timeout = -1;
3209
3210 #ifdef G_OS_WIN32
3211   socket_source->pollfd.revents = update_condition (socket_source->socket);
3212 #endif
3213
3214   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3215     return TRUE;
3216
3217   return FALSE;
3218 }
3219
3220 static gboolean
3221 socket_source_check (GSource *source)
3222 {
3223   int timeout;
3224
3225   return socket_source_prepare (source, &timeout);
3226 }
3227
3228 static gboolean
3229 socket_source_dispatch (GSource     *source,
3230                         GSourceFunc  callback,
3231                         gpointer     user_data)
3232 {
3233   GSocketSourceFunc func = (GSocketSourceFunc)callback;
3234   GSocketSource *socket_source = (GSocketSource *)source;
3235   GSocket *socket = socket_source->socket;
3236   gboolean ret;
3237
3238 #ifdef G_OS_WIN32
3239   socket_source->pollfd.revents = update_condition (socket_source->socket);
3240 #endif
3241   if (socket_source->socket->priv->timed_out)
3242     socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3243
3244   ret = (*func) (socket,
3245                  socket_source->pollfd.revents & socket_source->condition,
3246                  user_data);
3247
3248   if (socket->priv->timeout)
3249     socket_source->timeout_time = g_get_monotonic_time () +
3250                                   socket->priv->timeout * 1000000;
3251
3252   else
3253     socket_source->timeout_time = 0;
3254
3255   return ret;
3256 }
3257
3258 static void
3259 socket_source_finalize (GSource *source)
3260 {
3261   GSocketSource *socket_source = (GSocketSource *)source;
3262   GSocket *socket;
3263
3264   socket = socket_source->socket;
3265
3266 #ifdef G_OS_WIN32
3267   remove_condition_watch (socket, &socket_source->condition);
3268 #endif
3269
3270   g_object_unref (socket);
3271
3272   if (socket_source->cancellable)
3273     {
3274       g_cancellable_release_fd (socket_source->cancellable);
3275       g_object_unref (socket_source->cancellable);
3276     }
3277 }
3278
3279 static gboolean
3280 socket_source_closure_callback (GSocket      *socket,
3281                                 GIOCondition  condition,
3282                                 gpointer      data)
3283 {
3284   GClosure *closure = data;
3285
3286   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3287   GValue result_value = G_VALUE_INIT;
3288   gboolean result;
3289
3290   g_value_init (&result_value, G_TYPE_BOOLEAN);
3291
3292   g_value_init (&params[0], G_TYPE_SOCKET);
3293   g_value_set_object (&params[0], socket);
3294   g_value_init (&params[1], G_TYPE_IO_CONDITION);
3295   g_value_set_flags (&params[1], condition);
3296
3297   g_closure_invoke (closure, &result_value, 2, params, NULL);
3298
3299   result = g_value_get_boolean (&result_value);
3300   g_value_unset (&result_value);
3301   g_value_unset (&params[0]);
3302   g_value_unset (&params[1]);
3303
3304   return result;
3305 }
3306
3307 static GSourceFuncs socket_source_funcs =
3308 {
3309   socket_source_prepare,
3310   socket_source_check,
3311   socket_source_dispatch,
3312   socket_source_finalize,
3313   (GSourceFunc)socket_source_closure_callback,
3314 };
3315
3316 static GSource *
3317 socket_source_new (GSocket      *socket,
3318                    GIOCondition  condition,
3319                    GCancellable *cancellable)
3320 {
3321   GSource *source;
3322   GSocketSource *socket_source;
3323
3324 #ifdef G_OS_WIN32
3325   ensure_event (socket);
3326
3327   if (socket->priv->event == WSA_INVALID_EVENT)
3328     {
3329       g_warning ("Failed to create WSAEvent");
3330       return g_source_new (&broken_funcs, sizeof (GSource));
3331     }
3332 #endif
3333
3334   condition |= G_IO_HUP | G_IO_ERR;
3335
3336   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3337   g_source_set_name (source, "GSocket");
3338   socket_source = (GSocketSource *)source;
3339
3340   socket_source->socket = g_object_ref (socket);
3341   socket_source->condition = condition;
3342
3343   if (g_cancellable_make_pollfd (cancellable,
3344                                  &socket_source->cancel_pollfd))
3345     {
3346       socket_source->cancellable = g_object_ref (cancellable);
3347       g_source_add_poll (source, &socket_source->cancel_pollfd);
3348     }
3349
3350 #ifdef G_OS_WIN32
3351   add_condition_watch (socket, &socket_source->condition);
3352   socket_source->pollfd.fd = (gintptr) socket->priv->event;
3353 #else
3354   socket_source->pollfd.fd = socket->priv->fd;
3355 #endif
3356
3357   socket_source->pollfd.events = condition;
3358   socket_source->pollfd.revents = 0;
3359   g_source_add_poll (source, &socket_source->pollfd);
3360
3361   if (socket->priv->timeout)
3362     socket_source->timeout_time = g_get_monotonic_time () +
3363                                   socket->priv->timeout * 1000000;
3364
3365   else
3366     socket_source->timeout_time = 0;
3367
3368   return source;
3369 }
3370
3371 /**
3372  * g_socket_create_source: (skip)
3373  * @socket: a #GSocket
3374  * @condition: a #GIOCondition mask to monitor
3375  * @cancellable: (allow-none): a %GCancellable or %NULL
3376  *
3377  * Creates a %GSource that can be attached to a %GMainContext to monitor
3378  * for the availibility of the specified @condition on the socket.
3379  *
3380  * The callback on the source is of the #GSocketSourceFunc type.
3381  *
3382  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3383  * these conditions will always be reported output if they are true.
3384  *
3385  * @cancellable if not %NULL can be used to cancel the source, which will
3386  * cause the source to trigger, reporting the current condition (which
3387  * is likely 0 unless cancellation happened at the same time as a
3388  * condition change). You can check for this in the callback using
3389  * g_cancellable_is_cancelled().
3390  *
3391  * If @socket has a timeout set, and it is reached before @condition
3392  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3393  * %G_IO_OUT depending on @condition. However, @socket will have been
3394  * marked as having had a timeout, and so the next #GSocket I/O method
3395  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3396  *
3397  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3398  *
3399  * Since: 2.22
3400  */
3401 GSource *
3402 g_socket_create_source (GSocket      *socket,
3403                         GIOCondition  condition,
3404                         GCancellable *cancellable)
3405 {
3406   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3407
3408   return socket_source_new (socket, condition, cancellable);
3409 }
3410
3411 /**
3412  * g_socket_condition_check:
3413  * @socket: a #GSocket
3414  * @condition: a #GIOCondition mask to check
3415  *
3416  * Checks on the readiness of @socket to perform operations.
3417  * The operations specified in @condition are checked for and masked
3418  * against the currently-satisfied conditions on @socket. The result
3419  * is returned.
3420  *
3421  * Note that on Windows, it is possible for an operation to return
3422  * %G_IO_ERROR_WOULD_BLOCK even immediately after
3423  * g_socket_condition_check() has claimed that the socket is ready for
3424  * writing. Rather than calling g_socket_condition_check() and then
3425  * writing to the socket if it succeeds, it is generally better to
3426  * simply try writing to the socket right away, and try again later if
3427  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3428  *
3429  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3430  * these conditions will always be set in the output if they are true.
3431  *
3432  * This call never blocks.
3433  *
3434  * Returns: the @GIOCondition mask of the current state
3435  *
3436  * Since: 2.22
3437  */
3438 GIOCondition
3439 g_socket_condition_check (GSocket      *socket,
3440                           GIOCondition  condition)
3441 {
3442   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3443
3444   if (!check_socket (socket, NULL))
3445     return 0;
3446
3447 #ifdef G_OS_WIN32
3448   {
3449     GIOCondition current_condition;
3450
3451     condition |= G_IO_ERR | G_IO_HUP;
3452
3453     add_condition_watch (socket, &condition);
3454     current_condition = update_condition (socket);
3455     remove_condition_watch (socket, &condition);
3456     return condition & current_condition;
3457   }
3458 #else
3459   {
3460     GPollFD poll_fd;
3461     gint result;
3462     poll_fd.fd = socket->priv->fd;
3463     poll_fd.events = condition;
3464     poll_fd.revents = 0;
3465
3466     do
3467       result = g_poll (&poll_fd, 1, 0);
3468     while (result == -1 && get_socket_errno () == EINTR);
3469
3470     return poll_fd.revents;
3471   }
3472 #endif
3473 }
3474
3475 /**
3476  * g_socket_condition_wait:
3477  * @socket: a #GSocket
3478  * @condition: a #GIOCondition mask to wait for
3479  * @cancellable: (allow-none): a #GCancellable, or %NULL
3480  * @error: a #GError pointer, or %NULL
3481  *
3482  * Waits for @condition to become true on @socket. When the condition
3483  * is met, %TRUE is returned.
3484  *
3485  * If @cancellable is cancelled before the condition is met, or if the
3486  * socket has a timeout set and it is reached before the condition is
3487  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3488  * the appropriate value (%G_IO_ERROR_CANCELLED or
3489  * %G_IO_ERROR_TIMED_OUT).
3490  *
3491  * See also g_socket_condition_timed_wait().
3492  *
3493  * Returns: %TRUE if the condition was met, %FALSE otherwise
3494  *
3495  * Since: 2.22
3496  */
3497 gboolean
3498 g_socket_condition_wait (GSocket       *socket,
3499                          GIOCondition   condition,
3500                          GCancellable  *cancellable,
3501                          GError       **error)
3502 {
3503   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3504
3505   return g_socket_condition_timed_wait (socket, condition, -1,
3506                                         cancellable, error);
3507 }
3508
3509 /**
3510  * g_socket_condition_timed_wait:
3511  * @socket: a #GSocket
3512  * @condition: a #GIOCondition mask to wait for
3513  * @timeout: the maximum time (in microseconds) to wait, or -1
3514  * @cancellable: (allow-none): a #GCancellable, or %NULL
3515  * @error: a #GError pointer, or %NULL
3516  *
3517  * Waits for up to @timeout microseconds for @condition to become true
3518  * on @socket. If the condition is met, %TRUE is returned.
3519  *
3520  * If @cancellable is cancelled before the condition is met, or if
3521  * @timeout (or the socket's #GSocket:timeout) is reached before the
3522  * condition is met, then %FALSE is returned and @error, if non-%NULL,
3523  * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3524  * %G_IO_ERROR_TIMED_OUT).
3525  *
3526  * If you don't want a timeout, use g_socket_condition_wait().
3527  * (Alternatively, you can pass -1 for @timeout.)
3528  *
3529  * Note that although @timeout is in microseconds for consistency with
3530  * other GLib APIs, this function actually only has millisecond
3531  * resolution, and the behavior is undefined if @timeout is not an
3532  * exact number of milliseconds.
3533  *
3534  * Returns: %TRUE if the condition was met, %FALSE otherwise
3535  *
3536  * Since: 2.32
3537  */
3538 gboolean
3539 g_socket_condition_timed_wait (GSocket       *socket,
3540                                GIOCondition   condition,
3541                                gint64         timeout,
3542                                GCancellable  *cancellable,
3543                                GError       **error)
3544 {
3545   gint64 start_time;
3546
3547   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3548
3549   if (!check_socket (socket, error))
3550     return FALSE;
3551
3552   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3553     return FALSE;
3554
3555   if (socket->priv->timeout &&
3556       (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3557     timeout = socket->priv->timeout * 1000;
3558   else if (timeout != -1)
3559     timeout = timeout / 1000;
3560
3561   start_time = g_get_monotonic_time ();
3562
3563 #ifdef G_OS_WIN32
3564   {
3565     GIOCondition current_condition;
3566     WSAEVENT events[2];
3567     DWORD res;
3568     GPollFD cancel_fd;
3569     int num_events;
3570
3571     /* Always check these */
3572     condition |=  G_IO_ERR | G_IO_HUP;
3573
3574     add_condition_watch (socket, &condition);
3575
3576     num_events = 0;
3577     events[num_events++] = socket->priv->event;
3578
3579     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3580       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3581
3582     if (timeout == -1)
3583       timeout = WSA_INFINITE;
3584
3585     current_condition = update_condition (socket);
3586     while ((condition & current_condition) == 0)
3587       {
3588         res = WSAWaitForMultipleEvents (num_events, events,
3589                                         FALSE, timeout, FALSE);
3590         if (res == WSA_WAIT_FAILED)
3591           {
3592             int errsv = get_socket_errno ();
3593
3594             g_set_error (error, G_IO_ERROR,
3595                          socket_io_error_from_errno (errsv),
3596                          _("Waiting for socket condition: %s"),
3597                          socket_strerror (errsv));
3598             break;
3599           }
3600         else if (res == WSA_WAIT_TIMEOUT)
3601           {
3602             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3603                                  _("Socket I/O timed out"));
3604             break;
3605           }
3606
3607         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3608           break;
3609
3610         current_condition = update_condition (socket);
3611
3612         if (timeout != WSA_INFINITE)
3613           {
3614             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3615             if (timeout < 0)
3616               timeout = 0;
3617           }
3618       }
3619     remove_condition_watch (socket, &condition);
3620     if (num_events > 1)
3621       g_cancellable_release_fd (cancellable);
3622
3623     return (condition & current_condition) != 0;
3624   }
3625 #else
3626   {
3627     GPollFD poll_fd[2];
3628     gint result;
3629     gint num;
3630
3631     poll_fd[0].fd = socket->priv->fd;
3632     poll_fd[0].events = condition;
3633     num = 1;
3634
3635     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3636       num++;
3637
3638     while (TRUE)
3639       {
3640         result = g_poll (poll_fd, num, timeout);
3641         if (result != -1 || errno != EINTR)
3642           break;
3643
3644         if (timeout != -1)
3645           {
3646             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3647             if (timeout < 0)
3648               timeout = 0;
3649           }
3650       }
3651     
3652     if (num > 1)
3653       g_cancellable_release_fd (cancellable);
3654
3655     if (result == 0)
3656       {
3657         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3658                              _("Socket I/O timed out"));
3659         return FALSE;
3660       }
3661
3662     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3663   }
3664   #endif
3665 }
3666
3667 /**
3668  * g_socket_send_message:
3669  * @socket: a #GSocket
3670  * @address: (allow-none): a #GSocketAddress, or %NULL
3671  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3672  * @num_vectors: the number of elements in @vectors, or -1
3673  * @messages: (array length=num_messages) (allow-none): a pointer to an
3674  *   array of #GSocketControlMessages, or %NULL.
3675  * @num_messages: number of elements in @messages, or -1.
3676  * @flags: an int containing #GSocketMsgFlags flags
3677  * @cancellable: (allow-none): a %GCancellable or %NULL
3678  * @error: #GError for error reporting, or %NULL to ignore.
3679  *
3680  * Send data to @address on @socket.  This is the most complicated and
3681  * fully-featured version of this call. For easier use, see
3682  * g_socket_send() and g_socket_send_to().
3683  *
3684  * If @address is %NULL then the message is sent to the default receiver
3685  * (set by g_socket_connect()).
3686  *
3687  * @vectors must point to an array of #GOutputVector structs and
3688  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3689  * then @vectors is assumed to be terminated by a #GOutputVector with a
3690  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3691  * that the sent data will be gathered from. Using multiple
3692  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3693  * data from multiple sources into a single buffer, and more
3694  * network-efficient than making multiple calls to g_socket_send().
3695  *
3696  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3697  * #GSocketControlMessage instances. These correspond to the control
3698  * messages to be sent on the socket.
3699  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3700  * array.
3701  *
3702  * @flags modify how the message is sent. The commonly available arguments
3703  * for this are available in the #GSocketMsgFlags enum, but the
3704  * values there are the same as the system values, and the flags
3705  * are passed in as-is, so you can pass in system-specific flags too.
3706  *
3707  * If the socket is in blocking mode the call will block until there is
3708  * space for the data in the socket queue. If there is no space available
3709  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3710  * will be returned. To be notified when space is available, wait for the
3711  * %G_IO_OUT condition. Note though that you may still receive
3712  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3713  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3714  * very common due to the way the underlying APIs work.)
3715  *
3716  * On error -1 is returned and @error is set accordingly.
3717  *
3718  * Returns: Number of bytes written (which may be less than @size), or -1
3719  * on error
3720  *
3721  * Since: 2.22
3722  */
3723 gssize
3724 g_socket_send_message (GSocket                *socket,
3725                        GSocketAddress         *address,
3726                        GOutputVector          *vectors,
3727                        gint                    num_vectors,
3728                        GSocketControlMessage **messages,
3729                        gint                    num_messages,
3730                        gint                    flags,
3731                        GCancellable           *cancellable,
3732                        GError                **error)
3733 {
3734   GOutputVector one_vector;
3735   char zero;
3736
3737   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3738
3739   if (!check_socket (socket, error))
3740     return -1;
3741
3742   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3743     return -1;
3744
3745   if (num_vectors == -1)
3746     {
3747       for (num_vectors = 0;
3748            vectors[num_vectors].buffer != NULL;
3749            num_vectors++)
3750         ;
3751     }
3752
3753   if (num_messages == -1)
3754     {
3755       for (num_messages = 0;
3756            messages != NULL && messages[num_messages] != NULL;
3757            num_messages++)
3758         ;
3759     }
3760
3761   if (num_vectors == 0)
3762     {
3763       zero = '\0';
3764
3765       one_vector.buffer = &zero;
3766       one_vector.size = 1;
3767       num_vectors = 1;
3768       vectors = &one_vector;
3769     }
3770
3771 #ifndef G_OS_WIN32
3772   {
3773     struct msghdr msg;
3774     gssize result;
3775
3776    msg.msg_flags = 0;
3777
3778     /* name */
3779     if (address)
3780       {
3781         msg.msg_namelen = g_socket_address_get_native_size (address);
3782         msg.msg_name = g_alloca (msg.msg_namelen);
3783         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3784           return -1;
3785       }
3786     else
3787       {
3788         msg.msg_name = NULL;
3789         msg.msg_namelen = 0;
3790       }
3791
3792     /* iov */
3793     {
3794       /* this entire expression will be evaluated at compile time */
3795       if (sizeof *msg.msg_iov == sizeof *vectors &&
3796           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3797           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3798           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3799           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3800           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3801           G_STRUCT_OFFSET (GOutputVector, size))
3802         /* ABI is compatible */
3803         {
3804           msg.msg_iov = (struct iovec *) vectors;
3805           msg.msg_iovlen = num_vectors;
3806         }
3807       else
3808         /* ABI is incompatible */
3809         {
3810           gint i;
3811
3812           msg.msg_iov = g_newa (struct iovec, num_vectors);
3813           for (i = 0; i < num_vectors; i++)
3814             {
3815               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3816               msg.msg_iov[i].iov_len = vectors[i].size;
3817             }
3818           msg.msg_iovlen = num_vectors;
3819         }
3820     }
3821
3822     /* control */
3823     {
3824       struct cmsghdr *cmsg;
3825       gint i;
3826
3827       msg.msg_controllen = 0;
3828       for (i = 0; i < num_messages; i++)
3829         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3830
3831       if (msg.msg_controllen == 0)
3832         msg.msg_control = NULL;
3833       else
3834         {
3835           msg.msg_control = g_alloca (msg.msg_controllen);
3836           memset (msg.msg_control, '\0', msg.msg_controllen);
3837         }
3838
3839       cmsg = CMSG_FIRSTHDR (&msg);
3840       for (i = 0; i < num_messages; i++)
3841         {
3842           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3843           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3844           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3845           g_socket_control_message_serialize (messages[i],
3846                                               CMSG_DATA (cmsg));
3847           cmsg = CMSG_NXTHDR (&msg, cmsg);
3848         }
3849       g_assert (cmsg == NULL);
3850     }
3851
3852     while (1)
3853       {
3854         if (socket->priv->blocking &&
3855             !g_socket_condition_wait (socket,
3856                                       G_IO_OUT, cancellable, error))
3857           return -1;
3858
3859         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3860         if (result < 0)
3861           {
3862             int errsv = get_socket_errno ();
3863
3864             if (errsv == EINTR)
3865               continue;
3866
3867             if (socket->priv->blocking &&
3868                 (errsv == EWOULDBLOCK ||
3869                  errsv == EAGAIN))
3870               continue;
3871
3872             g_set_error (error, G_IO_ERROR,
3873                          socket_io_error_from_errno (errsv),
3874                          _("Error sending message: %s"), socket_strerror (errsv));
3875
3876             return -1;
3877           }
3878         break;
3879       }
3880
3881     return result;
3882   }
3883 #else
3884   {
3885     struct sockaddr_storage addr;
3886     guint addrlen;
3887     DWORD bytes_sent;
3888     int result;
3889     WSABUF *bufs;
3890     gint i;
3891
3892     /* Win32 doesn't support control messages.
3893        Actually this is possible for raw and datagram sockets
3894        via WSASendMessage on Vista or later, but that doesn't
3895        seem very useful */
3896     if (num_messages != 0)
3897       {
3898         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3899                              _("GSocketControlMessage not supported on Windows"));
3900         return -1;
3901       }
3902
3903     /* iov */
3904     bufs = g_newa (WSABUF, num_vectors);
3905     for (i = 0; i < num_vectors; i++)
3906       {
3907         bufs[i].buf = (char *)vectors[i].buffer;
3908         bufs[i].len = (gulong)vectors[i].size;
3909       }
3910
3911     /* name */
3912     addrlen = 0; /* Avoid warning */
3913     if (address)
3914       {
3915         addrlen = g_socket_address_get_native_size (address);
3916         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3917           return -1;
3918       }
3919
3920     while (1)
3921       {
3922         if (socket->priv->blocking &&
3923             !g_socket_condition_wait (socket,
3924                                       G_IO_OUT, cancellable, error))
3925           return -1;
3926
3927         if (address)
3928           result = WSASendTo (socket->priv->fd,
3929                               bufs, num_vectors,
3930                               &bytes_sent, flags,
3931                               (const struct sockaddr *)&addr, addrlen,
3932                               NULL, NULL);
3933         else
3934           result = WSASend (socket->priv->fd,
3935                             bufs, num_vectors,
3936                             &bytes_sent, flags,
3937                             NULL, NULL);
3938
3939         if (result != 0)
3940           {
3941             int errsv = get_socket_errno ();
3942
3943             if (errsv == WSAEINTR)
3944               continue;
3945
3946             if (errsv == WSAEWOULDBLOCK)
3947               win32_unset_event_mask (socket, FD_WRITE);
3948
3949             if (socket->priv->blocking &&
3950                 errsv == WSAEWOULDBLOCK)
3951               continue;
3952
3953             g_set_error (error, G_IO_ERROR,
3954                          socket_io_error_from_errno (errsv),
3955                          _("Error sending message: %s"), socket_strerror (errsv));
3956
3957             return -1;
3958           }
3959         break;
3960       }
3961
3962     return bytes_sent;
3963   }
3964 #endif
3965 }
3966
3967 static GSocketAddress *
3968 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3969 {
3970   GSocketAddress *saddr;
3971   gint i;
3972   guint64 oldest_time = G_MAXUINT64;
3973   gint oldest_index = 0;
3974
3975   if (native_len <= 0)
3976     return NULL;
3977
3978   saddr = NULL;
3979   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3980     {
3981       GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3982       gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3983       gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3984
3985       if (!tmp)
3986         continue;
3987
3988       if (tmp_native_len != native_len)
3989         continue;
3990
3991       if (memcmp (tmp_native, native, native_len) == 0)
3992         {
3993           saddr = g_object_ref (tmp);
3994           socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
3995           return saddr;
3996         }
3997
3998       if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
3999         {
4000           oldest_time = socket->priv->recv_addr_cache[i].last_used;
4001           oldest_index = i;
4002         }
4003     }
4004
4005   saddr = g_socket_address_new_from_native (native, native_len);
4006
4007   if (socket->priv->recv_addr_cache[oldest_index].addr)
4008     {
4009       g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
4010       g_free (socket->priv->recv_addr_cache[oldest_index].native);
4011     }
4012
4013   socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
4014   socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
4015   socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
4016   socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
4017
4018   return saddr;
4019 }
4020
4021 /**
4022  * g_socket_receive_message:
4023  * @socket: a #GSocket
4024  * @address: (out) (allow-none): a pointer to a #GSocketAddress
4025  *     pointer, or %NULL
4026  * @vectors: (array length=num_vectors): an array of #GInputVector structs
4027  * @num_vectors: the number of elements in @vectors, or -1
4028  * @messages: (array length=num_messages) (allow-none): a pointer which
4029  *    may be filled with an array of #GSocketControlMessages, or %NULL
4030  * @num_messages: a pointer which will be filled with the number of
4031  *    elements in @messages, or %NULL
4032  * @flags: a pointer to an int containing #GSocketMsgFlags flags
4033  * @cancellable: (allow-none): a %GCancellable or %NULL
4034  * @error: a #GError pointer, or %NULL
4035  *
4036  * Receive data from a socket.  This is the most complicated and
4037  * fully-featured version of this call. For easier use, see
4038  * g_socket_receive() and g_socket_receive_from().
4039  *
4040  * If @address is non-%NULL then @address will be set equal to the
4041  * source address of the received packet.
4042  * @address is owned by the caller.
4043  *
4044  * @vector must point to an array of #GInputVector structs and
4045  * @num_vectors must be the length of this array.  These structs
4046  * describe the buffers that received data will be scattered into.
4047  * If @num_vectors is -1, then @vectors is assumed to be terminated
4048  * by a #GInputVector with a %NULL buffer pointer.
4049  *
4050  * As a special case, if @num_vectors is 0 (in which case, @vectors
4051  * may of course be %NULL), then a single byte is received and
4052  * discarded. This is to facilitate the common practice of sending a
4053  * single '\0' byte for the purposes of transferring ancillary data.
4054  *
4055  * @messages, if non-%NULL, will be set to point to a newly-allocated
4056  * array of #GSocketControlMessage instances or %NULL if no such
4057  * messages was received. These correspond to the control messages
4058  * received from the kernel, one #GSocketControlMessage per message
4059  * from the kernel. This array is %NULL-terminated and must be freed
4060  * by the caller using g_free() after calling g_object_unref() on each
4061  * element. If @messages is %NULL, any control messages received will
4062  * be discarded.
4063  *
4064  * @num_messages, if non-%NULL, will be set to the number of control
4065  * messages received.
4066  *
4067  * If both @messages and @num_messages are non-%NULL, then
4068  * @num_messages gives the number of #GSocketControlMessage instances
4069  * in @messages (ie: not including the %NULL terminator).
4070  *
4071  * @flags is an in/out parameter. The commonly available arguments
4072  * for this are available in the #GSocketMsgFlags enum, but the
4073  * values there are the same as the system values, and the flags
4074  * are passed in as-is, so you can pass in system-specific flags too
4075  * (and g_socket_receive_message() may pass system-specific flags out).
4076  *
4077  * As with g_socket_receive(), data may be discarded if @socket is
4078  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4079  * provide enough buffer space to read a complete message. You can pass
4080  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4081  * removing it from the receive queue, but there is no portable way to find
4082  * out the length of the message other than by reading it into a
4083  * sufficiently-large buffer.
4084  *
4085  * If the socket is in blocking mode the call will block until there
4086  * is some data to receive, the connection is closed, or there is an
4087  * error. If there is no data available and the socket is in
4088  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4089  * returned. To be notified when data is available, wait for the
4090  * %G_IO_IN condition.
4091  *
4092  * On error -1 is returned and @error is set accordingly.
4093  *
4094  * Returns: Number of bytes read, or 0 if the connection was closed by
4095  * the peer, or -1 on error
4096  *
4097  * Since: 2.22
4098  */
4099 gssize
4100 g_socket_receive_message (GSocket                 *socket,
4101                           GSocketAddress         **address,
4102                           GInputVector            *vectors,
4103                           gint                     num_vectors,
4104                           GSocketControlMessage ***messages,
4105                           gint                    *num_messages,
4106                           gint                    *flags,
4107                           GCancellable            *cancellable,
4108                           GError                 **error)
4109 {
4110   GInputVector one_vector;
4111   char one_byte;
4112
4113   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4114
4115   if (!check_socket (socket, error))
4116     return -1;
4117
4118   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4119     return -1;
4120
4121   if (num_vectors == -1)
4122     {
4123       for (num_vectors = 0;
4124            vectors[num_vectors].buffer != NULL;
4125            num_vectors++)
4126         ;
4127     }
4128
4129   if (num_vectors == 0)
4130     {
4131       one_vector.buffer = &one_byte;
4132       one_vector.size = 1;
4133       num_vectors = 1;
4134       vectors = &one_vector;
4135     }
4136
4137 #ifndef G_OS_WIN32
4138   {
4139     struct msghdr msg;
4140     gssize result;
4141     struct sockaddr_storage one_sockaddr;
4142
4143     /* name */
4144     if (address)
4145       {
4146         msg.msg_name = &one_sockaddr;
4147         msg.msg_namelen = sizeof (struct sockaddr_storage);
4148       }
4149     else
4150       {
4151         msg.msg_name = NULL;
4152         msg.msg_namelen = 0;
4153       }
4154
4155     /* iov */
4156     /* this entire expression will be evaluated at compile time */
4157     if (sizeof *msg.msg_iov == sizeof *vectors &&
4158         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4159         G_STRUCT_OFFSET (struct iovec, iov_base) ==
4160         G_STRUCT_OFFSET (GInputVector, buffer) &&
4161         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4162         G_STRUCT_OFFSET (struct iovec, iov_len) ==
4163         G_STRUCT_OFFSET (GInputVector, size))
4164       /* ABI is compatible */
4165       {
4166         msg.msg_iov = (struct iovec *) vectors;
4167         msg.msg_iovlen = num_vectors;
4168       }
4169     else
4170       /* ABI is incompatible */
4171       {
4172         gint i;
4173
4174         msg.msg_iov = g_newa (struct iovec, num_vectors);
4175         for (i = 0; i < num_vectors; i++)
4176           {
4177             msg.msg_iov[i].iov_base = vectors[i].buffer;
4178             msg.msg_iov[i].iov_len = vectors[i].size;
4179           }
4180         msg.msg_iovlen = num_vectors;
4181       }
4182
4183     /* control */
4184     msg.msg_control = g_alloca (2048);
4185     msg.msg_controllen = 2048;
4186
4187     /* flags */
4188     if (flags != NULL)
4189       msg.msg_flags = *flags;
4190     else
4191       msg.msg_flags = 0;
4192
4193     /* We always set the close-on-exec flag so we don't leak file
4194      * descriptors into child processes.  Note that gunixfdmessage.c
4195      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4196      */
4197 #ifdef MSG_CMSG_CLOEXEC
4198     msg.msg_flags |= MSG_CMSG_CLOEXEC;
4199 #endif
4200
4201     /* do it */
4202     while (1)
4203       {
4204         if (socket->priv->blocking &&
4205             !g_socket_condition_wait (socket,
4206                                       G_IO_IN, cancellable, error))
4207           return -1;
4208
4209         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4210 #ifdef MSG_CMSG_CLOEXEC 
4211         if (result < 0 && get_socket_errno () == EINVAL)
4212           {
4213             /* We must be running on an old kernel.  Call without the flag. */
4214             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4215             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4216           }
4217 #endif
4218
4219         if (result < 0)
4220           {
4221             int errsv = get_socket_errno ();
4222
4223             if (errsv == EINTR)
4224               continue;
4225
4226             if (socket->priv->blocking &&
4227                 (errsv == EWOULDBLOCK ||
4228                  errsv == EAGAIN))
4229               continue;
4230
4231             g_set_error (error, G_IO_ERROR,
4232                          socket_io_error_from_errno (errsv),
4233                          _("Error receiving message: %s"), socket_strerror (errsv));
4234
4235             return -1;
4236           }
4237         break;
4238       }
4239
4240     /* decode address */
4241     if (address != NULL)
4242       {
4243         *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4244       }
4245
4246     /* decode control messages */
4247     {
4248       GPtrArray *my_messages = NULL;
4249       struct cmsghdr *cmsg;
4250
4251       if (msg.msg_controllen >= sizeof (struct cmsghdr))
4252         {
4253           for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4254             {
4255               GSocketControlMessage *message;
4256
4257               message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4258                                                               cmsg->cmsg_type,
4259                                                               cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4260                                                               CMSG_DATA (cmsg));
4261               if (message == NULL)
4262                 /* We've already spewed about the problem in the
4263                    deserialization code, so just continue */
4264                 continue;
4265
4266               if (messages == NULL)
4267                 {
4268                   /* we have to do it this way if the user ignores the
4269                    * messages so that we will close any received fds.
4270                    */
4271                   g_object_unref (message);
4272                 }
4273               else
4274                 {
4275                   if (my_messages == NULL)
4276                     my_messages = g_ptr_array_new ();
4277                   g_ptr_array_add (my_messages, message);
4278                 }
4279             }
4280         }
4281
4282       if (num_messages)
4283         *num_messages = my_messages != NULL ? my_messages->len : 0;
4284
4285       if (messages)
4286         {
4287           if (my_messages == NULL)
4288             {
4289               *messages = NULL;
4290             }
4291           else
4292             {
4293               g_ptr_array_add (my_messages, NULL);
4294               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4295             }
4296         }
4297       else
4298         {
4299           g_assert (my_messages == NULL);
4300         }
4301     }
4302
4303     /* capture the flags */
4304     if (flags != NULL)
4305       *flags = msg.msg_flags;
4306
4307     return result;
4308   }
4309 #else
4310   {
4311     struct sockaddr_storage addr;
4312     int addrlen;
4313     DWORD bytes_received;
4314     DWORD win_flags;
4315     int result;
4316     WSABUF *bufs;
4317     gint i;
4318
4319     /* iov */
4320     bufs = g_newa (WSABUF, num_vectors);
4321     for (i = 0; i < num_vectors; i++)
4322       {
4323         bufs[i].buf = (char *)vectors[i].buffer;
4324         bufs[i].len = (gulong)vectors[i].size;
4325       }
4326
4327     /* flags */
4328     if (flags != NULL)
4329       win_flags = *flags;
4330     else
4331       win_flags = 0;
4332
4333     /* do it */
4334     while (1)
4335       {
4336         if (socket->priv->blocking &&
4337             !g_socket_condition_wait (socket,
4338                                       G_IO_IN, cancellable, error))
4339           return -1;
4340
4341         addrlen = sizeof addr;
4342         if (address)
4343           result = WSARecvFrom (socket->priv->fd,
4344                                 bufs, num_vectors,
4345                                 &bytes_received, &win_flags,
4346                                 (struct sockaddr *)&addr, &addrlen,
4347                                 NULL, NULL);
4348         else
4349           result = WSARecv (socket->priv->fd,
4350                             bufs, num_vectors,
4351                             &bytes_received, &win_flags,
4352                             NULL, NULL);
4353         if (result != 0)
4354           {
4355             int errsv = get_socket_errno ();
4356
4357             if (errsv == WSAEINTR)
4358               continue;
4359
4360             win32_unset_event_mask (socket, FD_READ);
4361
4362             if (socket->priv->blocking &&
4363                 errsv == WSAEWOULDBLOCK)
4364               continue;
4365
4366             g_set_error (error, G_IO_ERROR,
4367                          socket_io_error_from_errno (errsv),
4368                          _("Error receiving message: %s"), socket_strerror (errsv));
4369
4370             return -1;
4371           }
4372         win32_unset_event_mask (socket, FD_READ);
4373         break;
4374       }
4375
4376     /* decode address */
4377     if (address != NULL)
4378       {
4379         *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
4380       }
4381
4382     /* capture the flags */
4383     if (flags != NULL)
4384       *flags = win_flags;
4385
4386     if (messages != NULL)
4387       *messages = NULL;
4388     if (num_messages != NULL)
4389       *num_messages = 0;
4390
4391     return bytes_received;
4392   }
4393 #endif
4394 }
4395
4396 /**
4397  * g_socket_get_credentials:
4398  * @socket: a #GSocket.
4399  * @error: #GError for error reporting, or %NULL to ignore.
4400  *
4401  * Returns the credentials of the foreign process connected to this
4402  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4403  * sockets).
4404  *
4405  * If this operation isn't supported on the OS, the method fails with
4406  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4407  * by reading the %SO_PEERCRED option on the underlying socket.
4408  *
4409  * Other ways to obtain credentials from a foreign peer includes the
4410  * #GUnixCredentialsMessage type and
4411  * g_unix_connection_send_credentials() /
4412  * g_unix_connection_receive_credentials() functions.
4413  *
4414  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4415  * that must be freed with g_object_unref().
4416  *
4417  * Since: 2.26
4418  */
4419 GCredentials *
4420 g_socket_get_credentials (GSocket   *socket,
4421                           GError   **error)
4422 {
4423   GCredentials *ret;
4424
4425   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4426   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4427
4428   ret = NULL;
4429
4430 #if defined(__linux__) || defined(__OpenBSD__)
4431   {
4432     socklen_t optlen;
4433 #if defined(__linux__)
4434     struct ucred native_creds;
4435     optlen = sizeof (struct ucred);
4436 #elif defined(__OpenBSD__)
4437     struct sockpeercred native_creds;
4438     optlen = sizeof (struct sockpeercred);
4439 #endif
4440     if (getsockopt (socket->priv->fd,
4441                     SOL_SOCKET,
4442                     SO_PEERCRED,
4443                     (void *)&native_creds,
4444                     &optlen) != 0)
4445       {
4446         int errsv = get_socket_errno ();
4447         g_set_error (error,
4448                      G_IO_ERROR,
4449                      socket_io_error_from_errno (errsv),
4450                      _("Unable to read socket credentials: %s"),
4451                      socket_strerror (errsv));
4452       }
4453     else
4454       {
4455         ret = g_credentials_new ();
4456         g_credentials_set_native (ret,
4457 #if defined(__linux__)
4458                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
4459 #elif defined(__OpenBSD__)
4460                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4461 #endif
4462                                   &native_creds);
4463       }
4464   }
4465 #else
4466   g_set_error_literal (error,
4467                        G_IO_ERROR,
4468                        G_IO_ERROR_NOT_SUPPORTED,
4469                        _("g_socket_get_credentials not implemented for this OS"));
4470 #endif
4471
4472   return ret;
4473 }
4474
4475 /**
4476  * g_socket_get_option:
4477  * @socket: a #GSocket
4478  * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4479  * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4480  * @value: (out): return location for the option value
4481  * @error: #GError for error reporting, or %NULL to ignore.
4482  *
4483  * Gets the value of an integer-valued option on @socket, as with
4484  * <literal>getsockopt ()</literal>. (If you need to fetch a
4485  * non-integer-valued option, you will need to call
4486  * <literal>getsockopt ()</literal> directly.)
4487  *
4488  * The <link linkend="gio-gnetworking.h"><literal>&lt;gio/gnetworking.h&gt;</literal></link>
4489  * header pulls in system headers that will define most of the
4490  * standard/portable socket options. For unusual socket protocols or
4491  * platform-dependent options, you may need to include additional
4492  * headers.
4493  *
4494  * Note that even for socket options that are a single byte in size,
4495  * @value is still a pointer to a #gint variable, not a #guchar;
4496  * g_socket_get_option() will handle the conversion internally.
4497  *
4498  * Returns: success or failure. On failure, @error will be set, and
4499  *   the system error value (<literal>errno</literal> or
4500  *   <literal>WSAGetLastError ()</literal>) will still be set to the
4501  *   result of the <literal>getsockopt ()</literal> call.
4502  *
4503  * Since: 2.36
4504  */
4505 gboolean
4506 g_socket_get_option (GSocket  *socket,
4507                      gint      level,
4508                      gint      optname,
4509                      gint     *value,
4510                      GError  **error)
4511 {
4512   guint size;
4513
4514   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4515
4516   *value = 0;
4517   size = sizeof (gint);
4518   if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
4519     {
4520       int errsv = get_socket_errno ();
4521
4522       g_set_error_literal (error,
4523                            G_IO_ERROR,
4524                            socket_io_error_from_errno (errsv),
4525                            socket_strerror (errsv));
4526 #ifndef G_OS_WIN32
4527       /* Reset errno in case the caller wants to look at it */
4528       errno = errsv;
4529 #endif
4530       return FALSE;
4531     }
4532
4533 #if G_BYTE_ORDER == G_BIG_ENDIAN
4534   /* If the returned value is smaller than an int then we need to
4535    * slide it over into the low-order bytes of *value.
4536    */
4537   if (size != sizeof (gint))
4538     *value = *value >> (8 * (sizeof (gint) - size));
4539 #endif
4540
4541   return TRUE;
4542 }
4543
4544 /**
4545  * g_socket_set_option:
4546  * @socket: a #GSocket
4547  * @level: the "API level" of the option (eg, <literal>SOL_SOCKET</literal>)
4548  * @optname: the "name" of the option (eg, <literal>SO_BROADCAST</literal>)
4549  * @value: the value to set the option to
4550  * @error: #GError for error reporting, or %NULL to ignore.
4551  *
4552  * Sets the value of an integer-valued option on @socket, as with
4553  * <literal>setsockopt ()</literal>. (If you need to set a
4554  * non-integer-valued option, you will need to call
4555  * <literal>setsockopt ()</literal> directly.)
4556  *
4557  * The <link linkend="gio-gnetworking.h"><literal>&lt;gio/gnetworking.h&gt;</literal></link>
4558  * header pulls in system headers that will define most of the
4559  * standard/portable socket options. For unusual socket protocols or
4560  * platform-dependent options, you may need to include additional
4561  * headers.
4562  *
4563  * Returns: success or failure. On failure, @error will be set, and
4564  *   the system error value (<literal>errno</literal> or
4565  *   <literal>WSAGetLastError ()</literal>) will still be set to the
4566  *   result of the <literal>setsockopt ()</literal> call.
4567  *
4568  * Since: 2.36
4569  */
4570 gboolean
4571 g_socket_set_option (GSocket  *socket,
4572                      gint      level,
4573                      gint      optname,
4574                      gint      value,
4575                      GError  **error)
4576 {
4577   gint errsv;
4578
4579   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4580
4581   if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
4582     return TRUE;
4583
4584 #if !defined (__linux__) && !defined (G_OS_WIN32)
4585   /* Linux and Windows let you set a single-byte value from an int,
4586    * but most other platforms don't.
4587    */
4588   if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
4589     {
4590 #if G_BYTE_ORDER == G_BIG_ENDIAN
4591       value = value << (8 * (sizeof (gint) - 1));
4592 #endif
4593       if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
4594         return TRUE;
4595     }
4596 #endif
4597
4598   errsv = get_socket_errno ();
4599
4600   g_set_error_literal (error,
4601                        G_IO_ERROR,
4602                        socket_io_error_from_errno (errsv),
4603                        socket_strerror (errsv));
4604 #ifndef G_OS_WIN32
4605   errno = errsv;
4606 #endif
4607   return FALSE;
4608 }
4609