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