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