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