Return correct value for g_socket_get_available_bytes() on Windows and OSX
[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 that can be read from the socket without
2372  * blocking. In the case of datagram sockets this returns the size
2373  * of the first datagram and not the sum of the sizes of all currently
2374  * queued datagrams.
2375  *
2376  * Returns: the number of bytes that can be read from the socket
2377  * without blocking or -1 on error.
2378  *
2379  * Since: 2.32
2380  */
2381 gssize
2382 g_socket_get_available_bytes (GSocket *socket)
2383 {
2384 #ifndef G_OS_WIN32
2385   gulong avail = 0;
2386 #else
2387   gint avail = 0;
2388   gsize avail_len = sizeof (avail);
2389 #endif
2390
2391   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2392
2393 #if defined(G_OS_WIN32)
2394   if (WSAIoctl (socket->priv->fd, FIONREAD, NULL, 0, &avail, sizeof (avail), 0, 0) == SOCKET_ERROR)
2395     return -1;
2396 #elif defined(SO_NREAD)
2397   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_NREAD, &avail, &avail_len) < 0)
2398     return -1;
2399 #else
2400   if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2401     return -1;
2402 #endif
2403
2404   return avail;
2405 }
2406
2407 /**
2408  * g_socket_receive:
2409  * @socket: a #GSocket
2410  * @buffer: a buffer to read data into (which should be at least @size
2411  *     bytes long).
2412  * @size: the number of bytes you want to read from the socket
2413  * @cancellable: (allow-none): a %GCancellable or %NULL
2414  * @error: #GError for error reporting, or %NULL to ignore.
2415  *
2416  * Receive data (up to @size bytes) from a socket. This is mainly used by
2417  * connection-oriented sockets; it is identical to g_socket_receive_from()
2418  * with @address set to %NULL.
2419  *
2420  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2421  * g_socket_receive() will always read either 0 or 1 complete messages from
2422  * the socket. If the received message is too large to fit in @buffer, then
2423  * the data beyond @size bytes will be discarded, without any explicit
2424  * indication that this has occurred.
2425  *
2426  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2427  * number of bytes, up to @size. If more than @size bytes have been
2428  * received, the additional data will be returned in future calls to
2429  * g_socket_receive().
2430  *
2431  * If the socket is in blocking mode the call will block until there
2432  * is some data to receive, the connection is closed, or there is an
2433  * error. If there is no data available and the socket is in
2434  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2435  * returned. To be notified when data is available, wait for the
2436  * %G_IO_IN condition.
2437  *
2438  * On error -1 is returned and @error is set accordingly.
2439  *
2440  * Returns: Number of bytes read, or 0 if the connection was closed by
2441  * the peer, or -1 on error
2442  *
2443  * Since: 2.22
2444  */
2445 gssize
2446 g_socket_receive (GSocket       *socket,
2447                   gchar         *buffer,
2448                   gsize          size,
2449                   GCancellable  *cancellable,
2450                   GError       **error)
2451 {
2452   return g_socket_receive_with_blocking (socket, buffer, size,
2453                                          socket->priv->blocking,
2454                                          cancellable, error);
2455 }
2456
2457 /**
2458  * g_socket_receive_with_blocking:
2459  * @socket: a #GSocket
2460  * @buffer: a buffer to read data into (which should be at least @size
2461  *     bytes long).
2462  * @size: the number of bytes you want to read from the socket
2463  * @blocking: whether to do blocking or non-blocking I/O
2464  * @cancellable: (allow-none): a %GCancellable or %NULL
2465  * @error: #GError for error reporting, or %NULL to ignore.
2466  *
2467  * This behaves exactly the same as g_socket_receive(), except that
2468  * the choice of blocking or non-blocking behavior is determined by
2469  * the @blocking argument rather than by @socket's properties.
2470  *
2471  * Returns: Number of bytes read, or 0 if the connection was closed by
2472  * the peer, or -1 on error
2473  *
2474  * Since: 2.26
2475  */
2476 gssize
2477 g_socket_receive_with_blocking (GSocket       *socket,
2478                                 gchar         *buffer,
2479                                 gsize          size,
2480                                 gboolean       blocking,
2481                                 GCancellable  *cancellable,
2482                                 GError       **error)
2483 {
2484   gssize ret;
2485
2486   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2487
2488   if (!check_socket (socket, error))
2489     return -1;
2490
2491   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2492     return -1;
2493
2494   while (1)
2495     {
2496       if (blocking &&
2497           !g_socket_condition_wait (socket,
2498                                     G_IO_IN, cancellable, error))
2499         return -1;
2500
2501       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2502         {
2503           int errsv = get_socket_errno ();
2504
2505           if (errsv == EINTR)
2506             continue;
2507
2508           if (blocking)
2509             {
2510 #ifdef WSAEWOULDBLOCK
2511               if (errsv == WSAEWOULDBLOCK)
2512                 continue;
2513 #else
2514               if (errsv == EWOULDBLOCK ||
2515                   errsv == EAGAIN)
2516                 continue;
2517 #endif
2518             }
2519
2520           win32_unset_event_mask (socket, FD_READ);
2521
2522           g_set_error (error, G_IO_ERROR,
2523                        socket_io_error_from_errno (errsv),
2524                        _("Error receiving data: %s"), socket_strerror (errsv));
2525           return -1;
2526         }
2527
2528       win32_unset_event_mask (socket, FD_READ);
2529
2530       break;
2531     }
2532
2533   return ret;
2534 }
2535
2536 /**
2537  * g_socket_receive_from:
2538  * @socket: a #GSocket
2539  * @address: (out) (allow-none): a pointer to a #GSocketAddress
2540  *     pointer, or %NULL
2541  * @buffer: (array length=size) (element-type guint8): a buffer to
2542  *     read data into (which should be at least @size bytes long).
2543  * @size: the number of bytes you want to read from the socket
2544  * @cancellable: (allow-none): a %GCancellable or %NULL
2545  * @error: #GError for error reporting, or %NULL to ignore.
2546  *
2547  * Receive data (up to @size bytes) from a socket.
2548  *
2549  * If @address is non-%NULL then @address will be set equal to the
2550  * source address of the received packet.
2551  * @address is owned by the caller.
2552  *
2553  * See g_socket_receive() for additional information.
2554  *
2555  * Returns: Number of bytes read, or 0 if the connection was closed by
2556  * the peer, or -1 on error
2557  *
2558  * Since: 2.22
2559  */
2560 gssize
2561 g_socket_receive_from (GSocket         *socket,
2562                        GSocketAddress **address,
2563                        gchar           *buffer,
2564                        gsize            size,
2565                        GCancellable    *cancellable,
2566                        GError         **error)
2567 {
2568   GInputVector v;
2569
2570   v.buffer = buffer;
2571   v.size = size;
2572
2573   return g_socket_receive_message (socket,
2574                                    address,
2575                                    &v, 1,
2576                                    NULL, 0, NULL,
2577                                    cancellable,
2578                                    error);
2579 }
2580
2581 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2582  * one, which can be confusing and annoying. So if possible, we want
2583  * to suppress the signal entirely.
2584  */
2585 #ifdef MSG_NOSIGNAL
2586 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2587 #else
2588 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2589 #endif
2590
2591 /**
2592  * g_socket_send:
2593  * @socket: a #GSocket
2594  * @buffer: (array length=size) (element-type guint8): the buffer
2595  *     containing the data to send.
2596  * @size: the number of bytes to send
2597  * @cancellable: (allow-none): a %GCancellable or %NULL
2598  * @error: #GError for error reporting, or %NULL to ignore.
2599  *
2600  * Tries to send @size bytes from @buffer on the socket. This is
2601  * mainly used by connection-oriented sockets; it is identical to
2602  * g_socket_send_to() with @address set to %NULL.
2603  *
2604  * If the socket is in blocking mode the call will block until there is
2605  * space for the data in the socket queue. If there is no space available
2606  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2607  * will be returned. To be notified when space is available, wait for the
2608  * %G_IO_OUT condition. Note though that you may still receive
2609  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2610  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2611  * very common due to the way the underlying APIs work.)
2612  *
2613  * On error -1 is returned and @error is set accordingly.
2614  *
2615  * Returns: Number of bytes written (which may be less than @size), or -1
2616  * on error
2617  *
2618  * Since: 2.22
2619  */
2620 gssize
2621 g_socket_send (GSocket       *socket,
2622                const gchar   *buffer,
2623                gsize          size,
2624                GCancellable  *cancellable,
2625                GError       **error)
2626 {
2627   return g_socket_send_with_blocking (socket, buffer, size,
2628                                       socket->priv->blocking,
2629                                       cancellable, error);
2630 }
2631
2632 /**
2633  * g_socket_send_with_blocking:
2634  * @socket: a #GSocket
2635  * @buffer: (array length=size) (element-type guint8): the buffer
2636  *     containing the data to send.
2637  * @size: the number of bytes to send
2638  * @blocking: whether to do blocking or non-blocking I/O
2639  * @cancellable: (allow-none): a %GCancellable or %NULL
2640  * @error: #GError for error reporting, or %NULL to ignore.
2641  *
2642  * This behaves exactly the same as g_socket_send(), except that
2643  * the choice of blocking or non-blocking behavior is determined by
2644  * the @blocking argument rather than by @socket's properties.
2645  *
2646  * Returns: Number of bytes written (which may be less than @size), or -1
2647  * on error
2648  *
2649  * Since: 2.26
2650  */
2651 gssize
2652 g_socket_send_with_blocking (GSocket       *socket,
2653                              const gchar   *buffer,
2654                              gsize          size,
2655                              gboolean       blocking,
2656                              GCancellable  *cancellable,
2657                              GError       **error)
2658 {
2659   gssize ret;
2660
2661   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2662
2663   if (!check_socket (socket, error))
2664     return -1;
2665
2666   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2667     return -1;
2668
2669   while (1)
2670     {
2671       if (blocking &&
2672           !g_socket_condition_wait (socket,
2673                                     G_IO_OUT, cancellable, error))
2674         return -1;
2675
2676       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2677         {
2678           int errsv = get_socket_errno ();
2679
2680           if (errsv == EINTR)
2681             continue;
2682
2683 #ifdef WSAEWOULDBLOCK
2684           if (errsv == WSAEWOULDBLOCK)
2685             win32_unset_event_mask (socket, FD_WRITE);
2686 #endif
2687
2688           if (blocking)
2689             {
2690 #ifdef WSAEWOULDBLOCK
2691               if (errsv == WSAEWOULDBLOCK)
2692                 continue;
2693 #else
2694               if (errsv == EWOULDBLOCK ||
2695                   errsv == EAGAIN)
2696                 continue;
2697 #endif
2698             }
2699
2700           g_set_error (error, G_IO_ERROR,
2701                        socket_io_error_from_errno (errsv),
2702                        _("Error sending data: %s"), socket_strerror (errsv));
2703           return -1;
2704         }
2705       break;
2706     }
2707
2708   return ret;
2709 }
2710
2711 /**
2712  * g_socket_send_to:
2713  * @socket: a #GSocket
2714  * @address: (allow-none): a #GSocketAddress, or %NULL
2715  * @buffer: (array length=size) (element-type guint8): the buffer
2716  *     containing the data to send.
2717  * @size: the number of bytes to send
2718  * @cancellable: (allow-none): a %GCancellable or %NULL
2719  * @error: #GError for error reporting, or %NULL to ignore.
2720  *
2721  * Tries to send @size bytes from @buffer to @address. If @address is
2722  * %NULL then the message is sent to the default receiver (set by
2723  * g_socket_connect()).
2724  *
2725  * See g_socket_send() for additional information.
2726  *
2727  * Returns: Number of bytes written (which may be less than @size), or -1
2728  * on error
2729  *
2730  * Since: 2.22
2731  */
2732 gssize
2733 g_socket_send_to (GSocket         *socket,
2734                   GSocketAddress  *address,
2735                   const gchar     *buffer,
2736                   gsize            size,
2737                   GCancellable    *cancellable,
2738                   GError         **error)
2739 {
2740   GOutputVector v;
2741
2742   v.buffer = buffer;
2743   v.size = size;
2744
2745   return g_socket_send_message (socket,
2746                                 address,
2747                                 &v, 1,
2748                                 NULL, 0,
2749                                 0,
2750                                 cancellable,
2751                                 error);
2752 }
2753
2754 /**
2755  * g_socket_shutdown:
2756  * @socket: a #GSocket
2757  * @shutdown_read: whether to shut down the read side
2758  * @shutdown_write: whether to shut down the write side
2759  * @error: #GError for error reporting, or %NULL to ignore.
2760  *
2761  * Shut down part of a full-duplex connection.
2762  *
2763  * If @shutdown_read is %TRUE then the receiving side of the connection
2764  * is shut down, and further reading is disallowed.
2765  *
2766  * If @shutdown_write is %TRUE then the sending side of the connection
2767  * is shut down, and further writing is disallowed.
2768  *
2769  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2770  *
2771  * One example where this is used is graceful disconnect for TCP connections
2772  * where you close the sending side, then wait for the other side to close
2773  * the connection, thus ensuring that the other side saw all sent data.
2774  *
2775  * Returns: %TRUE on success, %FALSE on error
2776  *
2777  * Since: 2.22
2778  */
2779 gboolean
2780 g_socket_shutdown (GSocket   *socket,
2781                    gboolean   shutdown_read,
2782                    gboolean   shutdown_write,
2783                    GError   **error)
2784 {
2785   int how;
2786
2787   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2788
2789   if (!check_socket (socket, error))
2790     return FALSE;
2791
2792   /* Do nothing? */
2793   if (!shutdown_read && !shutdown_write)
2794     return TRUE;
2795
2796 #ifndef G_OS_WIN32
2797   if (shutdown_read && shutdown_write)
2798     how = SHUT_RDWR;
2799   else if (shutdown_read)
2800     how = SHUT_RD;
2801   else
2802     how = SHUT_WR;
2803 #else
2804   if (shutdown_read && shutdown_write)
2805     how = SD_BOTH;
2806   else if (shutdown_read)
2807     how = SD_RECEIVE;
2808   else
2809     how = SD_SEND;
2810 #endif
2811
2812   if (shutdown (socket->priv->fd, how) != 0)
2813     {
2814       int errsv = get_socket_errno ();
2815       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2816                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2817       return FALSE;
2818     }
2819
2820   if (shutdown_read && shutdown_write)
2821     socket->priv->connected = FALSE;
2822
2823   return TRUE;
2824 }
2825
2826 /**
2827  * g_socket_close:
2828  * @socket: a #GSocket
2829  * @error: #GError for error reporting, or %NULL to ignore.
2830  *
2831  * Closes the socket, shutting down any active connection.
2832  *
2833  * Closing a socket does not wait for all outstanding I/O operations
2834  * to finish, so the caller should not rely on them to be guaranteed
2835  * to complete even if the close returns with no error.
2836  *
2837  * Once the socket is closed, all other operations will return
2838  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2839  * return an error.
2840  *
2841  * Sockets will be automatically closed when the last reference
2842  * is dropped, but you might want to call this function to make sure
2843  * resources are released as early as possible.
2844  *
2845  * Beware that due to the way that TCP works, it is possible for
2846  * recently-sent data to be lost if either you close a socket while the
2847  * %G_IO_IN condition is set, or else if the remote connection tries to
2848  * send something to you after you close the socket but before it has
2849  * finished reading all of the data you sent. There is no easy generic
2850  * way to avoid this problem; the easiest fix is to design the network
2851  * protocol such that the client will never send data "out of turn".
2852  * Another solution is for the server to half-close the connection by
2853  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2854  * and then wait for the client to notice this and close its side of the
2855  * connection, after which the server can safely call g_socket_close().
2856  * (This is what #GTcpConnection does if you call
2857  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2858  * only works if the client will close its connection after the server
2859  * does.)
2860  *
2861  * Returns: %TRUE on success, %FALSE on error
2862  *
2863  * Since: 2.22
2864  */
2865 gboolean
2866 g_socket_close (GSocket  *socket,
2867                 GError  **error)
2868 {
2869   int res;
2870
2871   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2872
2873   if (socket->priv->closed)
2874     return TRUE; /* Multiple close not an error */
2875
2876   if (!check_socket (socket, error))
2877     return FALSE;
2878
2879   while (1)
2880     {
2881 #ifdef G_OS_WIN32
2882       res = closesocket (socket->priv->fd);
2883 #else
2884       res = close (socket->priv->fd);
2885 #endif
2886       if (res == -1)
2887         {
2888           int errsv = get_socket_errno ();
2889
2890           if (errsv == EINTR)
2891             continue;
2892
2893           g_set_error (error, G_IO_ERROR,
2894                        socket_io_error_from_errno (errsv),
2895                        _("Error closing socket: %s"),
2896                        socket_strerror (errsv));
2897           return FALSE;
2898         }
2899       break;
2900     }
2901
2902   socket->priv->connected = FALSE;
2903   socket->priv->closed = TRUE;
2904   if (socket->priv->remote_address)
2905     {
2906       g_object_unref (socket->priv->remote_address);
2907       socket->priv->remote_address = NULL;
2908     }
2909
2910   return TRUE;
2911 }
2912
2913 /**
2914  * g_socket_is_closed:
2915  * @socket: a #GSocket
2916  *
2917  * Checks whether a socket is closed.
2918  *
2919  * Returns: %TRUE if socket is closed, %FALSE otherwise
2920  *
2921  * Since: 2.22
2922  */
2923 gboolean
2924 g_socket_is_closed (GSocket *socket)
2925 {
2926   return socket->priv->closed;
2927 }
2928
2929 #ifdef G_OS_WIN32
2930 /* Broken source, used on errors */
2931 static gboolean
2932 broken_prepare  (GSource *source,
2933                  gint    *timeout)
2934 {
2935   return FALSE;
2936 }
2937
2938 static gboolean
2939 broken_check (GSource *source)
2940 {
2941   return FALSE;
2942 }
2943
2944 static gboolean
2945 broken_dispatch (GSource     *source,
2946                  GSourceFunc  callback,
2947                  gpointer     user_data)
2948 {
2949   return TRUE;
2950 }
2951
2952 static GSourceFuncs broken_funcs =
2953 {
2954   broken_prepare,
2955   broken_check,
2956   broken_dispatch,
2957   NULL
2958 };
2959
2960 static gint
2961 network_events_for_condition (GIOCondition condition)
2962 {
2963   int event_mask = 0;
2964
2965   if (condition & G_IO_IN)
2966     event_mask |= (FD_READ | FD_ACCEPT);
2967   if (condition & G_IO_OUT)
2968     event_mask |= (FD_WRITE | FD_CONNECT);
2969   event_mask |= FD_CLOSE;
2970
2971   return event_mask;
2972 }
2973
2974 static void
2975 ensure_event (GSocket *socket)
2976 {
2977   if (socket->priv->event == WSA_INVALID_EVENT)
2978     socket->priv->event = WSACreateEvent();
2979 }
2980
2981 static void
2982 update_select_events (GSocket *socket)
2983 {
2984   int event_mask;
2985   GIOCondition *ptr;
2986   GList *l;
2987   WSAEVENT event;
2988
2989   ensure_event (socket);
2990
2991   event_mask = 0;
2992   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2993     {
2994       ptr = l->data;
2995       event_mask |= network_events_for_condition (*ptr);
2996     }
2997
2998   if (event_mask != socket->priv->selected_events)
2999     {
3000       /* If no events selected, disable event so we can unset
3001          nonblocking mode */
3002
3003       if (event_mask == 0)
3004         event = NULL;
3005       else
3006         event = socket->priv->event;
3007
3008       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3009         socket->priv->selected_events = event_mask;
3010     }
3011 }
3012
3013 static void
3014 add_condition_watch (GSocket      *socket,
3015                      GIOCondition *condition)
3016 {
3017   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3018
3019   socket->priv->requested_conditions =
3020     g_list_prepend (socket->priv->requested_conditions, condition);
3021
3022   update_select_events (socket);
3023 }
3024
3025 static void
3026 remove_condition_watch (GSocket      *socket,
3027                         GIOCondition *condition)
3028 {
3029   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3030
3031   socket->priv->requested_conditions =
3032     g_list_remove (socket->priv->requested_conditions, condition);
3033
3034   update_select_events (socket);
3035 }
3036
3037 static GIOCondition
3038 update_condition (GSocket *socket)
3039 {
3040   WSANETWORKEVENTS events;
3041   GIOCondition condition;
3042
3043   if (WSAEnumNetworkEvents (socket->priv->fd,
3044                             socket->priv->event,
3045                             &events) == 0)
3046     {
3047       socket->priv->current_events |= events.lNetworkEvents;
3048       if (events.lNetworkEvents & FD_WRITE &&
3049           events.iErrorCode[FD_WRITE_BIT] != 0)
3050         socket->priv->current_errors |= FD_WRITE;
3051       if (events.lNetworkEvents & FD_CONNECT &&
3052           events.iErrorCode[FD_CONNECT_BIT] != 0)
3053         socket->priv->current_errors |= FD_CONNECT;
3054     }
3055
3056   condition = 0;
3057   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3058     condition |= G_IO_IN;
3059
3060   if (socket->priv->current_events & FD_CLOSE)
3061     {
3062       int r, errsv, buffer;
3063
3064       r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3065       if (r < 0)
3066           errsv = get_socket_errno ();
3067
3068       if (r > 0 ||
3069           (r < 0 && errsv == WSAENOTCONN))
3070         condition |= G_IO_IN;
3071       else if (r == 0 ||
3072                (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3073                           errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3074         condition |= G_IO_HUP;
3075       else
3076         condition |= G_IO_ERR;
3077     }
3078
3079   if (socket->priv->closed)
3080     condition |= G_IO_HUP;
3081
3082   /* Never report both G_IO_OUT and HUP, these are
3083      mutually exclusive (can't write to a closed socket) */
3084   if ((condition & G_IO_HUP) == 0 &&
3085       socket->priv->current_events & FD_WRITE)
3086     {
3087       if (socket->priv->current_errors & FD_WRITE)
3088         condition |= G_IO_ERR;
3089       else
3090         condition |= G_IO_OUT;
3091     }
3092   else
3093     {
3094       if (socket->priv->current_events & FD_CONNECT)
3095         {
3096           if (socket->priv->current_errors & FD_CONNECT)
3097             condition |= (G_IO_HUP | G_IO_ERR);
3098           else
3099             condition |= G_IO_OUT;
3100         }
3101     }
3102
3103   return condition;
3104 }
3105 #endif
3106
3107 typedef struct {
3108   GSource       source;
3109   GPollFD       pollfd;
3110   GSocket      *socket;
3111   GIOCondition  condition;
3112   GCancellable *cancellable;
3113   GPollFD       cancel_pollfd;
3114   gint64        timeout_time;
3115 } GSocketSource;
3116
3117 static gboolean
3118 socket_source_prepare (GSource *source,
3119                        gint    *timeout)
3120 {
3121   GSocketSource *socket_source = (GSocketSource *)source;
3122
3123   if (g_cancellable_is_cancelled (socket_source->cancellable))
3124     return TRUE;
3125
3126   if (socket_source->timeout_time)
3127     {
3128       gint64 now;
3129
3130       now = g_source_get_time (source);
3131       /* Round up to ensure that we don't try again too early */
3132       *timeout = (socket_source->timeout_time - now + 999) / 1000;
3133       if (*timeout < 0)
3134         {
3135           socket_source->socket->priv->timed_out = TRUE;
3136           *timeout = 0;
3137           return TRUE;
3138         }
3139     }
3140   else
3141     *timeout = -1;
3142
3143 #ifdef G_OS_WIN32
3144   socket_source->pollfd.revents = update_condition (socket_source->socket);
3145 #endif
3146
3147   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3148     return TRUE;
3149
3150   return FALSE;
3151 }
3152
3153 static gboolean
3154 socket_source_check (GSource *source)
3155 {
3156   int timeout;
3157
3158   return socket_source_prepare (source, &timeout);
3159 }
3160
3161 static gboolean
3162 socket_source_dispatch (GSource     *source,
3163                         GSourceFunc  callback,
3164                         gpointer     user_data)
3165 {
3166   GSocketSourceFunc func = (GSocketSourceFunc)callback;
3167   GSocketSource *socket_source = (GSocketSource *)source;
3168   GSocket *socket = socket_source->socket;
3169   gboolean ret;
3170
3171 #ifdef G_OS_WIN32
3172   socket_source->pollfd.revents = update_condition (socket_source->socket);
3173 #endif
3174   if (socket_source->socket->priv->timed_out)
3175     socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3176
3177   ret = (*func) (socket,
3178                  socket_source->pollfd.revents & socket_source->condition,
3179                  user_data);
3180
3181   if (socket->priv->timeout)
3182     socket_source->timeout_time = g_get_monotonic_time () +
3183                                   socket->priv->timeout * 1000000;
3184
3185   else
3186     socket_source->timeout_time = 0;
3187
3188   return ret;
3189 }
3190
3191 static void
3192 socket_source_finalize (GSource *source)
3193 {
3194   GSocketSource *socket_source = (GSocketSource *)source;
3195   GSocket *socket;
3196
3197   socket = socket_source->socket;
3198
3199 #ifdef G_OS_WIN32
3200   remove_condition_watch (socket, &socket_source->condition);
3201 #endif
3202
3203   g_object_unref (socket);
3204
3205   if (socket_source->cancellable)
3206     {
3207       g_cancellable_release_fd (socket_source->cancellable);
3208       g_object_unref (socket_source->cancellable);
3209     }
3210 }
3211
3212 static gboolean
3213 socket_source_closure_callback (GSocket      *socket,
3214                                 GIOCondition  condition,
3215                                 gpointer      data)
3216 {
3217   GClosure *closure = data;
3218
3219   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3220   GValue result_value = G_VALUE_INIT;
3221   gboolean result;
3222
3223   g_value_init (&result_value, G_TYPE_BOOLEAN);
3224
3225   g_value_init (&params[0], G_TYPE_SOCKET);
3226   g_value_set_object (&params[0], socket);
3227   g_value_init (&params[1], G_TYPE_IO_CONDITION);
3228   g_value_set_flags (&params[1], condition);
3229
3230   g_closure_invoke (closure, &result_value, 2, params, NULL);
3231
3232   result = g_value_get_boolean (&result_value);
3233   g_value_unset (&result_value);
3234   g_value_unset (&params[0]);
3235   g_value_unset (&params[1]);
3236
3237   return result;
3238 }
3239
3240 static GSourceFuncs socket_source_funcs =
3241 {
3242   socket_source_prepare,
3243   socket_source_check,
3244   socket_source_dispatch,
3245   socket_source_finalize,
3246   (GSourceFunc)socket_source_closure_callback,
3247   (GSourceDummyMarshal)g_cclosure_marshal_generic,
3248 };
3249
3250 static GSource *
3251 socket_source_new (GSocket      *socket,
3252                    GIOCondition  condition,
3253                    GCancellable *cancellable)
3254 {
3255   GSource *source;
3256   GSocketSource *socket_source;
3257
3258 #ifdef G_OS_WIN32
3259   ensure_event (socket);
3260
3261   if (socket->priv->event == WSA_INVALID_EVENT)
3262     {
3263       g_warning ("Failed to create WSAEvent");
3264       return g_source_new (&broken_funcs, sizeof (GSource));
3265     }
3266 #endif
3267
3268   condition |= G_IO_HUP | G_IO_ERR;
3269
3270   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3271   g_source_set_name (source, "GSocket");
3272   socket_source = (GSocketSource *)source;
3273
3274   socket_source->socket = g_object_ref (socket);
3275   socket_source->condition = condition;
3276
3277   if (g_cancellable_make_pollfd (cancellable,
3278                                  &socket_source->cancel_pollfd))
3279     {
3280       socket_source->cancellable = g_object_ref (cancellable);
3281       g_source_add_poll (source, &socket_source->cancel_pollfd);
3282     }
3283
3284 #ifdef G_OS_WIN32
3285   add_condition_watch (socket, &socket_source->condition);
3286   socket_source->pollfd.fd = (gintptr) socket->priv->event;
3287 #else
3288   socket_source->pollfd.fd = socket->priv->fd;
3289 #endif
3290
3291   socket_source->pollfd.events = condition;
3292   socket_source->pollfd.revents = 0;
3293   g_source_add_poll (source, &socket_source->pollfd);
3294
3295   if (socket->priv->timeout)
3296     socket_source->timeout_time = g_get_monotonic_time () +
3297                                   socket->priv->timeout * 1000000;
3298
3299   else
3300     socket_source->timeout_time = 0;
3301
3302   return source;
3303 }
3304
3305 /**
3306  * g_socket_create_source: (skip)
3307  * @socket: a #GSocket
3308  * @condition: a #GIOCondition mask to monitor
3309  * @cancellable: (allow-none): a %GCancellable or %NULL
3310  *
3311  * Creates a %GSource that can be attached to a %GMainContext to monitor
3312  * for the availibility of the specified @condition on the socket.
3313  *
3314  * The callback on the source is of the #GSocketSourceFunc type.
3315  *
3316  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3317  * these conditions will always be reported output if they are true.
3318  *
3319  * @cancellable if not %NULL can be used to cancel the source, which will
3320  * cause the source to trigger, reporting the current condition (which
3321  * is likely 0 unless cancellation happened at the same time as a
3322  * condition change). You can check for this in the callback using
3323  * g_cancellable_is_cancelled().
3324  *
3325  * If @socket has a timeout set, and it is reached before @condition
3326  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3327  * %G_IO_OUT depending on @condition. However, @socket will have been
3328  * marked as having had a timeout, and so the next #GSocket I/O method
3329  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3330  *
3331  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3332  *
3333  * Since: 2.22
3334  */
3335 GSource *
3336 g_socket_create_source (GSocket      *socket,
3337                         GIOCondition  condition,
3338                         GCancellable *cancellable)
3339 {
3340   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3341
3342   return socket_source_new (socket, condition, cancellable);
3343 }
3344
3345 /**
3346  * g_socket_condition_check:
3347  * @socket: a #GSocket
3348  * @condition: a #GIOCondition mask to check
3349  *
3350  * Checks on the readiness of @socket to perform operations.
3351  * The operations specified in @condition are checked for and masked
3352  * against the currently-satisfied conditions on @socket. The result
3353  * is returned.
3354  *
3355  * Note that on Windows, it is possible for an operation to return
3356  * %G_IO_ERROR_WOULD_BLOCK even immediately after
3357  * g_socket_condition_check() has claimed that the socket is ready for
3358  * writing. Rather than calling g_socket_condition_check() and then
3359  * writing to the socket if it succeeds, it is generally better to
3360  * simply try writing to the socket right away, and try again later if
3361  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3362  *
3363  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3364  * these conditions will always be set in the output if they are true.
3365  *
3366  * This call never blocks.
3367  *
3368  * Returns: the @GIOCondition mask of the current state
3369  *
3370  * Since: 2.22
3371  */
3372 GIOCondition
3373 g_socket_condition_check (GSocket      *socket,
3374                           GIOCondition  condition)
3375 {
3376   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3377
3378   if (!check_socket (socket, NULL))
3379     return 0;
3380
3381 #ifdef G_OS_WIN32
3382   {
3383     GIOCondition current_condition;
3384
3385     condition |= G_IO_ERR | G_IO_HUP;
3386
3387     add_condition_watch (socket, &condition);
3388     current_condition = update_condition (socket);
3389     remove_condition_watch (socket, &condition);
3390     return condition & current_condition;
3391   }
3392 #else
3393   {
3394     GPollFD poll_fd;
3395     gint result;
3396     poll_fd.fd = socket->priv->fd;
3397     poll_fd.events = condition;
3398     poll_fd.revents = 0;
3399
3400     do
3401       result = g_poll (&poll_fd, 1, 0);
3402     while (result == -1 && get_socket_errno () == EINTR);
3403
3404     return poll_fd.revents;
3405   }
3406 #endif
3407 }
3408
3409 /**
3410  * g_socket_condition_wait:
3411  * @socket: a #GSocket
3412  * @condition: a #GIOCondition mask to wait for
3413  * @cancellable: (allow-none): a #GCancellable, or %NULL
3414  * @error: a #GError pointer, or %NULL
3415  *
3416  * Waits for @condition to become true on @socket. When the condition
3417  * is met, %TRUE is returned.
3418  *
3419  * If @cancellable is cancelled before the condition is met, or if the
3420  * socket has a timeout set and it is reached before the condition is
3421  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3422  * the appropriate value (%G_IO_ERROR_CANCELLED or
3423  * %G_IO_ERROR_TIMED_OUT).
3424  *
3425  * See also g_socket_condition_timed_wait().
3426  *
3427  * Returns: %TRUE if the condition was met, %FALSE otherwise
3428  *
3429  * Since: 2.22
3430  */
3431 gboolean
3432 g_socket_condition_wait (GSocket       *socket,
3433                          GIOCondition   condition,
3434                          GCancellable  *cancellable,
3435                          GError       **error)
3436 {
3437   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3438
3439   return g_socket_condition_timed_wait (socket, condition, -1,
3440                                         cancellable, error);
3441 }
3442
3443 /**
3444  * g_socket_condition_timed_wait:
3445  * @socket: a #GSocket
3446  * @condition: a #GIOCondition mask to wait for
3447  * @timeout: the maximum time (in microseconds) to wait, or -1
3448  * @cancellable: (allow-none): a #GCancellable, or %NULL
3449  * @error: a #GError pointer, or %NULL
3450  *
3451  * Waits for up to @timeout microseconds for @condition to become true
3452  * on @socket. If the condition is met, %TRUE is returned.
3453  *
3454  * If @cancellable is cancelled before the condition is met, or if
3455  * @timeout (or the socket's #GSocket:timeout) is reached before the
3456  * condition is met, then %FALSE is returned and @error, if non-%NULL,
3457  * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3458  * %G_IO_ERROR_TIMED_OUT).
3459  *
3460  * If you don't want a timeout, use g_socket_condition_wait().
3461  * (Alternatively, you can pass -1 for @timeout.)
3462  *
3463  * Note that although @timeout is in microseconds for consistency with
3464  * other GLib APIs, this function actually only has millisecond
3465  * resolution, and the behavior is undefined if @timeout is not an
3466  * exact number of milliseconds.
3467  *
3468  * Returns: %TRUE if the condition was met, %FALSE otherwise
3469  *
3470  * Since: 2.32
3471  */
3472 gboolean
3473 g_socket_condition_timed_wait (GSocket       *socket,
3474                                GIOCondition   condition,
3475                                gint64         timeout,
3476                                GCancellable  *cancellable,
3477                                GError       **error)
3478 {
3479   gint64 start_time;
3480
3481   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3482
3483   if (!check_socket (socket, error))
3484     return FALSE;
3485
3486   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3487     return FALSE;
3488
3489   if (socket->priv->timeout &&
3490       (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3491     timeout = socket->priv->timeout * 1000;
3492   else if (timeout != -1)
3493     timeout = timeout / 1000;
3494
3495   start_time = g_get_monotonic_time ();
3496
3497 #ifdef G_OS_WIN32
3498   {
3499     GIOCondition current_condition;
3500     WSAEVENT events[2];
3501     DWORD res;
3502     GPollFD cancel_fd;
3503     int num_events;
3504
3505     /* Always check these */
3506     condition |=  G_IO_ERR | G_IO_HUP;
3507
3508     add_condition_watch (socket, &condition);
3509
3510     num_events = 0;
3511     events[num_events++] = socket->priv->event;
3512
3513     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3514       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3515
3516     if (timeout == -1)
3517       timeout = WSA_INFINITE;
3518
3519     current_condition = update_condition (socket);
3520     while ((condition & current_condition) == 0)
3521       {
3522         res = WSAWaitForMultipleEvents (num_events, events,
3523                                         FALSE, timeout, FALSE);
3524         if (res == WSA_WAIT_FAILED)
3525           {
3526             int errsv = get_socket_errno ();
3527
3528             g_set_error (error, G_IO_ERROR,
3529                          socket_io_error_from_errno (errsv),
3530                          _("Waiting for socket condition: %s"),
3531                          socket_strerror (errsv));
3532             break;
3533           }
3534         else if (res == WSA_WAIT_TIMEOUT)
3535           {
3536             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3537                                  _("Socket I/O timed out"));
3538             break;
3539           }
3540
3541         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3542           break;
3543
3544         current_condition = update_condition (socket);
3545
3546         if (timeout != WSA_INFINITE)
3547           {
3548             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3549             if (timeout < 0)
3550               timeout = 0;
3551           }
3552       }
3553     remove_condition_watch (socket, &condition);
3554     if (num_events > 1)
3555       g_cancellable_release_fd (cancellable);
3556
3557     return (condition & current_condition) != 0;
3558   }
3559 #else
3560   {
3561     GPollFD poll_fd[2];
3562     gint result;
3563     gint num;
3564
3565     poll_fd[0].fd = socket->priv->fd;
3566     poll_fd[0].events = condition;
3567     num = 1;
3568
3569     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3570       num++;
3571
3572     while (TRUE)
3573       {
3574         result = g_poll (poll_fd, num, timeout);
3575         if (result != -1 || errno != EINTR)
3576           break;
3577
3578         if (timeout != -1)
3579           {
3580             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3581             if (timeout < 0)
3582               timeout = 0;
3583           }
3584       }
3585     
3586     if (num > 1)
3587       g_cancellable_release_fd (cancellable);
3588
3589     if (result == 0)
3590       {
3591         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3592                              _("Socket I/O timed out"));
3593         return FALSE;
3594       }
3595
3596     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3597   }
3598   #endif
3599 }
3600
3601 /**
3602  * g_socket_send_message:
3603  * @socket: a #GSocket
3604  * @address: (allow-none): a #GSocketAddress, or %NULL
3605  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3606  * @num_vectors: the number of elements in @vectors, or -1
3607  * @messages: (array length=num_messages) (allow-none): a pointer to an
3608  *   array of #GSocketControlMessages, or %NULL.
3609  * @num_messages: number of elements in @messages, or -1.
3610  * @flags: an int containing #GSocketMsgFlags flags
3611  * @cancellable: (allow-none): a %GCancellable or %NULL
3612  * @error: #GError for error reporting, or %NULL to ignore.
3613  *
3614  * Send data to @address on @socket.  This is the most complicated and
3615  * fully-featured version of this call. For easier use, see
3616  * g_socket_send() and g_socket_send_to().
3617  *
3618  * If @address is %NULL then the message is sent to the default receiver
3619  * (set by g_socket_connect()).
3620  *
3621  * @vectors must point to an array of #GOutputVector structs and
3622  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3623  * then @vectors is assumed to be terminated by a #GOutputVector with a
3624  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3625  * that the sent data will be gathered from. Using multiple
3626  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3627  * data from multiple sources into a single buffer, and more
3628  * network-efficient than making multiple calls to g_socket_send().
3629  *
3630  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3631  * #GSocketControlMessage instances. These correspond to the control
3632  * messages to be sent on the socket.
3633  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3634  * array.
3635  *
3636  * @flags modify how the message is sent. The commonly available arguments
3637  * for this are available in the #GSocketMsgFlags enum, but the
3638  * values there are the same as the system values, and the flags
3639  * are passed in as-is, so you can pass in system-specific flags too.
3640  *
3641  * If the socket is in blocking mode the call will block until there is
3642  * space for the data in the socket queue. If there is no space available
3643  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3644  * will be returned. To be notified when space is available, wait for the
3645  * %G_IO_OUT condition. Note though that you may still receive
3646  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3647  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3648  * very common due to the way the underlying APIs work.)
3649  *
3650  * On error -1 is returned and @error is set accordingly.
3651  *
3652  * Returns: Number of bytes written (which may be less than @size), or -1
3653  * on error
3654  *
3655  * Since: 2.22
3656  */
3657 gssize
3658 g_socket_send_message (GSocket                *socket,
3659                        GSocketAddress         *address,
3660                        GOutputVector          *vectors,
3661                        gint                    num_vectors,
3662                        GSocketControlMessage **messages,
3663                        gint                    num_messages,
3664                        gint                    flags,
3665                        GCancellable           *cancellable,
3666                        GError                **error)
3667 {
3668   GOutputVector one_vector;
3669   char zero;
3670
3671   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3672
3673   if (!check_socket (socket, error))
3674     return -1;
3675
3676   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3677     return -1;
3678
3679   if (num_vectors == -1)
3680     {
3681       for (num_vectors = 0;
3682            vectors[num_vectors].buffer != NULL;
3683            num_vectors++)
3684         ;
3685     }
3686
3687   if (num_messages == -1)
3688     {
3689       for (num_messages = 0;
3690            messages != NULL && messages[num_messages] != NULL;
3691            num_messages++)
3692         ;
3693     }
3694
3695   if (num_vectors == 0)
3696     {
3697       zero = '\0';
3698
3699       one_vector.buffer = &zero;
3700       one_vector.size = 1;
3701       num_vectors = 1;
3702       vectors = &one_vector;
3703     }
3704
3705 #ifndef G_OS_WIN32
3706   {
3707     struct msghdr msg;
3708     gssize result;
3709
3710    msg.msg_flags = 0;
3711
3712     /* name */
3713     if (address)
3714       {
3715         msg.msg_namelen = g_socket_address_get_native_size (address);
3716         msg.msg_name = g_alloca (msg.msg_namelen);
3717         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3718           return -1;
3719       }
3720     else
3721       {
3722         msg.msg_name = NULL;
3723         msg.msg_namelen = 0;
3724       }
3725
3726     /* iov */
3727     {
3728       /* this entire expression will be evaluated at compile time */
3729       if (sizeof *msg.msg_iov == sizeof *vectors &&
3730           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3731           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3732           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3733           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3734           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3735           G_STRUCT_OFFSET (GOutputVector, size))
3736         /* ABI is compatible */
3737         {
3738           msg.msg_iov = (struct iovec *) vectors;
3739           msg.msg_iovlen = num_vectors;
3740         }
3741       else
3742         /* ABI is incompatible */
3743         {
3744           gint i;
3745
3746           msg.msg_iov = g_newa (struct iovec, num_vectors);
3747           for (i = 0; i < num_vectors; i++)
3748             {
3749               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3750               msg.msg_iov[i].iov_len = vectors[i].size;
3751             }
3752           msg.msg_iovlen = num_vectors;
3753         }
3754     }
3755
3756     /* control */
3757     {
3758       struct cmsghdr *cmsg;
3759       gint i;
3760
3761       msg.msg_controllen = 0;
3762       for (i = 0; i < num_messages; i++)
3763         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3764
3765       if (msg.msg_controllen == 0)
3766         msg.msg_control = NULL;
3767       else
3768         {
3769           msg.msg_control = g_alloca (msg.msg_controllen);
3770           memset (msg.msg_control, '\0', msg.msg_controllen);
3771         }
3772
3773       cmsg = CMSG_FIRSTHDR (&msg);
3774       for (i = 0; i < num_messages; i++)
3775         {
3776           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3777           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3778           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3779           g_socket_control_message_serialize (messages[i],
3780                                               CMSG_DATA (cmsg));
3781           cmsg = CMSG_NXTHDR (&msg, cmsg);
3782         }
3783       g_assert (cmsg == NULL);
3784     }
3785
3786     while (1)
3787       {
3788         if (socket->priv->blocking &&
3789             !g_socket_condition_wait (socket,
3790                                       G_IO_OUT, cancellable, error))
3791           return -1;
3792
3793         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3794         if (result < 0)
3795           {
3796             int errsv = get_socket_errno ();
3797
3798             if (errsv == EINTR)
3799               continue;
3800
3801             if (socket->priv->blocking &&
3802                 (errsv == EWOULDBLOCK ||
3803                  errsv == EAGAIN))
3804               continue;
3805
3806             g_set_error (error, G_IO_ERROR,
3807                          socket_io_error_from_errno (errsv),
3808                          _("Error sending message: %s"), socket_strerror (errsv));
3809
3810             return -1;
3811           }
3812         break;
3813       }
3814
3815     return result;
3816   }
3817 #else
3818   {
3819     struct sockaddr_storage addr;
3820     guint addrlen;
3821     DWORD bytes_sent;
3822     int result;
3823     WSABUF *bufs;
3824     gint i;
3825
3826     /* Win32 doesn't support control messages.
3827        Actually this is possible for raw and datagram sockets
3828        via WSASendMessage on Vista or later, but that doesn't
3829        seem very useful */
3830     if (num_messages != 0)
3831       {
3832         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3833                              _("GSocketControlMessage not supported on Windows"));
3834         return -1;
3835       }
3836
3837     /* iov */
3838     bufs = g_newa (WSABUF, num_vectors);
3839     for (i = 0; i < num_vectors; i++)
3840       {
3841         bufs[i].buf = (char *)vectors[i].buffer;
3842         bufs[i].len = (gulong)vectors[i].size;
3843       }
3844
3845     /* name */
3846     addrlen = 0; /* Avoid warning */
3847     if (address)
3848       {
3849         addrlen = g_socket_address_get_native_size (address);
3850         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3851           return -1;
3852       }
3853
3854     while (1)
3855       {
3856         if (socket->priv->blocking &&
3857             !g_socket_condition_wait (socket,
3858                                       G_IO_OUT, cancellable, error))
3859           return -1;
3860
3861         if (address)
3862           result = WSASendTo (socket->priv->fd,
3863                               bufs, num_vectors,
3864                               &bytes_sent, flags,
3865                               (const struct sockaddr *)&addr, addrlen,
3866                               NULL, NULL);
3867         else
3868           result = WSASend (socket->priv->fd,
3869                             bufs, num_vectors,
3870                             &bytes_sent, flags,
3871                             NULL, NULL);
3872
3873         if (result != 0)
3874           {
3875             int errsv = get_socket_errno ();
3876
3877             if (errsv == WSAEINTR)
3878               continue;
3879
3880             if (errsv == WSAEWOULDBLOCK)
3881               win32_unset_event_mask (socket, FD_WRITE);
3882
3883             if (socket->priv->blocking &&
3884                 errsv == WSAEWOULDBLOCK)
3885               continue;
3886
3887             g_set_error (error, G_IO_ERROR,
3888                          socket_io_error_from_errno (errsv),
3889                          _("Error sending message: %s"), socket_strerror (errsv));
3890
3891             return -1;
3892           }
3893         break;
3894       }
3895
3896     return bytes_sent;
3897   }
3898 #endif
3899 }
3900
3901 /**
3902  * g_socket_receive_message:
3903  * @socket: a #GSocket
3904  * @address: (out) (allow-none): a pointer to a #GSocketAddress
3905  *     pointer, or %NULL
3906  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3907  * @num_vectors: the number of elements in @vectors, or -1
3908  * @messages: (array length=num_messages) (allow-none): a pointer which
3909  *    may be filled with an array of #GSocketControlMessages, or %NULL
3910  * @num_messages: a pointer which will be filled with the number of
3911  *    elements in @messages, or %NULL
3912  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3913  * @cancellable: (allow-none): a %GCancellable or %NULL
3914  * @error: a #GError pointer, or %NULL
3915  *
3916  * Receive data from a socket.  This is the most complicated and
3917  * fully-featured version of this call. For easier use, see
3918  * g_socket_receive() and g_socket_receive_from().
3919  *
3920  * If @address is non-%NULL then @address will be set equal to the
3921  * source address of the received packet.
3922  * @address is owned by the caller.
3923  *
3924  * @vector must point to an array of #GInputVector structs and
3925  * @num_vectors must be the length of this array.  These structs
3926  * describe the buffers that received data will be scattered into.
3927  * If @num_vectors is -1, then @vectors is assumed to be terminated
3928  * by a #GInputVector with a %NULL buffer pointer.
3929  *
3930  * As a special case, if @num_vectors is 0 (in which case, @vectors
3931  * may of course be %NULL), then a single byte is received and
3932  * discarded. This is to facilitate the common practice of sending a
3933  * single '\0' byte for the purposes of transferring ancillary data.
3934  *
3935  * @messages, if non-%NULL, will be set to point to a newly-allocated
3936  * array of #GSocketControlMessage instances or %NULL if no such
3937  * messages was received. These correspond to the control messages
3938  * received from the kernel, one #GSocketControlMessage per message
3939  * from the kernel. This array is %NULL-terminated and must be freed
3940  * by the caller using g_free() after calling g_object_unref() on each
3941  * element. If @messages is %NULL, any control messages received will
3942  * be discarded.
3943  *
3944  * @num_messages, if non-%NULL, will be set to the number of control
3945  * messages received.
3946  *
3947  * If both @messages and @num_messages are non-%NULL, then
3948  * @num_messages gives the number of #GSocketControlMessage instances
3949  * in @messages (ie: not including the %NULL terminator).
3950  *
3951  * @flags is an in/out parameter. The commonly available arguments
3952  * for this are available in the #GSocketMsgFlags enum, but the
3953  * values there are the same as the system values, and the flags
3954  * are passed in as-is, so you can pass in system-specific flags too
3955  * (and g_socket_receive_message() may pass system-specific flags out).
3956  *
3957  * As with g_socket_receive(), data may be discarded if @socket is
3958  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3959  * provide enough buffer space to read a complete message. You can pass
3960  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3961  * removing it from the receive queue, but there is no portable way to find
3962  * out the length of the message other than by reading it into a
3963  * sufficiently-large buffer.
3964  *
3965  * If the socket is in blocking mode the call will block until there
3966  * is some data to receive, the connection is closed, or there is an
3967  * error. If there is no data available and the socket is in
3968  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3969  * returned. To be notified when data is available, wait for the
3970  * %G_IO_IN condition.
3971  *
3972  * On error -1 is returned and @error is set accordingly.
3973  *
3974  * Returns: Number of bytes read, or 0 if the connection was closed by
3975  * the peer, or -1 on error
3976  *
3977  * Since: 2.22
3978  */
3979 gssize
3980 g_socket_receive_message (GSocket                 *socket,
3981                           GSocketAddress         **address,
3982                           GInputVector            *vectors,
3983                           gint                     num_vectors,
3984                           GSocketControlMessage ***messages,
3985                           gint                    *num_messages,
3986                           gint                    *flags,
3987                           GCancellable            *cancellable,
3988                           GError                 **error)
3989 {
3990   GInputVector one_vector;
3991   char one_byte;
3992
3993   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3994
3995   if (!check_socket (socket, error))
3996     return -1;
3997
3998   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3999     return -1;
4000
4001   if (num_vectors == -1)
4002     {
4003       for (num_vectors = 0;
4004            vectors[num_vectors].buffer != NULL;
4005            num_vectors++)
4006         ;
4007     }
4008
4009   if (num_vectors == 0)
4010     {
4011       one_vector.buffer = &one_byte;
4012       one_vector.size = 1;
4013       num_vectors = 1;
4014       vectors = &one_vector;
4015     }
4016
4017 #ifndef G_OS_WIN32
4018   {
4019     struct msghdr msg;
4020     gssize result;
4021     struct sockaddr_storage one_sockaddr;
4022
4023     /* name */
4024     if (address)
4025       {
4026         msg.msg_name = &one_sockaddr;
4027         msg.msg_namelen = sizeof (struct sockaddr_storage);
4028       }
4029     else
4030       {
4031         msg.msg_name = NULL;
4032         msg.msg_namelen = 0;
4033       }
4034
4035     /* iov */
4036     /* this entire expression will be evaluated at compile time */
4037     if (sizeof *msg.msg_iov == sizeof *vectors &&
4038         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4039         G_STRUCT_OFFSET (struct iovec, iov_base) ==
4040         G_STRUCT_OFFSET (GInputVector, buffer) &&
4041         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4042         G_STRUCT_OFFSET (struct iovec, iov_len) ==
4043         G_STRUCT_OFFSET (GInputVector, size))
4044       /* ABI is compatible */
4045       {
4046         msg.msg_iov = (struct iovec *) vectors;
4047         msg.msg_iovlen = num_vectors;
4048       }
4049     else
4050       /* ABI is incompatible */
4051       {
4052         gint i;
4053
4054         msg.msg_iov = g_newa (struct iovec, num_vectors);
4055         for (i = 0; i < num_vectors; i++)
4056           {
4057             msg.msg_iov[i].iov_base = vectors[i].buffer;
4058             msg.msg_iov[i].iov_len = vectors[i].size;
4059           }
4060         msg.msg_iovlen = num_vectors;
4061       }
4062
4063     /* control */
4064     msg.msg_control = g_alloca (2048);
4065     msg.msg_controllen = 2048;
4066
4067     /* flags */
4068     if (flags != NULL)
4069       msg.msg_flags = *flags;
4070     else
4071       msg.msg_flags = 0;
4072
4073     /* We always set the close-on-exec flag so we don't leak file
4074      * descriptors into child processes.  Note that gunixfdmessage.c
4075      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4076      */
4077 #ifdef MSG_CMSG_CLOEXEC
4078     msg.msg_flags |= MSG_CMSG_CLOEXEC;
4079 #endif
4080
4081     /* do it */
4082     while (1)
4083       {
4084         if (socket->priv->blocking &&
4085             !g_socket_condition_wait (socket,
4086                                       G_IO_IN, cancellable, error))
4087           return -1;
4088
4089         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4090 #ifdef MSG_CMSG_CLOEXEC 
4091         if (result < 0 && get_socket_errno () == EINVAL)
4092           {
4093             /* We must be running on an old kernel.  Call without the flag. */
4094             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4095             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4096           }
4097 #endif
4098
4099         if (result < 0)
4100           {
4101             int errsv = get_socket_errno ();
4102
4103             if (errsv == EINTR)
4104               continue;
4105
4106             if (socket->priv->blocking &&
4107                 (errsv == EWOULDBLOCK ||
4108                  errsv == EAGAIN))
4109               continue;
4110
4111             g_set_error (error, G_IO_ERROR,
4112                          socket_io_error_from_errno (errsv),
4113                          _("Error receiving message: %s"), socket_strerror (errsv));
4114
4115             return -1;
4116           }
4117         break;
4118       }
4119
4120     /* decode address */
4121     if (address != NULL)
4122       {
4123         if (msg.msg_namelen > 0)
4124           *address = g_socket_address_new_from_native (msg.msg_name,
4125                                                        msg.msg_namelen);
4126         else
4127           *address = NULL;
4128       }
4129
4130     /* decode control messages */
4131     {
4132       GPtrArray *my_messages = NULL;
4133       struct cmsghdr *cmsg;
4134
4135       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4136         {
4137           GSocketControlMessage *message;
4138
4139           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4140                                                           cmsg->cmsg_type,
4141                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4142                                                           CMSG_DATA (cmsg));
4143           if (message == NULL)
4144             /* We've already spewed about the problem in the
4145                deserialization code, so just continue */
4146             continue;
4147
4148           if (messages == NULL)
4149             {
4150               /* we have to do it this way if the user ignores the
4151                * messages so that we will close any received fds.
4152                */
4153               g_object_unref (message);
4154             }
4155           else
4156             {
4157               if (my_messages == NULL)
4158                 my_messages = g_ptr_array_new ();
4159               g_ptr_array_add (my_messages, message);
4160             }
4161         }
4162
4163       if (num_messages)
4164         *num_messages = my_messages != NULL ? my_messages->len : 0;
4165
4166       if (messages)
4167         {
4168           if (my_messages == NULL)
4169             {
4170               *messages = NULL;
4171             }
4172           else
4173             {
4174               g_ptr_array_add (my_messages, NULL);
4175               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4176             }
4177         }
4178       else
4179         {
4180           g_assert (my_messages == NULL);
4181         }
4182     }
4183
4184     /* capture the flags */
4185     if (flags != NULL)
4186       *flags = msg.msg_flags;
4187
4188     return result;
4189   }
4190 #else
4191   {
4192     struct sockaddr_storage addr;
4193     int addrlen;
4194     DWORD bytes_received;
4195     DWORD win_flags;
4196     int result;
4197     WSABUF *bufs;
4198     gint i;
4199
4200     /* iov */
4201     bufs = g_newa (WSABUF, num_vectors);
4202     for (i = 0; i < num_vectors; i++)
4203       {
4204         bufs[i].buf = (char *)vectors[i].buffer;
4205         bufs[i].len = (gulong)vectors[i].size;
4206       }
4207
4208     /* flags */
4209     if (flags != NULL)
4210       win_flags = *flags;
4211     else
4212       win_flags = 0;
4213
4214     /* do it */
4215     while (1)
4216       {
4217         if (socket->priv->blocking &&
4218             !g_socket_condition_wait (socket,
4219                                       G_IO_IN, cancellable, error))
4220           return -1;
4221
4222         addrlen = sizeof addr;
4223         if (address)
4224           result = WSARecvFrom (socket->priv->fd,
4225                                 bufs, num_vectors,
4226                                 &bytes_received, &win_flags,
4227                                 (struct sockaddr *)&addr, &addrlen,
4228                                 NULL, NULL);
4229         else
4230           result = WSARecv (socket->priv->fd,
4231                             bufs, num_vectors,
4232                             &bytes_received, &win_flags,
4233                             NULL, NULL);
4234         if (result != 0)
4235           {
4236             int errsv = get_socket_errno ();
4237
4238             if (errsv == WSAEINTR)
4239               continue;
4240
4241             win32_unset_event_mask (socket, FD_READ);
4242
4243             if (socket->priv->blocking &&
4244                 errsv == WSAEWOULDBLOCK)
4245               continue;
4246
4247             g_set_error (error, G_IO_ERROR,
4248                          socket_io_error_from_errno (errsv),
4249                          _("Error receiving message: %s"), socket_strerror (errsv));
4250
4251             return -1;
4252           }
4253         win32_unset_event_mask (socket, FD_READ);
4254         break;
4255       }
4256
4257     /* decode address */
4258     if (address != NULL)
4259       {
4260         if (addrlen > 0)
4261           *address = g_socket_address_new_from_native (&addr, addrlen);
4262         else
4263           *address = NULL;
4264       }
4265
4266     /* capture the flags */
4267     if (flags != NULL)
4268       *flags = win_flags;
4269
4270     if (messages != NULL)
4271       *messages = NULL;
4272     if (num_messages != NULL)
4273       *num_messages = 0;
4274
4275     return bytes_received;
4276   }
4277 #endif
4278 }
4279
4280 /**
4281  * g_socket_get_credentials:
4282  * @socket: a #GSocket.
4283  * @error: #GError for error reporting, or %NULL to ignore.
4284  *
4285  * Returns the credentials of the foreign process connected to this
4286  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4287  * sockets).
4288  *
4289  * If this operation isn't supported on the OS, the method fails with
4290  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4291  * by reading the %SO_PEERCRED option on the underlying socket.
4292  *
4293  * Other ways to obtain credentials from a foreign peer includes the
4294  * #GUnixCredentialsMessage type and
4295  * g_unix_connection_send_credentials() /
4296  * g_unix_connection_receive_credentials() functions.
4297  *
4298  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4299  * that must be freed with g_object_unref().
4300  *
4301  * Since: 2.26
4302  */
4303 GCredentials *
4304 g_socket_get_credentials (GSocket   *socket,
4305                           GError   **error)
4306 {
4307   GCredentials *ret;
4308
4309   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4310   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4311
4312   ret = NULL;
4313
4314 #if defined(__linux__) || defined(__OpenBSD__)
4315   {
4316     socklen_t optlen;
4317 #if defined(__linux__)
4318     struct ucred native_creds;
4319     optlen = sizeof (struct ucred);
4320 #elif defined(__OpenBSD__)
4321     struct sockpeercred native_creds;
4322     optlen = sizeof (struct sockpeercred);
4323 #endif
4324     if (getsockopt (socket->priv->fd,
4325                     SOL_SOCKET,
4326                     SO_PEERCRED,
4327                     (void *)&native_creds,
4328                     &optlen) != 0)
4329       {
4330         int errsv = get_socket_errno ();
4331         g_set_error (error,
4332                      G_IO_ERROR,
4333                      socket_io_error_from_errno (errsv),
4334                      _("Unable to get pending error: %s"),
4335                      socket_strerror (errsv));
4336       }
4337     else
4338       {
4339         ret = g_credentials_new ();
4340         g_credentials_set_native (ret,
4341 #if defined(__linux__)
4342                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
4343 #elif defined(__OpenBSD__)
4344                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4345 #endif
4346                                   &native_creds);
4347       }
4348   }
4349 #else
4350   g_set_error_literal (error,
4351                        G_IO_ERROR,
4352                        G_IO_ERROR_NOT_SUPPORTED,
4353                        _("g_socket_get_credentials not implemented for this OS"));
4354 #endif
4355
4356   return ret;
4357 }