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