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