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