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