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