Fix poll able streams for Darwin (and probably BSD)
[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     poll_fd.revents = 0;
3392
3393     do
3394       result = g_poll (&poll_fd, 1, 0);
3395     while (result == -1 && get_socket_errno () == EINTR);
3396
3397     return poll_fd.revents;
3398   }
3399 #endif
3400 }
3401
3402 /**
3403  * g_socket_condition_wait:
3404  * @socket: a #GSocket
3405  * @condition: a #GIOCondition mask to wait for
3406  * @cancellable: (allow-none): a #GCancellable, or %NULL
3407  * @error: a #GError pointer, or %NULL
3408  *
3409  * Waits for @condition to become true on @socket. When the condition
3410  * is met, %TRUE is returned.
3411  *
3412  * If @cancellable is cancelled before the condition is met, or if the
3413  * socket has a timeout set and it is reached before the condition is
3414  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3415  * the appropriate value (%G_IO_ERROR_CANCELLED or
3416  * %G_IO_ERROR_TIMED_OUT).
3417  *
3418  * See also g_socket_condition_timed_wait().
3419  *
3420  * Returns: %TRUE if the condition was met, %FALSE otherwise
3421  *
3422  * Since: 2.22
3423  */
3424 gboolean
3425 g_socket_condition_wait (GSocket       *socket,
3426                          GIOCondition   condition,
3427                          GCancellable  *cancellable,
3428                          GError       **error)
3429 {
3430   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3431
3432   return g_socket_condition_timed_wait (socket, condition, -1,
3433                                         cancellable, error);
3434 }
3435
3436 /**
3437  * g_socket_condition_timed_wait:
3438  * @socket: a #GSocket
3439  * @condition: a #GIOCondition mask to wait for
3440  * @timeout: the maximum time (in microseconds) to wait, or -1
3441  * @cancellable: (allow-none): a #GCancellable, or %NULL
3442  * @error: a #GError pointer, or %NULL
3443  *
3444  * Waits for up to @timeout microseconds for @condition to become true
3445  * on @socket. If the condition is met, %TRUE is returned.
3446  *
3447  * If @cancellable is cancelled before the condition is met, or if
3448  * @timeout (or the socket's #GSocket:timeout) is reached before the
3449  * condition is met, then %FALSE is returned and @error, if non-%NULL,
3450  * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3451  * %G_IO_ERROR_TIMED_OUT).
3452  *
3453  * If you don't want a timeout, use g_socket_condition_wait().
3454  * (Alternatively, you can pass -1 for @timeout.)
3455  *
3456  * Note that although @timeout is in microseconds for consistency with
3457  * other GLib APIs, this function actually only has millisecond
3458  * resolution, and the behavior is undefined if @timeout is not an
3459  * exact number of milliseconds.
3460  *
3461  * Returns: %TRUE if the condition was met, %FALSE otherwise
3462  *
3463  * Since: 2.32
3464  */
3465 gboolean
3466 g_socket_condition_timed_wait (GSocket       *socket,
3467                                GIOCondition   condition,
3468                                gint64         timeout,
3469                                GCancellable  *cancellable,
3470                                GError       **error)
3471 {
3472   gint64 start_time;
3473
3474   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3475
3476   if (!check_socket (socket, error))
3477     return FALSE;
3478
3479   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3480     return FALSE;
3481
3482   if (socket->priv->timeout &&
3483       (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3484     timeout = socket->priv->timeout * 1000;
3485   else if (timeout != -1)
3486     timeout = timeout / 1000;
3487
3488   start_time = g_get_monotonic_time ();
3489
3490 #ifdef G_OS_WIN32
3491   {
3492     GIOCondition current_condition;
3493     WSAEVENT events[2];
3494     DWORD res;
3495     GPollFD cancel_fd;
3496     int num_events;
3497
3498     /* Always check these */
3499     condition |=  G_IO_ERR | G_IO_HUP;
3500
3501     add_condition_watch (socket, &condition);
3502
3503     num_events = 0;
3504     events[num_events++] = socket->priv->event;
3505
3506     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3507       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3508
3509     if (timeout == -1)
3510       timeout = WSA_INFINITE;
3511
3512     current_condition = update_condition (socket);
3513     while ((condition & current_condition) == 0)
3514       {
3515         res = WSAWaitForMultipleEvents (num_events, events,
3516                                         FALSE, timeout, FALSE);
3517         if (res == WSA_WAIT_FAILED)
3518           {
3519             int errsv = get_socket_errno ();
3520
3521             g_set_error (error, G_IO_ERROR,
3522                          socket_io_error_from_errno (errsv),
3523                          _("Waiting for socket condition: %s"),
3524                          socket_strerror (errsv));
3525             break;
3526           }
3527         else if (res == WSA_WAIT_TIMEOUT)
3528           {
3529             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3530                                  _("Socket I/O timed out"));
3531             break;
3532           }
3533
3534         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3535           break;
3536
3537         current_condition = update_condition (socket);
3538
3539         if (timeout != WSA_INFINITE)
3540           {
3541             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3542             if (timeout < 0)
3543               timeout = 0;
3544           }
3545       }
3546     remove_condition_watch (socket, &condition);
3547     if (num_events > 1)
3548       g_cancellable_release_fd (cancellable);
3549
3550     return (condition & current_condition) != 0;
3551   }
3552 #else
3553   {
3554     GPollFD poll_fd[2];
3555     gint result;
3556     gint num;
3557
3558     poll_fd[0].fd = socket->priv->fd;
3559     poll_fd[0].events = condition;
3560     num = 1;
3561
3562     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3563       num++;
3564
3565     while (TRUE)
3566       {
3567         result = g_poll (poll_fd, num, timeout);
3568         if (result != -1 || errno != EINTR)
3569           break;
3570
3571         if (timeout != -1)
3572           {
3573             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3574             if (timeout < 0)
3575               timeout = 0;
3576           }
3577       }
3578     
3579     if (num > 1)
3580       g_cancellable_release_fd (cancellable);
3581
3582     if (result == 0)
3583       {
3584         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3585                              _("Socket I/O timed out"));
3586         return FALSE;
3587       }
3588
3589     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3590   }
3591   #endif
3592 }
3593
3594 /**
3595  * g_socket_send_message:
3596  * @socket: a #GSocket
3597  * @address: (allow-none): a #GSocketAddress, or %NULL
3598  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3599  * @num_vectors: the number of elements in @vectors, or -1
3600  * @messages: (array length=num_messages) (allow-none): a pointer to an
3601  *   array of #GSocketControlMessages, or %NULL.
3602  * @num_messages: number of elements in @messages, or -1.
3603  * @flags: an int containing #GSocketMsgFlags flags
3604  * @cancellable: (allow-none): a %GCancellable or %NULL
3605  * @error: #GError for error reporting, or %NULL to ignore.
3606  *
3607  * Send data to @address on @socket.  This is the most complicated and
3608  * fully-featured version of this call. For easier use, see
3609  * g_socket_send() and g_socket_send_to().
3610  *
3611  * If @address is %NULL then the message is sent to the default receiver
3612  * (set by g_socket_connect()).
3613  *
3614  * @vectors must point to an array of #GOutputVector structs and
3615  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3616  * then @vectors is assumed to be terminated by a #GOutputVector with a
3617  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3618  * that the sent data will be gathered from. Using multiple
3619  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3620  * data from multiple sources into a single buffer, and more
3621  * network-efficient than making multiple calls to g_socket_send().
3622  *
3623  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3624  * #GSocketControlMessage instances. These correspond to the control
3625  * messages to be sent on the socket.
3626  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3627  * array.
3628  *
3629  * @flags modify how the message is sent. The commonly available arguments
3630  * for this are available in the #GSocketMsgFlags enum, but the
3631  * values there are the same as the system values, and the flags
3632  * are passed in as-is, so you can pass in system-specific flags too.
3633  *
3634  * If the socket is in blocking mode the call will block until there is
3635  * space for the data in the socket queue. If there is no space available
3636  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3637  * will be returned. To be notified when space is available, wait for the
3638  * %G_IO_OUT condition. Note though that you may still receive
3639  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3640  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3641  * very common due to the way the underlying APIs work.)
3642  *
3643  * On error -1 is returned and @error is set accordingly.
3644  *
3645  * Returns: Number of bytes written (which may be less than @size), or -1
3646  * on error
3647  *
3648  * Since: 2.22
3649  */
3650 gssize
3651 g_socket_send_message (GSocket                *socket,
3652                        GSocketAddress         *address,
3653                        GOutputVector          *vectors,
3654                        gint                    num_vectors,
3655                        GSocketControlMessage **messages,
3656                        gint                    num_messages,
3657                        gint                    flags,
3658                        GCancellable           *cancellable,
3659                        GError                **error)
3660 {
3661   GOutputVector one_vector;
3662   char zero;
3663
3664   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3665
3666   if (!check_socket (socket, error))
3667     return -1;
3668
3669   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3670     return -1;
3671
3672   if (num_vectors == -1)
3673     {
3674       for (num_vectors = 0;
3675            vectors[num_vectors].buffer != NULL;
3676            num_vectors++)
3677         ;
3678     }
3679
3680   if (num_messages == -1)
3681     {
3682       for (num_messages = 0;
3683            messages != NULL && messages[num_messages] != NULL;
3684            num_messages++)
3685         ;
3686     }
3687
3688   if (num_vectors == 0)
3689     {
3690       zero = '\0';
3691
3692       one_vector.buffer = &zero;
3693       one_vector.size = 1;
3694       num_vectors = 1;
3695       vectors = &one_vector;
3696     }
3697
3698 #ifndef G_OS_WIN32
3699   {
3700     struct msghdr msg;
3701     gssize result;
3702
3703    msg.msg_flags = 0;
3704
3705     /* name */
3706     if (address)
3707       {
3708         msg.msg_namelen = g_socket_address_get_native_size (address);
3709         msg.msg_name = g_alloca (msg.msg_namelen);
3710         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3711           return -1;
3712       }
3713     else
3714       {
3715         msg.msg_name = NULL;
3716         msg.msg_namelen = 0;
3717       }
3718
3719     /* iov */
3720     {
3721       /* this entire expression will be evaluated at compile time */
3722       if (sizeof *msg.msg_iov == sizeof *vectors &&
3723           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3724           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3725           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3726           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3727           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3728           G_STRUCT_OFFSET (GOutputVector, size))
3729         /* ABI is compatible */
3730         {
3731           msg.msg_iov = (struct iovec *) vectors;
3732           msg.msg_iovlen = num_vectors;
3733         }
3734       else
3735         /* ABI is incompatible */
3736         {
3737           gint i;
3738
3739           msg.msg_iov = g_newa (struct iovec, num_vectors);
3740           for (i = 0; i < num_vectors; i++)
3741             {
3742               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3743               msg.msg_iov[i].iov_len = vectors[i].size;
3744             }
3745           msg.msg_iovlen = num_vectors;
3746         }
3747     }
3748
3749     /* control */
3750     {
3751       struct cmsghdr *cmsg;
3752       gint i;
3753
3754       msg.msg_controllen = 0;
3755       for (i = 0; i < num_messages; i++)
3756         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3757
3758       if (msg.msg_controllen == 0)
3759         msg.msg_control = NULL;
3760       else
3761         {
3762           msg.msg_control = g_alloca (msg.msg_controllen);
3763           memset (msg.msg_control, '\0', msg.msg_controllen);
3764         }
3765
3766       cmsg = CMSG_FIRSTHDR (&msg);
3767       for (i = 0; i < num_messages; i++)
3768         {
3769           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3770           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3771           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3772           g_socket_control_message_serialize (messages[i],
3773                                               CMSG_DATA (cmsg));
3774           cmsg = CMSG_NXTHDR (&msg, cmsg);
3775         }
3776       g_assert (cmsg == NULL);
3777     }
3778
3779     while (1)
3780       {
3781         if (socket->priv->blocking &&
3782             !g_socket_condition_wait (socket,
3783                                       G_IO_OUT, cancellable, error))
3784           return -1;
3785
3786         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3787         if (result < 0)
3788           {
3789             int errsv = get_socket_errno ();
3790
3791             if (errsv == EINTR)
3792               continue;
3793
3794             if (socket->priv->blocking &&
3795                 (errsv == EWOULDBLOCK ||
3796                  errsv == EAGAIN))
3797               continue;
3798
3799             g_set_error (error, G_IO_ERROR,
3800                          socket_io_error_from_errno (errsv),
3801                          _("Error sending message: %s"), socket_strerror (errsv));
3802
3803             return -1;
3804           }
3805         break;
3806       }
3807
3808     return result;
3809   }
3810 #else
3811   {
3812     struct sockaddr_storage addr;
3813     guint addrlen;
3814     DWORD bytes_sent;
3815     int result;
3816     WSABUF *bufs;
3817     gint i;
3818
3819     /* Win32 doesn't support control messages.
3820        Actually this is possible for raw and datagram sockets
3821        via WSASendMessage on Vista or later, but that doesn't
3822        seem very useful */
3823     if (num_messages != 0)
3824       {
3825         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3826                              _("GSocketControlMessage not supported on Windows"));
3827         return -1;
3828       }
3829
3830     /* iov */
3831     bufs = g_newa (WSABUF, num_vectors);
3832     for (i = 0; i < num_vectors; i++)
3833       {
3834         bufs[i].buf = (char *)vectors[i].buffer;
3835         bufs[i].len = (gulong)vectors[i].size;
3836       }
3837
3838     /* name */
3839     addrlen = 0; /* Avoid warning */
3840     if (address)
3841       {
3842         addrlen = g_socket_address_get_native_size (address);
3843         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3844           return -1;
3845       }
3846
3847     while (1)
3848       {
3849         if (socket->priv->blocking &&
3850             !g_socket_condition_wait (socket,
3851                                       G_IO_OUT, cancellable, error))
3852           return -1;
3853
3854         if (address)
3855           result = WSASendTo (socket->priv->fd,
3856                               bufs, num_vectors,
3857                               &bytes_sent, flags,
3858                               (const struct sockaddr *)&addr, addrlen,
3859                               NULL, NULL);
3860         else
3861           result = WSASend (socket->priv->fd,
3862                             bufs, num_vectors,
3863                             &bytes_sent, flags,
3864                             NULL, NULL);
3865
3866         if (result != 0)
3867           {
3868             int errsv = get_socket_errno ();
3869
3870             if (errsv == WSAEINTR)
3871               continue;
3872
3873             if (errsv == WSAEWOULDBLOCK)
3874               win32_unset_event_mask (socket, FD_WRITE);
3875
3876             if (socket->priv->blocking &&
3877                 errsv == WSAEWOULDBLOCK)
3878               continue;
3879
3880             g_set_error (error, G_IO_ERROR,
3881                          socket_io_error_from_errno (errsv),
3882                          _("Error sending message: %s"), socket_strerror (errsv));
3883
3884             return -1;
3885           }
3886         break;
3887       }
3888
3889     return bytes_sent;
3890   }
3891 #endif
3892 }
3893
3894 /**
3895  * g_socket_receive_message:
3896  * @socket: a #GSocket
3897  * @address: (out) (allow-none): a pointer to a #GSocketAddress
3898  *     pointer, or %NULL
3899  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3900  * @num_vectors: the number of elements in @vectors, or -1
3901  * @messages: (array length=num_messages) (allow-none): a pointer which
3902  *    may be filled with an array of #GSocketControlMessages, or %NULL
3903  * @num_messages: a pointer which will be filled with the number of
3904  *    elements in @messages, or %NULL
3905  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3906  * @cancellable: (allow-none): a %GCancellable or %NULL
3907  * @error: a #GError pointer, or %NULL
3908  *
3909  * Receive data from a socket.  This is the most complicated and
3910  * fully-featured version of this call. For easier use, see
3911  * g_socket_receive() and g_socket_receive_from().
3912  *
3913  * If @address is non-%NULL then @address will be set equal to the
3914  * source address of the received packet.
3915  * @address is owned by the caller.
3916  *
3917  * @vector must point to an array of #GInputVector structs and
3918  * @num_vectors must be the length of this array.  These structs
3919  * describe the buffers that received data will be scattered into.
3920  * If @num_vectors is -1, then @vectors is assumed to be terminated
3921  * by a #GInputVector with a %NULL buffer pointer.
3922  *
3923  * As a special case, if @num_vectors is 0 (in which case, @vectors
3924  * may of course be %NULL), then a single byte is received and
3925  * discarded. This is to facilitate the common practice of sending a
3926  * single '\0' byte for the purposes of transferring ancillary data.
3927  *
3928  * @messages, if non-%NULL, will be set to point to a newly-allocated
3929  * array of #GSocketControlMessage instances or %NULL if no such
3930  * messages was received. These correspond to the control messages
3931  * received from the kernel, one #GSocketControlMessage per message
3932  * from the kernel. This array is %NULL-terminated and must be freed
3933  * by the caller using g_free() after calling g_object_unref() on each
3934  * element. If @messages is %NULL, any control messages received will
3935  * be discarded.
3936  *
3937  * @num_messages, if non-%NULL, will be set to the number of control
3938  * messages received.
3939  *
3940  * If both @messages and @num_messages are non-%NULL, then
3941  * @num_messages gives the number of #GSocketControlMessage instances
3942  * in @messages (ie: not including the %NULL terminator).
3943  *
3944  * @flags is an in/out parameter. The commonly available arguments
3945  * for this are available in the #GSocketMsgFlags enum, but the
3946  * values there are the same as the system values, and the flags
3947  * are passed in as-is, so you can pass in system-specific flags too
3948  * (and g_socket_receive_message() may pass system-specific flags out).
3949  *
3950  * As with g_socket_receive(), data may be discarded if @socket is
3951  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3952  * provide enough buffer space to read a complete message. You can pass
3953  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3954  * removing it from the receive queue, but there is no portable way to find
3955  * out the length of the message other than by reading it into a
3956  * sufficiently-large buffer.
3957  *
3958  * If the socket is in blocking mode the call will block until there
3959  * is some data to receive, the connection is closed, or there is an
3960  * error. If there is no data available and the socket is in
3961  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3962  * returned. To be notified when data is available, wait for the
3963  * %G_IO_IN condition.
3964  *
3965  * On error -1 is returned and @error is set accordingly.
3966  *
3967  * Returns: Number of bytes read, or 0 if the connection was closed by
3968  * the peer, or -1 on error
3969  *
3970  * Since: 2.22
3971  */
3972 gssize
3973 g_socket_receive_message (GSocket                 *socket,
3974                           GSocketAddress         **address,
3975                           GInputVector            *vectors,
3976                           gint                     num_vectors,
3977                           GSocketControlMessage ***messages,
3978                           gint                    *num_messages,
3979                           gint                    *flags,
3980                           GCancellable            *cancellable,
3981                           GError                 **error)
3982 {
3983   GInputVector one_vector;
3984   char one_byte;
3985
3986   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3987
3988   if (!check_socket (socket, error))
3989     return -1;
3990
3991   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3992     return -1;
3993
3994   if (num_vectors == -1)
3995     {
3996       for (num_vectors = 0;
3997            vectors[num_vectors].buffer != NULL;
3998            num_vectors++)
3999         ;
4000     }
4001
4002   if (num_vectors == 0)
4003     {
4004       one_vector.buffer = &one_byte;
4005       one_vector.size = 1;
4006       num_vectors = 1;
4007       vectors = &one_vector;
4008     }
4009
4010 #ifndef G_OS_WIN32
4011   {
4012     struct msghdr msg;
4013     gssize result;
4014     struct sockaddr_storage one_sockaddr;
4015
4016     /* name */
4017     if (address)
4018       {
4019         msg.msg_name = &one_sockaddr;
4020         msg.msg_namelen = sizeof (struct sockaddr_storage);
4021       }
4022     else
4023       {
4024         msg.msg_name = NULL;
4025         msg.msg_namelen = 0;
4026       }
4027
4028     /* iov */
4029     /* this entire expression will be evaluated at compile time */
4030     if (sizeof *msg.msg_iov == sizeof *vectors &&
4031         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4032         G_STRUCT_OFFSET (struct iovec, iov_base) ==
4033         G_STRUCT_OFFSET (GInputVector, buffer) &&
4034         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4035         G_STRUCT_OFFSET (struct iovec, iov_len) ==
4036         G_STRUCT_OFFSET (GInputVector, size))
4037       /* ABI is compatible */
4038       {
4039         msg.msg_iov = (struct iovec *) vectors;
4040         msg.msg_iovlen = num_vectors;
4041       }
4042     else
4043       /* ABI is incompatible */
4044       {
4045         gint i;
4046
4047         msg.msg_iov = g_newa (struct iovec, num_vectors);
4048         for (i = 0; i < num_vectors; i++)
4049           {
4050             msg.msg_iov[i].iov_base = vectors[i].buffer;
4051             msg.msg_iov[i].iov_len = vectors[i].size;
4052           }
4053         msg.msg_iovlen = num_vectors;
4054       }
4055
4056     /* control */
4057     msg.msg_control = g_alloca (2048);
4058     msg.msg_controllen = 2048;
4059
4060     /* flags */
4061     if (flags != NULL)
4062       msg.msg_flags = *flags;
4063     else
4064       msg.msg_flags = 0;
4065
4066     /* We always set the close-on-exec flag so we don't leak file
4067      * descriptors into child processes.  Note that gunixfdmessage.c
4068      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4069      */
4070 #ifdef MSG_CMSG_CLOEXEC
4071     msg.msg_flags |= MSG_CMSG_CLOEXEC;
4072 #endif
4073
4074     /* do it */
4075     while (1)
4076       {
4077         if (socket->priv->blocking &&
4078             !g_socket_condition_wait (socket,
4079                                       G_IO_IN, cancellable, error))
4080           return -1;
4081
4082         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4083 #ifdef MSG_CMSG_CLOEXEC 
4084         if (result < 0 && get_socket_errno () == EINVAL)
4085           {
4086             /* We must be running on an old kernel.  Call without the flag. */
4087             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4088             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4089           }
4090 #endif
4091
4092         if (result < 0)
4093           {
4094             int errsv = get_socket_errno ();
4095
4096             if (errsv == EINTR)
4097               continue;
4098
4099             if (socket->priv->blocking &&
4100                 (errsv == EWOULDBLOCK ||
4101                  errsv == EAGAIN))
4102               continue;
4103
4104             g_set_error (error, G_IO_ERROR,
4105                          socket_io_error_from_errno (errsv),
4106                          _("Error receiving message: %s"), socket_strerror (errsv));
4107
4108             return -1;
4109           }
4110         break;
4111       }
4112
4113     /* decode address */
4114     if (address != NULL)
4115       {
4116         if (msg.msg_namelen > 0)
4117           *address = g_socket_address_new_from_native (msg.msg_name,
4118                                                        msg.msg_namelen);
4119         else
4120           *address = NULL;
4121       }
4122
4123     /* decode control messages */
4124     {
4125       GPtrArray *my_messages = NULL;
4126       struct cmsghdr *cmsg;
4127
4128       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4129         {
4130           GSocketControlMessage *message;
4131
4132           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4133                                                           cmsg->cmsg_type,
4134                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4135                                                           CMSG_DATA (cmsg));
4136           if (message == NULL)
4137             /* We've already spewed about the problem in the
4138                deserialization code, so just continue */
4139             continue;
4140
4141           if (messages == NULL)
4142             {
4143               /* we have to do it this way if the user ignores the
4144                * messages so that we will close any received fds.
4145                */
4146               g_object_unref (message);
4147             }
4148           else
4149             {
4150               if (my_messages == NULL)
4151                 my_messages = g_ptr_array_new ();
4152               g_ptr_array_add (my_messages, message);
4153             }
4154         }
4155
4156       if (num_messages)
4157         *num_messages = my_messages != NULL ? my_messages->len : 0;
4158
4159       if (messages)
4160         {
4161           if (my_messages == NULL)
4162             {
4163               *messages = NULL;
4164             }
4165           else
4166             {
4167               g_ptr_array_add (my_messages, NULL);
4168               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4169             }
4170         }
4171       else
4172         {
4173           g_assert (my_messages == NULL);
4174         }
4175     }
4176
4177     /* capture the flags */
4178     if (flags != NULL)
4179       *flags = msg.msg_flags;
4180
4181     return result;
4182   }
4183 #else
4184   {
4185     struct sockaddr_storage addr;
4186     int addrlen;
4187     DWORD bytes_received;
4188     DWORD win_flags;
4189     int result;
4190     WSABUF *bufs;
4191     gint i;
4192
4193     /* iov */
4194     bufs = g_newa (WSABUF, num_vectors);
4195     for (i = 0; i < num_vectors; i++)
4196       {
4197         bufs[i].buf = (char *)vectors[i].buffer;
4198         bufs[i].len = (gulong)vectors[i].size;
4199       }
4200
4201     /* flags */
4202     if (flags != NULL)
4203       win_flags = *flags;
4204     else
4205       win_flags = 0;
4206
4207     /* do it */
4208     while (1)
4209       {
4210         if (socket->priv->blocking &&
4211             !g_socket_condition_wait (socket,
4212                                       G_IO_IN, cancellable, error))
4213           return -1;
4214
4215         addrlen = sizeof addr;
4216         if (address)
4217           result = WSARecvFrom (socket->priv->fd,
4218                                 bufs, num_vectors,
4219                                 &bytes_received, &win_flags,
4220                                 (struct sockaddr *)&addr, &addrlen,
4221                                 NULL, NULL);
4222         else
4223           result = WSARecv (socket->priv->fd,
4224                             bufs, num_vectors,
4225                             &bytes_received, &win_flags,
4226                             NULL, NULL);
4227         if (result != 0)
4228           {
4229             int errsv = get_socket_errno ();
4230
4231             if (errsv == WSAEINTR)
4232               continue;
4233
4234             win32_unset_event_mask (socket, FD_READ);
4235
4236             if (socket->priv->blocking &&
4237                 errsv == WSAEWOULDBLOCK)
4238               continue;
4239
4240             g_set_error (error, G_IO_ERROR,
4241                          socket_io_error_from_errno (errsv),
4242                          _("Error receiving message: %s"), socket_strerror (errsv));
4243
4244             return -1;
4245           }
4246         win32_unset_event_mask (socket, FD_READ);
4247         break;
4248       }
4249
4250     /* decode address */
4251     if (address != NULL)
4252       {
4253         if (addrlen > 0)
4254           *address = g_socket_address_new_from_native (&addr, addrlen);
4255         else
4256           *address = NULL;
4257       }
4258
4259     /* capture the flags */
4260     if (flags != NULL)
4261       *flags = win_flags;
4262
4263     if (messages != NULL)
4264       *messages = NULL;
4265     if (num_messages != NULL)
4266       *num_messages = 0;
4267
4268     return bytes_received;
4269   }
4270 #endif
4271 }
4272
4273 /**
4274  * g_socket_get_credentials:
4275  * @socket: a #GSocket.
4276  * @error: #GError for error reporting, or %NULL to ignore.
4277  *
4278  * Returns the credentials of the foreign process connected to this
4279  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4280  * sockets).
4281  *
4282  * If this operation isn't supported on the OS, the method fails with
4283  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4284  * by reading the %SO_PEERCRED option on the underlying socket.
4285  *
4286  * Other ways to obtain credentials from a foreign peer includes the
4287  * #GUnixCredentialsMessage type and
4288  * g_unix_connection_send_credentials() /
4289  * g_unix_connection_receive_credentials() functions.
4290  *
4291  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4292  * that must be freed with g_object_unref().
4293  *
4294  * Since: 2.26
4295  */
4296 GCredentials *
4297 g_socket_get_credentials (GSocket   *socket,
4298                           GError   **error)
4299 {
4300   GCredentials *ret;
4301
4302   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4303   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4304
4305   ret = NULL;
4306
4307 #if defined(__linux__) || defined(__OpenBSD__)
4308   {
4309     socklen_t optlen;
4310 #if defined(__linux__)
4311     struct ucred native_creds;
4312     optlen = sizeof (struct ucred);
4313 #elif defined(__OpenBSD__)
4314     struct sockpeercred native_creds;
4315     optlen = sizeof (struct sockpeercred);
4316 #endif
4317     if (getsockopt (socket->priv->fd,
4318                     SOL_SOCKET,
4319                     SO_PEERCRED,
4320                     (void *)&native_creds,
4321                     &optlen) != 0)
4322       {
4323         int errsv = get_socket_errno ();
4324         g_set_error (error,
4325                      G_IO_ERROR,
4326                      socket_io_error_from_errno (errsv),
4327                      _("Unable to get pending error: %s"),
4328                      socket_strerror (errsv));
4329       }
4330     else
4331       {
4332         ret = g_credentials_new ();
4333         g_credentials_set_native (ret,
4334 #if defined(__linux__)
4335                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
4336 #elif defined(__OpenBSD__)
4337                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4338 #endif
4339                                   &native_creds);
4340       }
4341   }
4342 #else
4343   g_set_error_literal (error,
4344                        G_IO_ERROR,
4345                        G_IO_ERROR_NOT_SUPPORTED,
4346                        _("g_socket_get_credentials not implemented for this OS"));
4347 #endif
4348
4349   return ret;
4350 }