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