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