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