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