Add glib credentials support to OpenBSD.
[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 #endif
45
46 #ifdef HAVE_SYS_UIO_H
47 #include <sys/uio.h>
48 #endif
49
50 #include "gcancellable.h"
51 #include "gioenumtypes.h"
52 #include "ginetaddress.h"
53 #include "ginitable.h"
54 #include "gioerror.h"
55 #include "gioenums.h"
56 #include "gioerror.h"
57 #include "gio-marshal.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 };
143
144 struct _GSocketPrivate
145 {
146   GSocketFamily   family;
147   GSocketType     type;
148   GSocketProtocol protocol;
149   gint            fd;
150   gint            listen_backlog;
151   guint           timeout;
152   GError         *construct_error;
153   GSocketAddress *remote_address;
154   guint           inited : 1;
155   guint           blocking : 1;
156   guint           keepalive : 1;
157   guint           closed : 1;
158   guint           connected : 1;
159   guint           listening : 1;
160   guint           timed_out : 1;
161   guint           connect_pending : 1;
162 #ifdef G_OS_WIN32
163   WSAEVENT        event;
164   int             current_events;
165   int             current_errors;
166   int             selected_events;
167   GList          *requested_conditions; /* list of requested GIOCondition * */
168 #endif
169 };
170
171 static int
172 get_socket_errno (void)
173 {
174 #ifndef G_OS_WIN32
175   return errno;
176 #else
177   return WSAGetLastError ();
178 #endif
179 }
180
181 static GIOErrorEnum
182 socket_io_error_from_errno (int err)
183 {
184 #ifndef G_OS_WIN32
185   return g_io_error_from_errno (err);
186 #else
187   switch (err)
188     {
189     case WSAEADDRINUSE:
190       return G_IO_ERROR_ADDRESS_IN_USE;
191     case WSAEWOULDBLOCK:
192       return G_IO_ERROR_WOULD_BLOCK;
193     case WSAEACCES:
194       return G_IO_ERROR_PERMISSION_DENIED;
195     case WSA_INVALID_HANDLE:
196     case WSA_INVALID_PARAMETER:
197     case WSAEBADF:
198     case WSAENOTSOCK:
199       return G_IO_ERROR_INVALID_ARGUMENT;
200     case WSAEPROTONOSUPPORT:
201       return G_IO_ERROR_NOT_SUPPORTED;
202     case WSAECANCELLED:
203       return G_IO_ERROR_CANCELLED;
204     case WSAESOCKTNOSUPPORT:
205     case WSAEOPNOTSUPP:
206     case WSAEPFNOSUPPORT:
207     case WSAEAFNOSUPPORT:
208       return G_IO_ERROR_NOT_SUPPORTED;
209     default:
210       return G_IO_ERROR_FAILED;
211     }
212 #endif
213 }
214
215 static const char *
216 socket_strerror (int err)
217 {
218 #ifndef G_OS_WIN32
219   return g_strerror (err);
220 #else
221   static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
222   char *msg;
223
224   msg = g_win32_error_message (err);
225   g_static_private_set (&last_msg, msg, g_free);
226
227   return msg;
228 #endif
229 }
230
231 #ifdef G_OS_WIN32
232 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
233 static void
234 _win32_unset_event_mask (GSocket *socket, int mask)
235 {
236   socket->priv->current_events &= ~mask;
237   socket->priv->current_errors &= ~mask;
238 }
239 #else
240 #define win32_unset_event_mask(_socket, _mask)
241 #endif
242
243 static void
244 set_fd_nonblocking (int fd)
245 {
246 #ifndef G_OS_WIN32
247   GError *error = NULL;
248 #else
249   gulong arg;
250 #endif
251
252 #ifndef G_OS_WIN32
253   if (!g_unix_set_fd_nonblocking (fd, TRUE, &error))
254     {
255       g_warning ("Error setting socket nonblocking: %s", error->message);
256       g_clear_error (&error);
257     }
258 #else
259   arg = TRUE;
260
261   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
262     {
263       int errsv = get_socket_errno ();
264       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
265     }
266 #endif
267 }
268
269 static gboolean
270 check_socket (GSocket *socket,
271               GError **error)
272 {
273   if (!socket->priv->inited)
274     {
275       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
276                            _("Invalid socket, not initialized"));
277       return FALSE;
278     }
279
280   if (socket->priv->construct_error)
281     {
282       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
283                    _("Invalid socket, initialization failed due to: %s"),
284                    socket->priv->construct_error->message);
285       return FALSE;
286     }
287
288   if (socket->priv->closed)
289     {
290       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
291                            _("Socket is already closed"));
292       return FALSE;
293     }
294
295   if (socket->priv->timed_out)
296     {
297       socket->priv->timed_out = FALSE;
298       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
299                            _("Socket I/O timed out"));
300       return FALSE;
301     }
302
303   return TRUE;
304 }
305
306 static void
307 g_socket_details_from_fd (GSocket *socket)
308 {
309   struct sockaddr_storage address;
310   gint fd;
311   guint addrlen;
312   guint optlen;
313   int value;
314   int errsv;
315 #ifdef G_OS_WIN32
316   /* See bug #611756 */
317   BOOL bool_val = FALSE;
318 #else
319   int bool_val;
320 #endif
321
322   fd = socket->priv->fd;
323   optlen = sizeof value;
324   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
325     {
326       errsv = get_socket_errno ();
327
328       switch (errsv)
329         {
330 #ifdef ENOTSOCK
331          case ENOTSOCK:
332 #endif
333 #ifdef WSAENOTSOCK
334          case WSAENOTSOCK:
335 #endif
336          case EBADF:
337           /* programmer error */
338           g_error ("creating GSocket from fd %d: %s\n",
339                    fd, socket_strerror (errsv));
340          default:
341            break;
342         }
343
344       goto err;
345     }
346
347   g_assert (optlen == sizeof value);
348   switch (value)
349     {
350      case SOCK_STREAM:
351       socket->priv->type = G_SOCKET_TYPE_STREAM;
352       break;
353
354      case SOCK_DGRAM:
355       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
356       break;
357
358      case SOCK_SEQPACKET:
359       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
360       break;
361
362      default:
363       socket->priv->type = G_SOCKET_TYPE_INVALID;
364       break;
365     }
366
367   addrlen = sizeof address;
368   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
369     {
370       errsv = get_socket_errno ();
371       goto err;
372     }
373
374   g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
375             sizeof address.ss_family <= addrlen);
376   switch (address.ss_family)
377     {
378      case G_SOCKET_FAMILY_IPV4:
379      case G_SOCKET_FAMILY_IPV6:
380        socket->priv->family = address.ss_family;
381        switch (socket->priv->type)
382          {
383          case G_SOCKET_TYPE_STREAM:
384            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
385            break;
386
387          case G_SOCKET_TYPE_DATAGRAM:
388            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
389            break;
390
391          case G_SOCKET_TYPE_SEQPACKET:
392            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
393            break;
394
395          default:
396            break;
397          }
398        break;
399
400      case G_SOCKET_FAMILY_UNIX:
401        socket->priv->family = G_SOCKET_FAMILY_UNIX;
402        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
403        break;
404
405      default:
406        socket->priv->family = G_SOCKET_FAMILY_INVALID;
407        break;
408     }
409
410   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
411     {
412       addrlen = sizeof address;
413       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
414         socket->priv->connected = TRUE;
415     }
416
417   optlen = sizeof bool_val;
418   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
419                   (void *)&bool_val, &optlen) == 0)
420     {
421 #ifndef G_OS_WIN32
422       /* Experimentation indicates that the SO_KEEPALIVE value is
423        * actually a char on Windows, even if documentation claims it
424        * to be a BOOL which is a typedef for int. So this g_assert()
425        * fails. See bug #611756.
426        */
427       g_assert (optlen == sizeof bool_val);
428 #endif
429       socket->priv->keepalive = !!bool_val;
430     }
431   else
432     {
433       /* Can't read, maybe not supported, assume FALSE */
434       socket->priv->keepalive = FALSE;
435     }
436
437   return;
438
439  err:
440   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
441                socket_io_error_from_errno (errsv),
442                _("creating GSocket from fd: %s"),
443                socket_strerror (errsv));
444 }
445
446 static gint
447 g_socket_create_socket (GSocketFamily   family,
448                         GSocketType     type,
449                         int             protocol,
450                         GError        **error)
451 {
452   gint native_type;
453   gint fd;
454
455   switch (type)
456     {
457      case G_SOCKET_TYPE_STREAM:
458       native_type = SOCK_STREAM;
459       break;
460
461      case G_SOCKET_TYPE_DATAGRAM:
462       native_type = SOCK_DGRAM;
463       break;
464
465      case G_SOCKET_TYPE_SEQPACKET:
466       native_type = SOCK_SEQPACKET;
467       break;
468
469      default:
470       g_assert_not_reached ();
471     }
472
473   if (protocol == -1)
474     {
475       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
476                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
477       return -1;
478     }
479
480 #ifdef SOCK_CLOEXEC
481   fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
482   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
483   if (fd < 0 && errno == EINVAL)
484 #endif
485     fd = socket (family, native_type, protocol);
486
487   if (fd < 0)
488     {
489       int errsv = get_socket_errno ();
490
491       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
492                    _("Unable to create socket: %s"), socket_strerror (errsv));
493     }
494
495 #ifndef G_OS_WIN32
496   {
497     int flags;
498
499     /* We always want to set close-on-exec to protect users. If you
500        need to so some weird inheritance to exec you can re-enable this
501        using lower level hacks with g_socket_get_fd(). */
502     flags = fcntl (fd, F_GETFD, 0);
503     if (flags != -1 &&
504         (flags & FD_CLOEXEC) == 0)
505       {
506         flags |= FD_CLOEXEC;
507         fcntl (fd, F_SETFD, flags);
508       }
509   }
510 #endif
511
512   return fd;
513 }
514
515 static void
516 g_socket_constructed (GObject *object)
517 {
518   GSocket *socket = G_SOCKET (object);
519
520   if (socket->priv->fd >= 0)
521     /* create socket->priv info from the fd */
522     g_socket_details_from_fd (socket);
523
524   else
525     /* create the fd from socket->priv info */
526     socket->priv->fd = g_socket_create_socket (socket->priv->family,
527                                                socket->priv->type,
528                                                socket->priv->protocol,
529                                                &socket->priv->construct_error);
530
531   /* Always use native nonblocking sockets, as
532      windows sets sockets to nonblocking automatically
533      in certain operations. This way we make things work
534      the same on all platforms */
535   if (socket->priv->fd != -1)
536     set_fd_nonblocking (socket->priv->fd);
537 }
538
539 static void
540 g_socket_get_property (GObject    *object,
541                        guint       prop_id,
542                        GValue     *value,
543                        GParamSpec *pspec)
544 {
545   GSocket *socket = G_SOCKET (object);
546   GSocketAddress *address;
547
548   switch (prop_id)
549     {
550       case PROP_FAMILY:
551         g_value_set_enum (value, socket->priv->family);
552         break;
553
554       case PROP_TYPE:
555         g_value_set_enum (value, socket->priv->type);
556         break;
557
558       case PROP_PROTOCOL:
559         g_value_set_enum (value, socket->priv->protocol);
560         break;
561
562       case PROP_FD:
563         g_value_set_int (value, socket->priv->fd);
564         break;
565
566       case PROP_BLOCKING:
567         g_value_set_boolean (value, socket->priv->blocking);
568         break;
569
570       case PROP_LISTEN_BACKLOG:
571         g_value_set_int (value, socket->priv->listen_backlog);
572         break;
573
574       case PROP_KEEPALIVE:
575         g_value_set_boolean (value, socket->priv->keepalive);
576         break;
577
578       case PROP_LOCAL_ADDRESS:
579         address = g_socket_get_local_address (socket, NULL);
580         g_value_take_object (value, address);
581         break;
582
583       case PROP_REMOTE_ADDRESS:
584         address = g_socket_get_remote_address (socket, NULL);
585         g_value_take_object (value, address);
586         break;
587
588       case PROP_TIMEOUT:
589         g_value_set_uint (value, socket->priv->timeout);
590         break;
591
592       default:
593         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
594     }
595 }
596
597 static void
598 g_socket_set_property (GObject      *object,
599                        guint         prop_id,
600                        const GValue *value,
601                        GParamSpec   *pspec)
602 {
603   GSocket *socket = G_SOCKET (object);
604
605   switch (prop_id)
606     {
607       case PROP_FAMILY:
608         socket->priv->family = g_value_get_enum (value);
609         break;
610
611       case PROP_TYPE:
612         socket->priv->type = g_value_get_enum (value);
613         break;
614
615       case PROP_PROTOCOL:
616         socket->priv->protocol = g_value_get_enum (value);
617         break;
618
619       case PROP_FD:
620         socket->priv->fd = g_value_get_int (value);
621         break;
622
623       case PROP_BLOCKING:
624         g_socket_set_blocking (socket, g_value_get_boolean (value));
625         break;
626
627       case PROP_LISTEN_BACKLOG:
628         g_socket_set_listen_backlog (socket, g_value_get_int (value));
629         break;
630
631       case PROP_KEEPALIVE:
632         g_socket_set_keepalive (socket, g_value_get_boolean (value));
633         break;
634
635       case PROP_TIMEOUT:
636         g_socket_set_timeout (socket, g_value_get_uint (value));
637         break;
638
639       default:
640         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
641     }
642 }
643
644 static void
645 g_socket_finalize (GObject *object)
646 {
647   GSocket *socket = G_SOCKET (object);
648
649   g_clear_error (&socket->priv->construct_error);
650
651   if (socket->priv->fd != -1 &&
652       !socket->priv->closed)
653     g_socket_close (socket, NULL);
654
655   if (socket->priv->remote_address)
656     g_object_unref (socket->priv->remote_address);
657
658 #ifdef G_OS_WIN32
659   if (socket->priv->event != WSA_INVALID_EVENT)
660     {
661       WSACloseEvent (socket->priv->event);
662       socket->priv->event = WSA_INVALID_EVENT;
663     }
664
665   g_assert (socket->priv->requested_conditions == NULL);
666 #endif
667
668   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
669     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
670 }
671
672 static void
673 g_socket_class_init (GSocketClass *klass)
674 {
675   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
676   volatile GType type;
677
678   /* Make sure winsock has been initialized */
679   type = g_inet_address_get_type ();
680   (type); /* To avoid -Wunused-but-set-variable */
681
682 #ifdef SIGPIPE
683   /* There is no portable, thread-safe way to avoid having the process
684    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
685    * forced to simply ignore the signal process-wide.
686    */
687   signal (SIGPIPE, SIG_IGN);
688 #endif
689
690   g_type_class_add_private (klass, sizeof (GSocketPrivate));
691
692   gobject_class->finalize = g_socket_finalize;
693   gobject_class->constructed = g_socket_constructed;
694   gobject_class->set_property = g_socket_set_property;
695   gobject_class->get_property = g_socket_get_property;
696
697   g_object_class_install_property (gobject_class, PROP_FAMILY,
698                                    g_param_spec_enum ("family",
699                                                       P_("Socket family"),
700                                                       P_("The sockets address family"),
701                                                       G_TYPE_SOCKET_FAMILY,
702                                                       G_SOCKET_FAMILY_INVALID,
703                                                       G_PARAM_CONSTRUCT_ONLY |
704                                                       G_PARAM_READWRITE |
705                                                       G_PARAM_STATIC_STRINGS));
706
707   g_object_class_install_property (gobject_class, PROP_TYPE,
708                                    g_param_spec_enum ("type",
709                                                       P_("Socket type"),
710                                                       P_("The sockets type"),
711                                                       G_TYPE_SOCKET_TYPE,
712                                                       G_SOCKET_TYPE_STREAM,
713                                                       G_PARAM_CONSTRUCT_ONLY |
714                                                       G_PARAM_READWRITE |
715                                                       G_PARAM_STATIC_STRINGS));
716
717   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
718                                    g_param_spec_enum ("protocol",
719                                                       P_("Socket protocol"),
720                                                       P_("The id of the protocol to use, or -1 for unknown"),
721                                                       G_TYPE_SOCKET_PROTOCOL,
722                                                       G_SOCKET_PROTOCOL_UNKNOWN,
723                                                       G_PARAM_CONSTRUCT_ONLY |
724                                                       G_PARAM_READWRITE |
725                                                       G_PARAM_STATIC_STRINGS));
726
727   g_object_class_install_property (gobject_class, PROP_FD,
728                                    g_param_spec_int ("fd",
729                                                      P_("File descriptor"),
730                                                      P_("The sockets file descriptor"),
731                                                      G_MININT,
732                                                      G_MAXINT,
733                                                      -1,
734                                                      G_PARAM_CONSTRUCT_ONLY |
735                                                      G_PARAM_READWRITE |
736                                                      G_PARAM_STATIC_STRINGS));
737
738   g_object_class_install_property (gobject_class, PROP_BLOCKING,
739                                    g_param_spec_boolean ("blocking",
740                                                          P_("blocking"),
741                                                          P_("Whether or not I/O on this socket is blocking"),
742                                                          TRUE,
743                                                          G_PARAM_READWRITE |
744                                                          G_PARAM_STATIC_STRINGS));
745
746   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
747                                    g_param_spec_int ("listen-backlog",
748                                                      P_("Listen backlog"),
749                                                      P_("Outstanding connections in the listen queue"),
750                                                      0,
751                                                      SOMAXCONN,
752                                                      10,
753                                                      G_PARAM_READWRITE |
754                                                      G_PARAM_STATIC_STRINGS));
755
756   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
757                                    g_param_spec_boolean ("keepalive",
758                                                          P_("Keep connection alive"),
759                                                          P_("Keep connection alive by sending periodic pings"),
760                                                          FALSE,
761                                                          G_PARAM_READWRITE |
762                                                          G_PARAM_STATIC_STRINGS));
763
764   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
765                                    g_param_spec_object ("local-address",
766                                                         P_("Local address"),
767                                                         P_("The local address the socket is bound to"),
768                                                         G_TYPE_SOCKET_ADDRESS,
769                                                         G_PARAM_READABLE |
770                                                         G_PARAM_STATIC_STRINGS));
771
772   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
773                                    g_param_spec_object ("remote-address",
774                                                         P_("Remote address"),
775                                                         P_("The remote address the socket is connected to"),
776                                                         G_TYPE_SOCKET_ADDRESS,
777                                                         G_PARAM_READABLE |
778                                                         G_PARAM_STATIC_STRINGS));
779
780   /**
781    * GSocket:timeout:
782    *
783    * The timeout in seconds on socket I/O
784    *
785    * Since: 2.26
786    */
787   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
788                                    g_param_spec_uint ("timeout",
789                                                       P_("Timeout"),
790                                                       P_("The timeout in seconds on socket I/O"),
791                                                       0,
792                                                       G_MAXUINT,
793                                                       0,
794                                                       G_PARAM_READWRITE |
795                                                       G_PARAM_STATIC_STRINGS));
796 }
797
798 static void
799 g_socket_initable_iface_init (GInitableIface *iface)
800 {
801   iface->init = g_socket_initable_init;
802 }
803
804 static void
805 g_socket_init (GSocket *socket)
806 {
807   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
808
809   socket->priv->fd = -1;
810   socket->priv->blocking = TRUE;
811   socket->priv->listen_backlog = 10;
812   socket->priv->construct_error = NULL;
813 #ifdef G_OS_WIN32
814   socket->priv->event = WSA_INVALID_EVENT;
815 #endif
816 }
817
818 static gboolean
819 g_socket_initable_init (GInitable *initable,
820                         GCancellable *cancellable,
821                         GError  **error)
822 {
823   GSocket  *socket;
824
825   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
826
827   socket = G_SOCKET (initable);
828
829   if (cancellable != NULL)
830     {
831       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
832                            _("Cancellable initialization not supported"));
833       return FALSE;
834     }
835
836   socket->priv->inited = TRUE;
837
838   if (socket->priv->construct_error)
839     {
840       if (error)
841         *error = g_error_copy (socket->priv->construct_error);
842       return FALSE;
843     }
844
845
846   return TRUE;
847 }
848
849 /**
850  * g_socket_new:
851  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
852  * @type: the socket type to use.
853  * @protocol: the id of the protocol to use, or 0 for default.
854  * @error: #GError for error reporting, or %NULL to ignore.
855  *
856  * Creates a new #GSocket with the defined family, type and protocol.
857  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
858  * for the family and type is used.
859  *
860  * The @protocol is a family and type specific int that specifies what
861  * kind of protocol to use. #GSocketProtocol lists several common ones.
862  * Many families only support one protocol, and use 0 for this, others
863  * support several and using 0 means to use the default protocol for
864  * the family and type.
865  *
866  * The protocol id is passed directly to the operating
867  * system, so you can use protocols not listed in #GSocketProtocol if you
868  * know the protocol number used for it.
869  *
870  * Returns: a #GSocket or %NULL on error.
871  *     Free the returned object with g_object_unref().
872  *
873  * Since: 2.22
874  */
875 GSocket *
876 g_socket_new (GSocketFamily     family,
877               GSocketType       type,
878               GSocketProtocol   protocol,
879               GError          **error)
880 {
881   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
882                                    NULL, error,
883                                    "family", family,
884                                    "type", type,
885                                    "protocol", protocol,
886                                    NULL));
887 }
888
889 /**
890  * g_socket_new_from_fd:
891  * @fd: a native socket file descriptor.
892  * @error: #GError for error reporting, or %NULL to ignore.
893  *
894  * Creates a new #GSocket from a native file descriptor
895  * or winsock SOCKET handle.
896  *
897  * This reads all the settings from the file descriptor so that
898  * all properties should work. Note that the file descriptor
899  * will be set to non-blocking mode, independent on the blocking
900  * mode of the #GSocket.
901  *
902  * Returns: a #GSocket or %NULL on error.
903  *     Free the returned object with g_object_unref().
904  *
905  * Since: 2.22
906  */
907 GSocket *
908 g_socket_new_from_fd (gint     fd,
909                       GError **error)
910 {
911   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
912                                    NULL, error,
913                                    "fd", fd,
914                                    NULL));
915 }
916
917 /**
918  * g_socket_set_blocking:
919  * @socket: a #GSocket.
920  * @blocking: Whether to use blocking I/O or not.
921  *
922  * Sets the blocking mode of the socket. In blocking mode
923  * all operations block until they succeed or there is an error. In
924  * non-blocking mode all functions return results immediately or
925  * with a %G_IO_ERROR_WOULD_BLOCK error.
926  *
927  * All sockets are created in blocking mode. However, note that the
928  * platform level socket is always non-blocking, and blocking mode
929  * is a GSocket level feature.
930  *
931  * Since: 2.22
932  */
933 void
934 g_socket_set_blocking (GSocket  *socket,
935                        gboolean  blocking)
936 {
937   g_return_if_fail (G_IS_SOCKET (socket));
938
939   blocking = !!blocking;
940
941   if (socket->priv->blocking == blocking)
942     return;
943
944   socket->priv->blocking = blocking;
945   g_object_notify (G_OBJECT (socket), "blocking");
946 }
947
948 /**
949  * g_socket_get_blocking:
950  * @socket: a #GSocket.
951  *
952  * Gets the blocking mode of the socket. For details on blocking I/O,
953  * see g_socket_set_blocking().
954  *
955  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
956  *
957  * Since: 2.22
958  */
959 gboolean
960 g_socket_get_blocking (GSocket *socket)
961 {
962   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
963
964   return socket->priv->blocking;
965 }
966
967 /**
968  * g_socket_set_keepalive:
969  * @socket: a #GSocket.
970  * @keepalive: Value for the keepalive flag
971  *
972  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
973  * this flag is set on a socket, the system will attempt to verify that the
974  * remote socket endpoint is still present if a sufficiently long period of
975  * time passes with no data being exchanged. If the system is unable to
976  * verify the presence of the remote endpoint, it will automatically close
977  * the connection.
978  *
979  * This option is only functional on certain kinds of sockets. (Notably,
980  * %G_SOCKET_PROTOCOL_TCP sockets.)
981  *
982  * The exact time between pings is system- and protocol-dependent, but will
983  * normally be at least two hours. Most commonly, you would set this flag
984  * on a server socket if you want to allow clients to remain idle for long
985  * periods of time, but also want to ensure that connections are eventually
986  * garbage-collected if clients crash or become unreachable.
987  *
988  * Since: 2.22
989  */
990 void
991 g_socket_set_keepalive (GSocket  *socket,
992                         gboolean  keepalive)
993 {
994   int value;
995
996   g_return_if_fail (G_IS_SOCKET (socket));
997
998   keepalive = !!keepalive;
999   if (socket->priv->keepalive == keepalive)
1000     return;
1001
1002   value = (gint) keepalive;
1003   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1004                   (gpointer) &value, sizeof (value)) < 0)
1005     {
1006       int errsv = get_socket_errno ();
1007       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1008       return;
1009     }
1010
1011   socket->priv->keepalive = keepalive;
1012   g_object_notify (G_OBJECT (socket), "keepalive");
1013 }
1014
1015 /**
1016  * g_socket_get_keepalive:
1017  * @socket: a #GSocket.
1018  *
1019  * Gets the keepalive mode of the socket. For details on this,
1020  * see g_socket_set_keepalive().
1021  *
1022  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1023  *
1024  * Since: 2.22
1025  */
1026 gboolean
1027 g_socket_get_keepalive (GSocket *socket)
1028 {
1029   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1030
1031   return socket->priv->keepalive;
1032 }
1033
1034 /**
1035  * g_socket_get_listen_backlog:
1036  * @socket: a #GSocket.
1037  *
1038  * Gets the listen backlog setting of the socket. For details on this,
1039  * see g_socket_set_listen_backlog().
1040  *
1041  * Returns: the maximum number of pending connections.
1042  *
1043  * Since: 2.22
1044  */
1045 gint
1046 g_socket_get_listen_backlog  (GSocket *socket)
1047 {
1048   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1049
1050   return socket->priv->listen_backlog;
1051 }
1052
1053 /**
1054  * g_socket_set_listen_backlog:
1055  * @socket: a #GSocket.
1056  * @backlog: the maximum number of pending connections.
1057  *
1058  * Sets the maximum number of outstanding connections allowed
1059  * when listening on this socket. If more clients than this are
1060  * connecting to the socket and the application is not handling them
1061  * on time then the new connections will be refused.
1062  *
1063  * Note that this must be called before g_socket_listen() and has no
1064  * effect if called after that.
1065  *
1066  * Since: 2.22
1067  */
1068 void
1069 g_socket_set_listen_backlog (GSocket *socket,
1070                              gint     backlog)
1071 {
1072   g_return_if_fail (G_IS_SOCKET (socket));
1073   g_return_if_fail (!socket->priv->listening);
1074
1075   if (backlog != socket->priv->listen_backlog)
1076     {
1077       socket->priv->listen_backlog = backlog;
1078       g_object_notify (G_OBJECT (socket), "listen-backlog");
1079     }
1080 }
1081
1082 /**
1083  * g_socket_get_timeout:
1084  * @socket: a #GSocket.
1085  *
1086  * Gets the timeout setting of the socket. For details on this, see
1087  * g_socket_set_timeout().
1088  *
1089  * Returns: the timeout in seconds
1090  *
1091  * Since: 2.26
1092  */
1093 guint
1094 g_socket_get_timeout (GSocket *socket)
1095 {
1096   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1097
1098   return socket->priv->timeout;
1099 }
1100
1101 /**
1102  * g_socket_set_timeout:
1103  * @socket: a #GSocket.
1104  * @timeout: the timeout for @socket, in seconds, or 0 for none
1105  *
1106  * Sets the time in seconds after which I/O operations on @socket will
1107  * time out if they have not yet completed.
1108  *
1109  * On a blocking socket, this means that any blocking #GSocket
1110  * operation will time out after @timeout seconds of inactivity,
1111  * returning %G_IO_ERROR_TIMED_OUT.
1112  *
1113  * On a non-blocking socket, calls to g_socket_condition_wait() will
1114  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1115  * created with g_socket_create_source() will trigger after
1116  * @timeout seconds of inactivity, with the requested condition
1117  * set, at which point calling g_socket_receive(), g_socket_send(),
1118  * g_socket_check_connect_result(), etc, will fail with
1119  * %G_IO_ERROR_TIMED_OUT.
1120  *
1121  * If @timeout is 0 (the default), operations will never time out
1122  * on their own.
1123  *
1124  * Note that if an I/O operation is interrupted by a signal, this may
1125  * cause the timeout to be reset.
1126  *
1127  * Since: 2.26
1128  */
1129 void
1130 g_socket_set_timeout (GSocket *socket,
1131                       guint    timeout)
1132 {
1133   g_return_if_fail (G_IS_SOCKET (socket));
1134
1135   if (timeout != socket->priv->timeout)
1136     {
1137       socket->priv->timeout = timeout;
1138       g_object_notify (G_OBJECT (socket), "timeout");
1139     }
1140 }
1141
1142 /**
1143  * g_socket_get_family:
1144  * @socket: a #GSocket.
1145  *
1146  * Gets the socket family of the socket.
1147  *
1148  * Returns: a #GSocketFamily
1149  *
1150  * Since: 2.22
1151  */
1152 GSocketFamily
1153 g_socket_get_family (GSocket *socket)
1154 {
1155   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1156
1157   return socket->priv->family;
1158 }
1159
1160 /**
1161  * g_socket_get_socket_type:
1162  * @socket: a #GSocket.
1163  *
1164  * Gets the socket type of the socket.
1165  *
1166  * Returns: a #GSocketType
1167  *
1168  * Since: 2.22
1169  */
1170 GSocketType
1171 g_socket_get_socket_type (GSocket *socket)
1172 {
1173   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1174
1175   return socket->priv->type;
1176 }
1177
1178 /**
1179  * g_socket_get_protocol:
1180  * @socket: a #GSocket.
1181  *
1182  * Gets the socket protocol id the socket was created with.
1183  * In case the protocol is unknown, -1 is returned.
1184  *
1185  * Returns: a protocol id, or -1 if unknown
1186  *
1187  * Since: 2.22
1188  */
1189 GSocketProtocol
1190 g_socket_get_protocol (GSocket *socket)
1191 {
1192   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1193
1194   return socket->priv->protocol;
1195 }
1196
1197 /**
1198  * g_socket_get_fd:
1199  * @socket: a #GSocket.
1200  *
1201  * Returns the underlying OS socket object. On unix this
1202  * is a socket file descriptor, and on windows this is
1203  * a Winsock2 SOCKET handle. This may be useful for
1204  * doing platform specific or otherwise unusual operations
1205  * on the socket.
1206  *
1207  * Returns: the file descriptor of the socket.
1208  *
1209  * Since: 2.22
1210  */
1211 int
1212 g_socket_get_fd (GSocket *socket)
1213 {
1214   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1215
1216   return socket->priv->fd;
1217 }
1218
1219 /**
1220  * g_socket_get_local_address:
1221  * @socket: a #GSocket.
1222  * @error: #GError for error reporting, or %NULL to ignore.
1223  *
1224  * Try to get the local address of a bound socket. This is only
1225  * useful if the socket has been bound to a local address,
1226  * either explicitly or implicitly when connecting.
1227  *
1228  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1229  *     Free the returned object with g_object_unref().
1230  *
1231  * Since: 2.22
1232  */
1233 GSocketAddress *
1234 g_socket_get_local_address (GSocket  *socket,
1235                             GError  **error)
1236 {
1237   struct sockaddr_storage buffer;
1238   guint32 len = sizeof (buffer);
1239
1240   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1241
1242   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1243     {
1244       int errsv = get_socket_errno ();
1245       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1246                    _("could not get local address: %s"), socket_strerror (errsv));
1247       return NULL;
1248     }
1249
1250   return g_socket_address_new_from_native (&buffer, len);
1251 }
1252
1253 /**
1254  * g_socket_get_remote_address:
1255  * @socket: a #GSocket.
1256  * @error: #GError for error reporting, or %NULL to ignore.
1257  *
1258  * Try to get the remove address of a connected socket. This is only
1259  * useful for connection oriented sockets that have been connected.
1260  *
1261  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1262  *     Free the returned object with g_object_unref().
1263  *
1264  * Since: 2.22
1265  */
1266 GSocketAddress *
1267 g_socket_get_remote_address (GSocket  *socket,
1268                              GError  **error)
1269 {
1270   struct sockaddr_storage buffer;
1271   guint32 len = sizeof (buffer);
1272
1273   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1274
1275   if (socket->priv->connect_pending)
1276     {
1277       if (!g_socket_check_connect_result (socket, error))
1278         return NULL;
1279       else
1280         socket->priv->connect_pending = FALSE;
1281     }
1282
1283   if (!socket->priv->remote_address)
1284     {
1285       if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1286         {
1287           int errsv = get_socket_errno ();
1288           g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1289                        _("could not get remote address: %s"), socket_strerror (errsv));
1290           return NULL;
1291         }
1292
1293       socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1294     }
1295
1296   return g_object_ref (socket->priv->remote_address);
1297 }
1298
1299 /**
1300  * g_socket_is_connected:
1301  * @socket: a #GSocket.
1302  *
1303  * Check whether the socket is connected. This is only useful for
1304  * connection-oriented sockets.
1305  *
1306  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1307  *
1308  * Since: 2.22
1309  */
1310 gboolean
1311 g_socket_is_connected (GSocket *socket)
1312 {
1313   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1314
1315   return socket->priv->connected;
1316 }
1317
1318 /**
1319  * g_socket_listen:
1320  * @socket: a #GSocket.
1321  * @error: #GError for error reporting, or %NULL to ignore.
1322  *
1323  * Marks the socket as a server socket, i.e. a socket that is used
1324  * to accept incoming requests using g_socket_accept().
1325  *
1326  * Before calling this the socket must be bound to a local address using
1327  * g_socket_bind().
1328  *
1329  * To set the maximum amount of outstanding clients, use
1330  * g_socket_set_listen_backlog().
1331  *
1332  * Returns: %TRUE on success, %FALSE on error.
1333  *
1334  * Since: 2.22
1335  */
1336 gboolean
1337 g_socket_listen (GSocket  *socket,
1338                  GError  **error)
1339 {
1340   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1341
1342   if (!check_socket (socket, error))
1343     return FALSE;
1344
1345   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1346     {
1347       int errsv = get_socket_errno ();
1348
1349       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1350                    _("could not listen: %s"), socket_strerror (errsv));
1351       return FALSE;
1352     }
1353
1354   socket->priv->listening = TRUE;
1355
1356   return TRUE;
1357 }
1358
1359 /**
1360  * g_socket_bind:
1361  * @socket: a #GSocket.
1362  * @address: a #GSocketAddress specifying the local address.
1363  * @allow_reuse: whether to allow reusing this address
1364  * @error: #GError for error reporting, or %NULL to ignore.
1365  *
1366  * When a socket is created it is attached to an address family, but it
1367  * doesn't have an address in this family. g_socket_bind() assigns the
1368  * address (sometimes called name) of the socket.
1369  *
1370  * It is generally required to bind to a local address before you can
1371  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1372  * In certain situations, you may also want to bind a socket that will be
1373  * used to initiate connections, though this is not normally required.
1374  *
1375  * @allow_reuse should be %TRUE for server sockets (sockets that you will
1376  * eventually call g_socket_accept() on), and %FALSE for client sockets.
1377  * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1378  * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1379  * that address was previously used by another socket that has not yet been
1380  * fully cleaned-up by the kernel. Failing to set this flag on a server
1381  * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1382  * the server program is stopped and then immediately restarted.)
1383  *
1384  * Returns: %TRUE on success, %FALSE on error.
1385  *
1386  * Since: 2.22
1387  */
1388 gboolean
1389 g_socket_bind (GSocket         *socket,
1390                GSocketAddress  *address,
1391                gboolean         reuse_address,
1392                GError         **error)
1393 {
1394   struct sockaddr_storage addr;
1395
1396   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1397
1398   if (!check_socket (socket, error))
1399     return FALSE;
1400
1401   /* SO_REUSEADDR on windows means something else and is not what we want.
1402      It always allows the unix variant of SO_REUSEADDR anyway */
1403 #ifndef G_OS_WIN32
1404   {
1405     int value;
1406
1407     value = (int) !!reuse_address;
1408     /* Ignore errors here, the only likely error is "not supported", and
1409        this is a "best effort" thing mainly */
1410     setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1411                 (gpointer) &value, sizeof (value));
1412   }
1413 #endif
1414
1415   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1416     return FALSE;
1417
1418   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1419             g_socket_address_get_native_size (address)) < 0)
1420     {
1421       int errsv = get_socket_errno ();
1422       g_set_error (error,
1423                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1424                    _("Error binding to address: %s"), socket_strerror (errsv));
1425       return FALSE;
1426     }
1427
1428   return TRUE;
1429 }
1430
1431 /**
1432  * g_socket_speaks_ipv4:
1433  * @socket: a #GSocket
1434  *
1435  * Checks if a socket is capable of speaking IPv4.
1436  *
1437  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
1438  * and under some combinations of circumstances IPv6 sockets are also
1439  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
1440  * information.
1441  *
1442  * No other types of sockets are currently considered as being capable
1443  * of speaking IPv4.
1444  *
1445  * Returns: %TRUE if this socket can be used with IPv4.
1446  *
1447  * Since: 2.22
1448  **/
1449 gboolean
1450 g_socket_speaks_ipv4 (GSocket *socket)
1451 {
1452   switch (socket->priv->family)
1453     {
1454     case G_SOCKET_FAMILY_IPV4:
1455       return TRUE;
1456
1457     case G_SOCKET_FAMILY_IPV6:
1458 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1459       {
1460         guint sizeof_int = sizeof (int);
1461         gint v6_only;
1462
1463         if (getsockopt (socket->priv->fd,
1464                         IPPROTO_IPV6, IPV6_V6ONLY,
1465                         &v6_only, &sizeof_int) != 0)
1466           return FALSE;
1467
1468         return !v6_only;
1469       }
1470 #else
1471       return FALSE;
1472 #endif
1473
1474     default:
1475       return FALSE;
1476     }
1477 }
1478
1479 /**
1480  * g_socket_accept:
1481  * @socket: a #GSocket.
1482  * @cancellable: (allow-none): a %GCancellable or %NULL
1483  * @error: #GError for error reporting, or %NULL to ignore.
1484  *
1485  * Accept incoming connections on a connection-based socket. This removes
1486  * the first outstanding connection request from the listening socket and
1487  * creates a #GSocket object for it.
1488  *
1489  * The @socket must be bound to a local address with g_socket_bind() and
1490  * must be listening for incoming connections (g_socket_listen()).
1491  *
1492  * If there are no outstanding connections then the operation will block
1493  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1494  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1495  *
1496  * Returns: (transfer full): a new #GSocket, or %NULL on error.
1497  *     Free the returned object with g_object_unref().
1498  *
1499  * Since: 2.22
1500  */
1501 GSocket *
1502 g_socket_accept (GSocket       *socket,
1503                  GCancellable  *cancellable,
1504                  GError       **error)
1505 {
1506   GSocket *new_socket;
1507   gint ret;
1508
1509   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1510
1511   if (!check_socket (socket, error))
1512     return NULL;
1513
1514   while (TRUE)
1515     {
1516       if (socket->priv->blocking &&
1517           !g_socket_condition_wait (socket,
1518                                     G_IO_IN, cancellable, error))
1519         return NULL;
1520
1521       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1522         {
1523           int errsv = get_socket_errno ();
1524
1525           win32_unset_event_mask (socket, FD_ACCEPT);
1526
1527           if (errsv == EINTR)
1528             continue;
1529
1530           if (socket->priv->blocking)
1531             {
1532 #ifdef WSAEWOULDBLOCK
1533               if (errsv == WSAEWOULDBLOCK)
1534                 continue;
1535 #else
1536               if (errsv == EWOULDBLOCK ||
1537                   errsv == EAGAIN)
1538                 continue;
1539 #endif
1540             }
1541
1542           g_set_error (error, G_IO_ERROR,
1543                        socket_io_error_from_errno (errsv),
1544                        _("Error accepting connection: %s"), socket_strerror (errsv));
1545           return NULL;
1546         }
1547       break;
1548     }
1549
1550   win32_unset_event_mask (socket, FD_ACCEPT);
1551
1552 #ifdef G_OS_WIN32
1553   {
1554     /* The socket inherits the accepting sockets event mask and even object,
1555        we need to remove that */
1556     WSAEventSelect (ret, NULL, 0);
1557   }
1558 #else
1559   {
1560     int flags;
1561
1562     /* We always want to set close-on-exec to protect users. If you
1563        need to so some weird inheritance to exec you can re-enable this
1564        using lower level hacks with g_socket_get_fd(). */
1565     flags = fcntl (ret, F_GETFD, 0);
1566     if (flags != -1 &&
1567         (flags & FD_CLOEXEC) == 0)
1568       {
1569         flags |= FD_CLOEXEC;
1570         fcntl (ret, F_SETFD, flags);
1571       }
1572   }
1573 #endif
1574
1575   new_socket = g_socket_new_from_fd (ret, error);
1576   if (new_socket == NULL)
1577     {
1578 #ifdef G_OS_WIN32
1579       closesocket (ret);
1580 #else
1581       close (ret);
1582 #endif
1583     }
1584   else
1585     new_socket->priv->protocol = socket->priv->protocol;
1586
1587   return new_socket;
1588 }
1589
1590 /**
1591  * g_socket_connect:
1592  * @socket: a #GSocket.
1593  * @address: a #GSocketAddress specifying the remote address.
1594  * @cancellable: (allow-none): a %GCancellable or %NULL
1595  * @error: #GError for error reporting, or %NULL to ignore.
1596  *
1597  * Connect the socket to the specified remote address.
1598  *
1599  * For connection oriented socket this generally means we attempt to make
1600  * a connection to the @address. For a connection-less socket it sets
1601  * the default address for g_socket_send() and discards all incoming datagrams
1602  * from other sources.
1603  *
1604  * Generally connection oriented sockets can only connect once, but
1605  * connection-less sockets can connect multiple times to change the
1606  * default address.
1607  *
1608  * If the connect call needs to do network I/O it will block, unless
1609  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1610  * and the user can be notified of the connection finishing by waiting
1611  * for the G_IO_OUT condition. The result of the connection can then be
1612  * checked with g_socket_check_connect_result().
1613  *
1614  * Returns: %TRUE if connected, %FALSE on error.
1615  *
1616  * Since: 2.22
1617  */
1618 gboolean
1619 g_socket_connect (GSocket         *socket,
1620                   GSocketAddress  *address,
1621                   GCancellable    *cancellable,
1622                   GError         **error)
1623 {
1624   struct sockaddr_storage buffer;
1625
1626   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1627
1628   if (!check_socket (socket, error))
1629     return FALSE;
1630
1631   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1632     return FALSE;
1633
1634   if (socket->priv->remote_address)
1635     g_object_unref (socket->priv->remote_address);
1636   socket->priv->remote_address = g_object_ref (address);
1637
1638   while (1)
1639     {
1640       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1641                    g_socket_address_get_native_size (address)) < 0)
1642         {
1643           int errsv = get_socket_errno ();
1644
1645           if (errsv == EINTR)
1646             continue;
1647
1648 #ifndef G_OS_WIN32
1649           if (errsv == EINPROGRESS)
1650 #else
1651           if (errsv == WSAEWOULDBLOCK)
1652 #endif
1653             {
1654               if (socket->priv->blocking)
1655                 {
1656                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1657                     {
1658                       if (g_socket_check_connect_result (socket, error))
1659                         break;
1660                     }
1661                   g_prefix_error (error, _("Error connecting: "));
1662                 }
1663               else
1664                 {
1665                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1666                                        _("Connection in progress"));
1667                   socket->priv->connect_pending = TRUE;
1668                 }
1669             }
1670           else
1671             g_set_error (error, G_IO_ERROR,
1672                          socket_io_error_from_errno (errsv),
1673                          _("Error connecting: %s"), socket_strerror (errsv));
1674
1675           return FALSE;
1676         }
1677       break;
1678     }
1679
1680   win32_unset_event_mask (socket, FD_CONNECT);
1681
1682   socket->priv->connected = TRUE;
1683
1684   return TRUE;
1685 }
1686
1687 /**
1688  * g_socket_check_connect_result:
1689  * @socket: a #GSocket
1690  * @error: #GError for error reporting, or %NULL to ignore.
1691  *
1692  * Checks and resets the pending connect error for the socket.
1693  * This is used to check for errors when g_socket_connect() is
1694  * used in non-blocking mode.
1695  *
1696  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1697  *
1698  * Since: 2.22
1699  */
1700 gboolean
1701 g_socket_check_connect_result (GSocket  *socket,
1702                                GError  **error)
1703 {
1704   guint optlen;
1705   int value;
1706
1707   if (!check_socket (socket, error))
1708     return FALSE;
1709
1710   optlen = sizeof (value);
1711   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1712     {
1713       int errsv = get_socket_errno ();
1714
1715       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1716                    _("Unable to get pending error: %s"), socket_strerror (errsv));
1717       return FALSE;
1718     }
1719
1720   if (value != 0)
1721     {
1722       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1723                            socket_strerror (value));
1724       if (socket->priv->remote_address)
1725         {
1726           g_object_unref (socket->priv->remote_address);
1727           socket->priv->remote_address = NULL;
1728         }
1729       return FALSE;
1730     }
1731   return TRUE;
1732 }
1733
1734 /**
1735  * g_socket_receive:
1736  * @socket: a #GSocket
1737  * @buffer: a buffer to read data into (which should be at least @size
1738  *     bytes long).
1739  * @size: the number of bytes you want to read from the socket
1740  * @cancellable: (allow-none): a %GCancellable or %NULL
1741  * @error: #GError for error reporting, or %NULL to ignore.
1742  *
1743  * Receive data (up to @size bytes) from a socket. This is mainly used by
1744  * connection-oriented sockets; it is identical to g_socket_receive_from()
1745  * with @address set to %NULL.
1746  *
1747  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1748  * g_socket_receive() will always read either 0 or 1 complete messages from
1749  * the socket. If the received message is too large to fit in @buffer, then
1750  * the data beyond @size bytes will be discarded, without any explicit
1751  * indication that this has occurred.
1752  *
1753  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1754  * number of bytes, up to @size. If more than @size bytes have been
1755  * received, the additional data will be returned in future calls to
1756  * g_socket_receive().
1757  *
1758  * If the socket is in blocking mode the call will block until there
1759  * is some data to receive, the connection is closed, or there is an
1760  * error. If there is no data available and the socket is in
1761  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
1762  * returned. To be notified when data is available, wait for the
1763  * %G_IO_IN condition.
1764  *
1765  * On error -1 is returned and @error is set accordingly.
1766  *
1767  * Returns: Number of bytes read, or 0 if the connection was closed by
1768  * the peer, or -1 on error
1769  *
1770  * Since: 2.22
1771  */
1772 gssize
1773 g_socket_receive (GSocket       *socket,
1774                   gchar         *buffer,
1775                   gsize          size,
1776                   GCancellable  *cancellable,
1777                   GError       **error)
1778 {
1779   return g_socket_receive_with_blocking (socket, buffer, size,
1780                                          socket->priv->blocking,
1781                                          cancellable, error);
1782 }
1783
1784 /**
1785  * g_socket_receive_with_blocking:
1786  * @socket: a #GSocket
1787  * @buffer: a buffer to read data into (which should be at least @size
1788  *     bytes long).
1789  * @size: the number of bytes you want to read from the socket
1790  * @blocking: whether to do blocking or non-blocking I/O
1791  * @cancellable: (allow-none): a %GCancellable or %NULL
1792  * @error: #GError for error reporting, or %NULL to ignore.
1793  *
1794  * This behaves exactly the same as g_socket_receive(), except that
1795  * the choice of blocking or non-blocking behavior is determined by
1796  * the @blocking argument rather than by @socket's properties.
1797  *
1798  * Returns: Number of bytes read, or 0 if the connection was closed by
1799  * the peer, or -1 on error
1800  *
1801  * Since: 2.26
1802  */
1803 gssize
1804 g_socket_receive_with_blocking (GSocket       *socket,
1805                                 gchar         *buffer,
1806                                 gsize          size,
1807                                 gboolean       blocking,
1808                                 GCancellable  *cancellable,
1809                                 GError       **error)
1810 {
1811   gssize ret;
1812
1813   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1814
1815   if (!check_socket (socket, error))
1816     return -1;
1817
1818   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1819     return -1;
1820
1821   while (1)
1822     {
1823       if (blocking &&
1824           !g_socket_condition_wait (socket,
1825                                     G_IO_IN, cancellable, error))
1826         return -1;
1827
1828       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1829         {
1830           int errsv = get_socket_errno ();
1831
1832           if (errsv == EINTR)
1833             continue;
1834
1835           if (blocking)
1836             {
1837 #ifdef WSAEWOULDBLOCK
1838               if (errsv == WSAEWOULDBLOCK)
1839                 continue;
1840 #else
1841               if (errsv == EWOULDBLOCK ||
1842                   errsv == EAGAIN)
1843                 continue;
1844 #endif
1845             }
1846
1847           win32_unset_event_mask (socket, FD_READ);
1848
1849           g_set_error (error, G_IO_ERROR,
1850                        socket_io_error_from_errno (errsv),
1851                        _("Error receiving data: %s"), socket_strerror (errsv));
1852           return -1;
1853         }
1854
1855       win32_unset_event_mask (socket, FD_READ);
1856
1857       break;
1858     }
1859
1860   return ret;
1861 }
1862
1863 /**
1864  * g_socket_receive_from:
1865  * @socket: a #GSocket
1866  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1867  * @buffer: a buffer to read data into (which should be at least @size
1868  *     bytes long).
1869  * @size: the number of bytes you want to read from the socket
1870  * @cancellable: (allow-none): a %GCancellable or %NULL
1871  * @error: #GError for error reporting, or %NULL to ignore.
1872  *
1873  * Receive data (up to @size bytes) from a socket.
1874  *
1875  * If @address is non-%NULL then @address will be set equal to the
1876  * source address of the received packet.
1877  * @address is owned by the caller.
1878  *
1879  * See g_socket_receive() for additional information.
1880  *
1881  * Returns: Number of bytes read, or 0 if the connection was closed by
1882  * the peer, or -1 on error
1883  *
1884  * Since: 2.22
1885  */
1886 gssize
1887 g_socket_receive_from (GSocket         *socket,
1888                        GSocketAddress **address,
1889                        gchar           *buffer,
1890                        gsize            size,
1891                        GCancellable    *cancellable,
1892                        GError         **error)
1893 {
1894   GInputVector v;
1895
1896   v.buffer = buffer;
1897   v.size = size;
1898
1899   return g_socket_receive_message (socket,
1900                                    address,
1901                                    &v, 1,
1902                                    NULL, 0, NULL,
1903                                    cancellable,
1904                                    error);
1905 }
1906
1907 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1908  * one, which can be confusing and annoying. So if possible, we want
1909  * to suppress the signal entirely.
1910  */
1911 #ifdef MSG_NOSIGNAL
1912 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1913 #else
1914 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1915 #endif
1916
1917 /**
1918  * g_socket_send:
1919  * @socket: a #GSocket
1920  * @buffer: (array length=size): the buffer containing the data to send.
1921  * @size: the number of bytes to send
1922  * @cancellable: (allow-none): a %GCancellable or %NULL
1923  * @error: #GError for error reporting, or %NULL to ignore.
1924  *
1925  * Tries to send @size bytes from @buffer on the socket. This is
1926  * mainly used by connection-oriented sockets; it is identical to
1927  * g_socket_send_to() with @address set to %NULL.
1928  *
1929  * If the socket is in blocking mode the call will block until there is
1930  * space for the data in the socket queue. If there is no space available
1931  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1932  * will be returned. To be notified when space is available, wait for the
1933  * %G_IO_OUT condition. Note though that you may still receive
1934  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1935  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1936  * very common due to the way the underlying APIs work.)
1937  *
1938  * On error -1 is returned and @error is set accordingly.
1939  *
1940  * Returns: Number of bytes written (which may be less than @size), or -1
1941  * on error
1942  *
1943  * Since: 2.22
1944  */
1945 gssize
1946 g_socket_send (GSocket       *socket,
1947                const gchar   *buffer,
1948                gsize          size,
1949                GCancellable  *cancellable,
1950                GError       **error)
1951 {
1952   return g_socket_send_with_blocking (socket, buffer, size,
1953                                       socket->priv->blocking,
1954                                       cancellable, error);
1955 }
1956
1957 /**
1958  * g_socket_send_with_blocking:
1959  * @socket: a #GSocket
1960  * @buffer: (array length=size): the buffer containing the data to send.
1961  * @size: the number of bytes to send
1962  * @blocking: whether to do blocking or non-blocking I/O
1963  * @cancellable: (allow-none): a %GCancellable or %NULL
1964  * @error: #GError for error reporting, or %NULL to ignore.
1965  *
1966  * This behaves exactly the same as g_socket_send(), except that
1967  * the choice of blocking or non-blocking behavior is determined by
1968  * the @blocking argument rather than by @socket's properties.
1969  *
1970  * Returns: Number of bytes written (which may be less than @size), or -1
1971  * on error
1972  *
1973  * Since: 2.26
1974  */
1975 gssize
1976 g_socket_send_with_blocking (GSocket       *socket,
1977                              const gchar   *buffer,
1978                              gsize          size,
1979                              gboolean       blocking,
1980                              GCancellable  *cancellable,
1981                              GError       **error)
1982 {
1983   gssize ret;
1984
1985   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1986
1987   if (!check_socket (socket, error))
1988     return -1;
1989
1990   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1991     return -1;
1992
1993   while (1)
1994     {
1995       if (blocking &&
1996           !g_socket_condition_wait (socket,
1997                                     G_IO_OUT, cancellable, error))
1998         return -1;
1999
2000       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2001         {
2002           int errsv = get_socket_errno ();
2003
2004           if (errsv == EINTR)
2005             continue;
2006
2007 #ifdef WSAEWOULDBLOCK
2008           if (errsv == WSAEWOULDBLOCK)
2009             win32_unset_event_mask (socket, FD_WRITE);
2010 #endif
2011
2012           if (blocking)
2013             {
2014 #ifdef WSAEWOULDBLOCK
2015               if (errsv == WSAEWOULDBLOCK)
2016                 continue;
2017 #else
2018               if (errsv == EWOULDBLOCK ||
2019                   errsv == EAGAIN)
2020                 continue;
2021 #endif
2022             }
2023
2024           g_set_error (error, G_IO_ERROR,
2025                        socket_io_error_from_errno (errsv),
2026                        _("Error sending data: %s"), socket_strerror (errsv));
2027           return -1;
2028         }
2029       break;
2030     }
2031
2032   return ret;
2033 }
2034
2035 /**
2036  * g_socket_send_to:
2037  * @socket: a #GSocket
2038  * @address: a #GSocketAddress, or %NULL
2039  * @buffer: (array length=size): the buffer containing the data to send.
2040  * @size: the number of bytes to send
2041  * @cancellable: (allow-none): a %GCancellable or %NULL
2042  * @error: #GError for error reporting, or %NULL to ignore.
2043  *
2044  * Tries to send @size bytes from @buffer to @address. If @address is
2045  * %NULL then the message is sent to the default receiver (set by
2046  * g_socket_connect()).
2047  *
2048  * See g_socket_send() for additional information.
2049  *
2050  * Returns: Number of bytes written (which may be less than @size), or -1
2051  * on error
2052  *
2053  * Since: 2.22
2054  */
2055 gssize
2056 g_socket_send_to (GSocket         *socket,
2057                   GSocketAddress  *address,
2058                   const gchar     *buffer,
2059                   gsize            size,
2060                   GCancellable    *cancellable,
2061                   GError         **error)
2062 {
2063   GOutputVector v;
2064
2065   v.buffer = buffer;
2066   v.size = size;
2067
2068   return g_socket_send_message (socket,
2069                                 address,
2070                                 &v, 1,
2071                                 NULL, 0,
2072                                 0,
2073                                 cancellable,
2074                                 error);
2075 }
2076
2077 /**
2078  * g_socket_shutdown:
2079  * @socket: a #GSocket
2080  * @shutdown_read: whether to shut down the read side
2081  * @shutdown_write: whether to shut down the write side
2082  * @error: #GError for error reporting, or %NULL to ignore.
2083  *
2084  * Shut down part of a full-duplex connection.
2085  *
2086  * If @shutdown_read is %TRUE then the recieving side of the connection
2087  * is shut down, and further reading is disallowed.
2088  *
2089  * If @shutdown_write is %TRUE then the sending side of the connection
2090  * is shut down, and further writing is disallowed.
2091  *
2092  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2093  *
2094  * One example where this is used is graceful disconnect for TCP connections
2095  * where you close the sending side, then wait for the other side to close
2096  * the connection, thus ensuring that the other side saw all sent data.
2097  *
2098  * Returns: %TRUE on success, %FALSE on error
2099  *
2100  * Since: 2.22
2101  */
2102 gboolean
2103 g_socket_shutdown (GSocket   *socket,
2104                    gboolean   shutdown_read,
2105                    gboolean   shutdown_write,
2106                    GError   **error)
2107 {
2108   int how;
2109
2110   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2111
2112   if (!check_socket (socket, NULL))
2113     return FALSE;
2114
2115   /* Do nothing? */
2116   if (!shutdown_read && !shutdown_write)
2117     return TRUE;
2118
2119 #ifndef G_OS_WIN32
2120   if (shutdown_read && shutdown_write)
2121     how = SHUT_RDWR;
2122   else if (shutdown_read)
2123     how = SHUT_RD;
2124   else
2125     how = SHUT_WR;
2126 #else
2127   if (shutdown_read && shutdown_write)
2128     how = SD_BOTH;
2129   else if (shutdown_read)
2130     how = SD_RECEIVE;
2131   else
2132     how = SD_SEND;
2133 #endif
2134
2135   if (shutdown (socket->priv->fd, how) != 0)
2136     {
2137       int errsv = get_socket_errno ();
2138       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2139                    _("Unable to create socket: %s"), socket_strerror (errsv));
2140       return FALSE;
2141     }
2142
2143   if (shutdown_read && shutdown_write)
2144     socket->priv->connected = FALSE;
2145
2146   return TRUE;
2147 }
2148
2149 /**
2150  * g_socket_close:
2151  * @socket: a #GSocket
2152  * @error: #GError for error reporting, or %NULL to ignore.
2153  *
2154  * Closes the socket, shutting down any active connection.
2155  *
2156  * Closing a socket does not wait for all outstanding I/O operations
2157  * to finish, so the caller should not rely on them to be guaranteed
2158  * to complete even if the close returns with no error.
2159  *
2160  * Once the socket is closed, all other operations will return
2161  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2162  * return an error.
2163  *
2164  * Sockets will be automatically closed when the last reference
2165  * is dropped, but you might want to call this function to make sure
2166  * resources are released as early as possible.
2167  *
2168  * Beware that due to the way that TCP works, it is possible for
2169  * recently-sent data to be lost if either you close a socket while the
2170  * %G_IO_IN condition is set, or else if the remote connection tries to
2171  * send something to you after you close the socket but before it has
2172  * finished reading all of the data you sent. There is no easy generic
2173  * way to avoid this problem; the easiest fix is to design the network
2174  * protocol such that the client will never send data "out of turn".
2175  * Another solution is for the server to half-close the connection by
2176  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2177  * and then wait for the client to notice this and close its side of the
2178  * connection, after which the server can safely call g_socket_close().
2179  * (This is what #GTcpConnection does if you call
2180  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2181  * only works if the client will close its connection after the server
2182  * does.)
2183  *
2184  * Returns: %TRUE on success, %FALSE on error
2185  *
2186  * Since: 2.22
2187  */
2188 gboolean
2189 g_socket_close (GSocket  *socket,
2190                 GError  **error)
2191 {
2192   int res;
2193
2194   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2195
2196   if (socket->priv->closed)
2197     return TRUE; /* Multiple close not an error */
2198
2199   if (!check_socket (socket, NULL))
2200     return FALSE;
2201
2202   while (1)
2203     {
2204 #ifdef G_OS_WIN32
2205       res = closesocket (socket->priv->fd);
2206 #else
2207       res = close (socket->priv->fd);
2208 #endif
2209       if (res == -1)
2210         {
2211           int errsv = get_socket_errno ();
2212
2213           if (errsv == EINTR)
2214             continue;
2215
2216           g_set_error (error, G_IO_ERROR,
2217                        socket_io_error_from_errno (errsv),
2218                        _("Error closing socket: %s"),
2219                        socket_strerror (errsv));
2220           return FALSE;
2221         }
2222       break;
2223     }
2224
2225   socket->priv->connected = FALSE;
2226   socket->priv->closed = TRUE;
2227   if (socket->priv->remote_address)
2228     {
2229       g_object_unref (socket->priv->remote_address);
2230       socket->priv->remote_address = NULL;
2231     }
2232
2233   return TRUE;
2234 }
2235
2236 /**
2237  * g_socket_is_closed:
2238  * @socket: a #GSocket
2239  *
2240  * Checks whether a socket is closed.
2241  *
2242  * Returns: %TRUE if socket is closed, %FALSE otherwise
2243  *
2244  * Since: 2.22
2245  */
2246 gboolean
2247 g_socket_is_closed (GSocket *socket)
2248 {
2249   return socket->priv->closed;
2250 }
2251
2252 #ifdef G_OS_WIN32
2253 /* Broken source, used on errors */
2254 static gboolean
2255 broken_prepare  (GSource *source,
2256                  gint    *timeout)
2257 {
2258   return FALSE;
2259 }
2260
2261 static gboolean
2262 broken_check (GSource *source)
2263 {
2264   return FALSE;
2265 }
2266
2267 static gboolean
2268 broken_dispatch (GSource     *source,
2269                  GSourceFunc  callback,
2270                  gpointer     user_data)
2271 {
2272   return TRUE;
2273 }
2274
2275 static GSourceFuncs broken_funcs =
2276 {
2277   broken_prepare,
2278   broken_check,
2279   broken_dispatch,
2280   NULL
2281 };
2282
2283 static gint
2284 network_events_for_condition (GIOCondition condition)
2285 {
2286   int event_mask = 0;
2287
2288   if (condition & G_IO_IN)
2289     event_mask |= (FD_READ | FD_ACCEPT);
2290   if (condition & G_IO_OUT)
2291     event_mask |= (FD_WRITE | FD_CONNECT);
2292   event_mask |= FD_CLOSE;
2293
2294   return event_mask;
2295 }
2296
2297 static void
2298 ensure_event (GSocket *socket)
2299 {
2300   if (socket->priv->event == WSA_INVALID_EVENT)
2301     socket->priv->event = WSACreateEvent();
2302 }
2303
2304 static void
2305 update_select_events (GSocket *socket)
2306 {
2307   int event_mask;
2308   GIOCondition *ptr;
2309   GList *l;
2310   WSAEVENT event;
2311
2312   ensure_event (socket);
2313
2314   event_mask = 0;
2315   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2316     {
2317       ptr = l->data;
2318       event_mask |= network_events_for_condition (*ptr);
2319     }
2320
2321   if (event_mask != socket->priv->selected_events)
2322     {
2323       /* If no events selected, disable event so we can unset
2324          nonblocking mode */
2325
2326       if (event_mask == 0)
2327         event = NULL;
2328       else
2329         event = socket->priv->event;
2330
2331       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2332         socket->priv->selected_events = event_mask;
2333     }
2334 }
2335
2336 static void
2337 add_condition_watch (GSocket      *socket,
2338                      GIOCondition *condition)
2339 {
2340   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2341
2342   socket->priv->requested_conditions =
2343     g_list_prepend (socket->priv->requested_conditions, condition);
2344
2345   update_select_events (socket);
2346 }
2347
2348 static void
2349 remove_condition_watch (GSocket      *socket,
2350                         GIOCondition *condition)
2351 {
2352   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2353
2354   socket->priv->requested_conditions =
2355     g_list_remove (socket->priv->requested_conditions, condition);
2356
2357   update_select_events (socket);
2358 }
2359
2360 static GIOCondition
2361 update_condition (GSocket *socket)
2362 {
2363   WSANETWORKEVENTS events;
2364   GIOCondition condition;
2365
2366   if (WSAEnumNetworkEvents (socket->priv->fd,
2367                             socket->priv->event,
2368                             &events) == 0)
2369     {
2370       socket->priv->current_events |= events.lNetworkEvents;
2371       if (events.lNetworkEvents & FD_WRITE &&
2372           events.iErrorCode[FD_WRITE_BIT] != 0)
2373         socket->priv->current_errors |= FD_WRITE;
2374       if (events.lNetworkEvents & FD_CONNECT &&
2375           events.iErrorCode[FD_CONNECT_BIT] != 0)
2376         socket->priv->current_errors |= FD_CONNECT;
2377     }
2378
2379   condition = 0;
2380   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2381     condition |= G_IO_IN;
2382
2383   if (socket->priv->current_events & FD_CLOSE ||
2384       socket->priv->closed)
2385     condition |= G_IO_HUP;
2386
2387   /* Never report both G_IO_OUT and HUP, these are
2388      mutually exclusive (can't write to a closed socket) */
2389   if ((condition & G_IO_HUP) == 0 &&
2390       socket->priv->current_events & FD_WRITE)
2391     {
2392       if (socket->priv->current_errors & FD_WRITE)
2393         condition |= G_IO_ERR;
2394       else
2395         condition |= G_IO_OUT;
2396     }
2397   else
2398     {
2399       if (socket->priv->current_events & FD_CONNECT)
2400         {
2401           if (socket->priv->current_errors & FD_CONNECT)
2402             condition |= (G_IO_HUP | G_IO_ERR);
2403           else
2404             condition |= G_IO_OUT;
2405         }
2406     }
2407
2408   return condition;
2409 }
2410 #endif
2411
2412 typedef struct {
2413   GSource       source;
2414   GPollFD       pollfd;
2415   GSocket      *socket;
2416   GIOCondition  condition;
2417   GCancellable *cancellable;
2418   GPollFD       cancel_pollfd;
2419   gint64        timeout_time;
2420 } GSocketSource;
2421
2422 static gboolean
2423 socket_source_prepare (GSource *source,
2424                        gint    *timeout)
2425 {
2426   GSocketSource *socket_source = (GSocketSource *)source;
2427
2428   if (g_cancellable_is_cancelled (socket_source->cancellable))
2429     return TRUE;
2430
2431   if (socket_source->timeout_time)
2432     {
2433       gint64 now;
2434
2435       now = g_source_get_time (source);
2436       /* Round up to ensure that we don't try again too early */
2437       *timeout = (socket_source->timeout_time - now + 999) / 1000;
2438       if (*timeout < 0)
2439         {
2440           socket_source->socket->priv->timed_out = TRUE;
2441           socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2442           *timeout = 0;
2443           return TRUE;
2444         }
2445     }
2446   else
2447     *timeout = -1;
2448
2449 #ifdef G_OS_WIN32
2450   socket_source->pollfd.revents = update_condition (socket_source->socket);
2451 #endif
2452
2453   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2454     return TRUE;
2455
2456   return FALSE;
2457 }
2458
2459 static gboolean
2460 socket_source_check (GSource *source)
2461 {
2462   int timeout;
2463
2464   return socket_source_prepare (source, &timeout);
2465 }
2466
2467 static gboolean
2468 socket_source_dispatch (GSource     *source,
2469                         GSourceFunc  callback,
2470                         gpointer     user_data)
2471 {
2472   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2473   GSocketSource *socket_source = (GSocketSource *)source;
2474
2475 #ifdef G_OS_WIN32
2476   socket_source->pollfd.revents = update_condition (socket_source->socket);
2477 #endif
2478
2479   return (*func) (socket_source->socket,
2480                   socket_source->pollfd.revents & socket_source->condition,
2481                   user_data);
2482 }
2483
2484 static void
2485 socket_source_finalize (GSource *source)
2486 {
2487   GSocketSource *socket_source = (GSocketSource *)source;
2488   GSocket *socket;
2489
2490   socket = socket_source->socket;
2491
2492 #ifdef G_OS_WIN32
2493   remove_condition_watch (socket, &socket_source->condition);
2494 #endif
2495
2496   g_object_unref (socket);
2497
2498   if (socket_source->cancellable)
2499     {
2500       g_cancellable_release_fd (socket_source->cancellable);
2501       g_object_unref (socket_source->cancellable);
2502     }
2503 }
2504
2505 static gboolean
2506 socket_source_closure_callback (GSocket      *socket,
2507                                 GIOCondition  condition,
2508                                 gpointer      data)
2509 {
2510   GClosure *closure = data;
2511
2512   GValue params[2] = { { 0, }, { 0, } };
2513   GValue result_value = { 0, };
2514   gboolean result;
2515
2516   g_value_init (&result_value, G_TYPE_BOOLEAN);
2517
2518   g_value_init (&params[0], G_TYPE_SOCKET);
2519   g_value_set_object (&params[0], socket);
2520   g_value_init (&params[1], G_TYPE_IO_CONDITION);
2521   g_value_set_flags (&params[1], condition);
2522
2523   g_closure_invoke (closure, &result_value, 2, params, NULL);
2524
2525   result = g_value_get_boolean (&result_value);
2526   g_value_unset (&result_value);
2527   g_value_unset (&params[0]);
2528   g_value_unset (&params[1]);
2529
2530   return result;
2531 }
2532
2533 static GSourceFuncs socket_source_funcs =
2534 {
2535   socket_source_prepare,
2536   socket_source_check,
2537   socket_source_dispatch,
2538   socket_source_finalize,
2539   (GSourceFunc)socket_source_closure_callback,
2540   (GSourceDummyMarshal)_gio_marshal_BOOLEAN__FLAGS,
2541 };
2542
2543 static GSource *
2544 socket_source_new (GSocket      *socket,
2545                    GIOCondition  condition,
2546                    GCancellable *cancellable)
2547 {
2548   GSource *source;
2549   GSocketSource *socket_source;
2550
2551 #ifdef G_OS_WIN32
2552   ensure_event (socket);
2553
2554   if (socket->priv->event == WSA_INVALID_EVENT)
2555     {
2556       g_warning ("Failed to create WSAEvent");
2557       return g_source_new (&broken_funcs, sizeof (GSource));
2558     }
2559 #endif
2560
2561   condition |= G_IO_HUP | G_IO_ERR;
2562
2563   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2564   g_source_set_name (source, "GSocket");
2565   socket_source = (GSocketSource *)source;
2566
2567   socket_source->socket = g_object_ref (socket);
2568   socket_source->condition = condition;
2569
2570   if (g_cancellable_make_pollfd (cancellable,
2571                                  &socket_source->cancel_pollfd))
2572     {
2573       socket_source->cancellable = g_object_ref (cancellable);
2574       g_source_add_poll (source, &socket_source->cancel_pollfd);
2575     }
2576
2577 #ifdef G_OS_WIN32
2578   add_condition_watch (socket, &socket_source->condition);
2579   socket_source->pollfd.fd = (gintptr) socket->priv->event;
2580 #else
2581   socket_source->pollfd.fd = socket->priv->fd;
2582 #endif
2583
2584   socket_source->pollfd.events = condition;
2585   socket_source->pollfd.revents = 0;
2586   g_source_add_poll (source, &socket_source->pollfd);
2587
2588   if (socket->priv->timeout)
2589     socket_source->timeout_time = g_get_monotonic_time () +
2590                                   socket->priv->timeout * 1000000;
2591
2592   else
2593     socket_source->timeout_time = 0;
2594
2595   return source;
2596 }
2597
2598 /**
2599  * g_socket_create_source: (skip)
2600  * @socket: a #GSocket
2601  * @condition: a #GIOCondition mask to monitor
2602  * @cancellable: (allow-none): a %GCancellable or %NULL
2603  *
2604  * Creates a %GSource that can be attached to a %GMainContext to monitor
2605  * for the availibility of the specified @condition on the socket.
2606  *
2607  * The callback on the source is of the #GSocketSourceFunc type.
2608  *
2609  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2610  * these conditions will always be reported output if they are true.
2611  *
2612  * @cancellable if not %NULL can be used to cancel the source, which will
2613  * cause the source to trigger, reporting the current condition (which
2614  * is likely 0 unless cancellation happened at the same time as a
2615  * condition change). You can check for this in the callback using
2616  * g_cancellable_is_cancelled().
2617  *
2618  * If @socket has a timeout set, and it is reached before @condition
2619  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2620  * %G_IO_OUT depending on @condition. However, @socket will have been
2621  * marked as having had a timeout, and so the next #GSocket I/O method
2622  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2623  *
2624  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2625  *
2626  * Since: 2.22
2627  */
2628 GSource *
2629 g_socket_create_source (GSocket      *socket,
2630                         GIOCondition  condition,
2631                         GCancellable *cancellable)
2632 {
2633   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2634
2635   return socket_source_new (socket, condition, cancellable);
2636 }
2637
2638 /**
2639  * g_socket_condition_check:
2640  * @socket: a #GSocket
2641  * @condition: a #GIOCondition mask to check
2642  *
2643  * Checks on the readiness of @socket to perform operations.
2644  * The operations specified in @condition are checked for and masked
2645  * against the currently-satisfied conditions on @socket. The result
2646  * is returned.
2647  *
2648  * Note that on Windows, it is possible for an operation to return
2649  * %G_IO_ERROR_WOULD_BLOCK even immediately after
2650  * g_socket_condition_check() has claimed that the socket is ready for
2651  * writing. Rather than calling g_socket_condition_check() and then
2652  * writing to the socket if it succeeds, it is generally better to
2653  * simply try writing to the socket right away, and try again later if
2654  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2655  *
2656  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2657  * these conditions will always be set in the output if they are true.
2658  *
2659  * This call never blocks.
2660  *
2661  * Returns: the @GIOCondition mask of the current state
2662  *
2663  * Since: 2.22
2664  */
2665 GIOCondition
2666 g_socket_condition_check (GSocket      *socket,
2667                           GIOCondition  condition)
2668 {
2669   if (!check_socket (socket, NULL))
2670     return 0;
2671
2672 #ifdef G_OS_WIN32
2673   {
2674     GIOCondition current_condition;
2675
2676     condition |= G_IO_ERR | G_IO_HUP;
2677
2678     add_condition_watch (socket, &condition);
2679     current_condition = update_condition (socket);
2680     remove_condition_watch (socket, &condition);
2681     return condition & current_condition;
2682   }
2683 #else
2684   {
2685     GPollFD poll_fd;
2686     gint result;
2687     poll_fd.fd = socket->priv->fd;
2688     poll_fd.events = condition;
2689
2690     do
2691       result = g_poll (&poll_fd, 1, 0);
2692     while (result == -1 && get_socket_errno () == EINTR);
2693
2694     return poll_fd.revents;
2695   }
2696 #endif
2697 }
2698
2699 /**
2700  * g_socket_condition_wait:
2701  * @socket: a #GSocket
2702  * @condition: a #GIOCondition mask to wait for
2703  * @cancellable: (allow-none): a #GCancellable, or %NULL
2704  * @error: a #GError pointer, or %NULL
2705  *
2706  * Waits for @condition to become true on @socket. When the condition
2707  * is met, %TRUE is returned.
2708  *
2709  * If @cancellable is cancelled before the condition is met, or if the
2710  * socket has a timeout set and it is reached before the condition is
2711  * met, then %FALSE is returned and @error, if non-%NULL, is set to
2712  * the appropriate value (%G_IO_ERROR_CANCELLED or
2713  * %G_IO_ERROR_TIMED_OUT).
2714  *
2715  * Returns: %TRUE if the condition was met, %FALSE otherwise
2716  *
2717  * Since: 2.22
2718  */
2719 gboolean
2720 g_socket_condition_wait (GSocket       *socket,
2721                          GIOCondition   condition,
2722                          GCancellable  *cancellable,
2723                          GError       **error)
2724 {
2725   if (!check_socket (socket, error))
2726     return FALSE;
2727
2728   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2729     return FALSE;
2730
2731 #ifdef G_OS_WIN32
2732   {
2733     GIOCondition current_condition;
2734     WSAEVENT events[2];
2735     DWORD res, timeout;
2736     GPollFD cancel_fd;
2737     int num_events;
2738
2739     /* Always check these */
2740     condition |=  G_IO_ERR | G_IO_HUP;
2741
2742     add_condition_watch (socket, &condition);
2743
2744     num_events = 0;
2745     events[num_events++] = socket->priv->event;
2746
2747     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2748       events[num_events++] = (WSAEVENT)cancel_fd.fd;
2749
2750     if (socket->priv->timeout)
2751       timeout = socket->priv->timeout * 1000;
2752     else
2753       timeout = WSA_INFINITE;
2754
2755     current_condition = update_condition (socket);
2756     while ((condition & current_condition) == 0)
2757       {
2758         res = WSAWaitForMultipleEvents(num_events, events,
2759                                        FALSE, timeout, FALSE);
2760         if (res == WSA_WAIT_FAILED)
2761           {
2762             int errsv = get_socket_errno ();
2763
2764             g_set_error (error, G_IO_ERROR,
2765                          socket_io_error_from_errno (errsv),
2766                          _("Waiting for socket condition: %s"),
2767                          socket_strerror (errsv));
2768             break;
2769           }
2770         else if (res == WSA_WAIT_TIMEOUT)
2771           {
2772             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2773                                  _("Socket I/O timed out"));
2774             break;
2775           }
2776
2777         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2778           break;
2779
2780         current_condition = update_condition (socket);
2781       }
2782     remove_condition_watch (socket, &condition);
2783     if (num_events > 1)
2784       g_cancellable_release_fd (cancellable);
2785
2786     return (condition & current_condition) != 0;
2787   }
2788 #else
2789   {
2790     GPollFD poll_fd[2];
2791     gint result;
2792     gint num;
2793     gint timeout;
2794
2795     poll_fd[0].fd = socket->priv->fd;
2796     poll_fd[0].events = condition;
2797     num = 1;
2798
2799     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2800       num++;
2801
2802     if (socket->priv->timeout)
2803       timeout = socket->priv->timeout * 1000;
2804     else
2805       timeout = -1;
2806
2807     do
2808       result = g_poll (poll_fd, num, timeout);
2809     while (result == -1 && get_socket_errno () == EINTR);
2810     
2811     if (num > 1)
2812       g_cancellable_release_fd (cancellable);
2813
2814     if (result == 0)
2815       {
2816         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2817                              _("Socket I/O timed out"));
2818         return FALSE;
2819       }
2820
2821     return !g_cancellable_set_error_if_cancelled (cancellable, error);
2822   }
2823   #endif
2824 }
2825
2826 /**
2827  * g_socket_send_message:
2828  * @socket: a #GSocket
2829  * @address: a #GSocketAddress, or %NULL
2830  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2831  * @num_vectors: the number of elements in @vectors, or -1
2832  * @messages: (array length=num_messages) (allow-none): a pointer to an
2833  *   array of #GSocketControlMessages, or %NULL.
2834  * @num_messages: number of elements in @messages, or -1.
2835  * @flags: an int containing #GSocketMsgFlags flags
2836  * @cancellable: (allow-none): a %GCancellable or %NULL
2837  * @error: #GError for error reporting, or %NULL to ignore.
2838  *
2839  * Send data to @address on @socket.  This is the most complicated and
2840  * fully-featured version of this call. For easier use, see
2841  * g_socket_send() and g_socket_send_to().
2842  *
2843  * If @address is %NULL then the message is sent to the default receiver
2844  * (set by g_socket_connect()).
2845  *
2846  * @vectors must point to an array of #GOutputVector structs and
2847  * @num_vectors must be the length of this array. (If @num_vectors is -1,
2848  * then @vectors is assumed to be terminated by a #GOutputVector with a
2849  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2850  * that the sent data will be gathered from. Using multiple
2851  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2852  * data from multiple sources into a single buffer, and more
2853  * network-efficient than making multiple calls to g_socket_send().
2854  *
2855  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2856  * #GSocketControlMessage instances. These correspond to the control
2857  * messages to be sent on the socket.
2858  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2859  * array.
2860  *
2861  * @flags modify how the message is sent. The commonly available arguments
2862  * for this are available in the #GSocketMsgFlags enum, but the
2863  * values there are the same as the system values, and the flags
2864  * are passed in as-is, so you can pass in system-specific flags too.
2865  *
2866  * If the socket is in blocking mode the call will block until there is
2867  * space for the data in the socket queue. If there is no space available
2868  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2869  * will be returned. To be notified when space is available, wait for the
2870  * %G_IO_OUT condition. Note though that you may still receive
2871  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2872  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2873  * very common due to the way the underlying APIs work.)
2874  *
2875  * On error -1 is returned and @error is set accordingly.
2876  *
2877  * Returns: Number of bytes written (which may be less than @size), or -1
2878  * on error
2879  *
2880  * Since: 2.22
2881  */
2882 gssize
2883 g_socket_send_message (GSocket                *socket,
2884                        GSocketAddress         *address,
2885                        GOutputVector          *vectors,
2886                        gint                    num_vectors,
2887                        GSocketControlMessage **messages,
2888                        gint                    num_messages,
2889                        gint                    flags,
2890                        GCancellable           *cancellable,
2891                        GError                **error)
2892 {
2893   GOutputVector one_vector;
2894   char zero;
2895
2896   if (!check_socket (socket, error))
2897     return -1;
2898
2899   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2900     return -1;
2901
2902   if (num_vectors == -1)
2903     {
2904       for (num_vectors = 0;
2905            vectors[num_vectors].buffer != NULL;
2906            num_vectors++)
2907         ;
2908     }
2909
2910   if (num_messages == -1)
2911     {
2912       for (num_messages = 0;
2913            messages != NULL && messages[num_messages] != NULL;
2914            num_messages++)
2915         ;
2916     }
2917
2918   if (num_vectors == 0)
2919     {
2920       zero = '\0';
2921
2922       one_vector.buffer = &zero;
2923       one_vector.size = 1;
2924       num_vectors = 1;
2925       vectors = &one_vector;
2926     }
2927
2928 #ifndef G_OS_WIN32
2929   {
2930     struct msghdr msg;
2931     gssize result;
2932
2933    msg.msg_flags = 0;
2934
2935     /* name */
2936     if (address)
2937       {
2938         msg.msg_namelen = g_socket_address_get_native_size (address);
2939         msg.msg_name = g_alloca (msg.msg_namelen);
2940         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2941           return -1;
2942       }
2943     else
2944       {
2945         msg.msg_name = NULL;
2946         msg.msg_namelen = 0;
2947       }
2948
2949     /* iov */
2950     {
2951       /* this entire expression will be evaluated at compile time */
2952       if (sizeof *msg.msg_iov == sizeof *vectors &&
2953           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2954           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2955           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2956           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2957           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2958           G_STRUCT_OFFSET (GOutputVector, size))
2959         /* ABI is compatible */
2960         {
2961           msg.msg_iov = (struct iovec *) vectors;
2962           msg.msg_iovlen = num_vectors;
2963         }
2964       else
2965         /* ABI is incompatible */
2966         {
2967           gint i;
2968
2969           msg.msg_iov = g_newa (struct iovec, num_vectors);
2970           for (i = 0; i < num_vectors; i++)
2971             {
2972               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2973               msg.msg_iov[i].iov_len = vectors[i].size;
2974             }
2975           msg.msg_iovlen = num_vectors;
2976         }
2977     }
2978
2979     /* control */
2980     {
2981       struct cmsghdr *cmsg;
2982       gint i;
2983
2984       msg.msg_controllen = 0;
2985       for (i = 0; i < num_messages; i++)
2986         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2987
2988       if (msg.msg_controllen == 0)
2989         msg.msg_control = NULL;
2990       else
2991         {
2992           msg.msg_control = g_alloca (msg.msg_controllen);
2993           memset (msg.msg_control, '\0', msg.msg_controllen);
2994         }
2995
2996       cmsg = CMSG_FIRSTHDR (&msg);
2997       for (i = 0; i < num_messages; i++)
2998         {
2999           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3000           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3001           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3002           g_socket_control_message_serialize (messages[i],
3003                                               CMSG_DATA (cmsg));
3004           cmsg = CMSG_NXTHDR (&msg, cmsg);
3005         }
3006       g_assert (cmsg == NULL);
3007     }
3008
3009     while (1)
3010       {
3011         if (socket->priv->blocking &&
3012             !g_socket_condition_wait (socket,
3013                                       G_IO_OUT, cancellable, error))
3014           return -1;
3015
3016         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3017         if (result < 0)
3018           {
3019             int errsv = get_socket_errno ();
3020
3021             if (errsv == EINTR)
3022               continue;
3023
3024             if (socket->priv->blocking &&
3025                 (errsv == EWOULDBLOCK ||
3026                  errsv == EAGAIN))
3027               continue;
3028
3029             g_set_error (error, G_IO_ERROR,
3030                          socket_io_error_from_errno (errsv),
3031                          _("Error sending message: %s"), socket_strerror (errsv));
3032
3033             return -1;
3034           }
3035         break;
3036       }
3037
3038     return result;
3039   }
3040 #else
3041   {
3042     struct sockaddr_storage addr;
3043     guint addrlen;
3044     DWORD bytes_sent;
3045     int result;
3046     WSABUF *bufs;
3047     gint i;
3048
3049     /* Win32 doesn't support control messages.
3050        Actually this is possible for raw and datagram sockets
3051        via WSASendMessage on Vista or later, but that doesn't
3052        seem very useful */
3053     if (num_messages != 0)
3054       {
3055         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3056                              _("GSocketControlMessage not supported on windows"));
3057         return -1;
3058       }
3059
3060     /* iov */
3061     bufs = g_newa (WSABUF, num_vectors);
3062     for (i = 0; i < num_vectors; i++)
3063       {
3064         bufs[i].buf = (char *)vectors[i].buffer;
3065         bufs[i].len = (gulong)vectors[i].size;
3066       }
3067
3068     /* name */
3069     addrlen = 0; /* Avoid warning */
3070     if (address)
3071       {
3072         addrlen = g_socket_address_get_native_size (address);
3073         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3074           return -1;
3075       }
3076
3077     while (1)
3078       {
3079         if (socket->priv->blocking &&
3080             !g_socket_condition_wait (socket,
3081                                       G_IO_OUT, cancellable, error))
3082           return -1;
3083
3084         if (address)
3085           result = WSASendTo (socket->priv->fd,
3086                               bufs, num_vectors,
3087                               &bytes_sent, flags,
3088                               (const struct sockaddr *)&addr, addrlen,
3089                               NULL, NULL);
3090         else
3091           result = WSASend (socket->priv->fd,
3092                             bufs, num_vectors,
3093                             &bytes_sent, flags,
3094                             NULL, NULL);
3095
3096         if (result != 0)
3097           {
3098             int errsv = get_socket_errno ();
3099
3100             if (errsv == WSAEINTR)
3101               continue;
3102
3103             if (errsv == WSAEWOULDBLOCK)
3104               win32_unset_event_mask (socket, FD_WRITE);
3105
3106             if (socket->priv->blocking &&
3107                 errsv == WSAEWOULDBLOCK)
3108               continue;
3109
3110             g_set_error (error, G_IO_ERROR,
3111                          socket_io_error_from_errno (errsv),
3112                          _("Error sending message: %s"), socket_strerror (errsv));
3113
3114             return -1;
3115           }
3116         break;
3117       }
3118
3119     return bytes_sent;
3120   }
3121 #endif
3122 }
3123
3124 /**
3125  * g_socket_receive_message:
3126  * @socket: a #GSocket
3127  * @address: a pointer to a #GSocketAddress pointer, or %NULL
3128  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3129  * @num_vectors: the number of elements in @vectors, or -1
3130  * @messages: (array length=num_messages) (allow-none): a pointer which
3131  *    may be filled with an array of #GSocketControlMessages, or %NULL
3132  * @num_messages: a pointer which will be filled with the number of
3133  *    elements in @messages, or %NULL
3134  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3135  * @cancellable: (allow-none): a %GCancellable or %NULL
3136  * @error: a #GError pointer, or %NULL
3137  *
3138  * Receive data from a socket.  This is the most complicated and
3139  * fully-featured version of this call. For easier use, see
3140  * g_socket_receive() and g_socket_receive_from().
3141  *
3142  * If @address is non-%NULL then @address will be set equal to the
3143  * source address of the received packet.
3144  * @address is owned by the caller.
3145  *
3146  * @vector must point to an array of #GInputVector structs and
3147  * @num_vectors must be the length of this array.  These structs
3148  * describe the buffers that received data will be scattered into.
3149  * If @num_vectors is -1, then @vectors is assumed to be terminated
3150  * by a #GInputVector with a %NULL buffer pointer.
3151  *
3152  * As a special case, if @num_vectors is 0 (in which case, @vectors
3153  * may of course be %NULL), then a single byte is received and
3154  * discarded. This is to facilitate the common practice of sending a
3155  * single '\0' byte for the purposes of transferring ancillary data.
3156  *
3157  * @messages, if non-%NULL, will be set to point to a newly-allocated
3158  * array of #GSocketControlMessage instances or %NULL if no such
3159  * messages was received. These correspond to the control messages
3160  * received from the kernel, one #GSocketControlMessage per message
3161  * from the kernel. This array is %NULL-terminated and must be freed
3162  * by the caller using g_free() after calling g_object_unref() on each
3163  * element. If @messages is %NULL, any control messages received will
3164  * be discarded.
3165  *
3166  * @num_messages, if non-%NULL, will be set to the number of control
3167  * messages received.
3168  *
3169  * If both @messages and @num_messages are non-%NULL, then
3170  * @num_messages gives the number of #GSocketControlMessage instances
3171  * in @messages (ie: not including the %NULL terminator).
3172  *
3173  * @flags is an in/out parameter. The commonly available arguments
3174  * for this are available in the #GSocketMsgFlags enum, but the
3175  * values there are the same as the system values, and the flags
3176  * are passed in as-is, so you can pass in system-specific flags too
3177  * (and g_socket_receive_message() may pass system-specific flags out).
3178  *
3179  * As with g_socket_receive(), data may be discarded if @socket is
3180  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3181  * provide enough buffer space to read a complete message. You can pass
3182  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3183  * removing it from the receive queue, but there is no portable way to find
3184  * out the length of the message other than by reading it into a
3185  * sufficiently-large buffer.
3186  *
3187  * If the socket is in blocking mode the call will block until there
3188  * is some data to receive, the connection is closed, or there is an
3189  * error. If there is no data available and the socket is in
3190  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3191  * returned. To be notified when data is available, wait for the
3192  * %G_IO_IN condition.
3193  *
3194  * On error -1 is returned and @error is set accordingly.
3195  *
3196  * Returns: Number of bytes read, or 0 if the connection was closed by
3197  * the peer, or -1 on error
3198  *
3199  * Since: 2.22
3200  */
3201 gssize
3202 g_socket_receive_message (GSocket                 *socket,
3203                           GSocketAddress         **address,
3204                           GInputVector            *vectors,
3205                           gint                     num_vectors,
3206                           GSocketControlMessage ***messages,
3207                           gint                    *num_messages,
3208                           gint                    *flags,
3209                           GCancellable            *cancellable,
3210                           GError                 **error)
3211 {
3212   GInputVector one_vector;
3213   char one_byte;
3214
3215   if (!check_socket (socket, error))
3216     return -1;
3217
3218   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3219     return -1;
3220
3221   if (num_vectors == -1)
3222     {
3223       for (num_vectors = 0;
3224            vectors[num_vectors].buffer != NULL;
3225            num_vectors++)
3226         ;
3227     }
3228
3229   if (num_vectors == 0)
3230     {
3231       one_vector.buffer = &one_byte;
3232       one_vector.size = 1;
3233       num_vectors = 1;
3234       vectors = &one_vector;
3235     }
3236
3237 #ifndef G_OS_WIN32
3238   {
3239     struct msghdr msg;
3240     gssize result;
3241     struct sockaddr_storage one_sockaddr;
3242
3243     /* name */
3244     if (address)
3245       {
3246         msg.msg_name = &one_sockaddr;
3247         msg.msg_namelen = sizeof (struct sockaddr_storage);
3248       }
3249     else
3250       {
3251         msg.msg_name = NULL;
3252         msg.msg_namelen = 0;
3253       }
3254
3255     /* iov */
3256     /* this entire expression will be evaluated at compile time */
3257     if (sizeof *msg.msg_iov == sizeof *vectors &&
3258         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3259         G_STRUCT_OFFSET (struct iovec, iov_base) ==
3260         G_STRUCT_OFFSET (GInputVector, buffer) &&
3261         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3262         G_STRUCT_OFFSET (struct iovec, iov_len) ==
3263         G_STRUCT_OFFSET (GInputVector, size))
3264       /* ABI is compatible */
3265       {
3266         msg.msg_iov = (struct iovec *) vectors;
3267         msg.msg_iovlen = num_vectors;
3268       }
3269     else
3270       /* ABI is incompatible */
3271       {
3272         gint i;
3273
3274         msg.msg_iov = g_newa (struct iovec, num_vectors);
3275         for (i = 0; i < num_vectors; i++)
3276           {
3277             msg.msg_iov[i].iov_base = vectors[i].buffer;
3278             msg.msg_iov[i].iov_len = vectors[i].size;
3279           }
3280         msg.msg_iovlen = num_vectors;
3281       }
3282
3283     /* control */
3284     msg.msg_control = g_alloca (2048);
3285     msg.msg_controllen = 2048;
3286
3287     /* flags */
3288     if (flags != NULL)
3289       msg.msg_flags = *flags;
3290     else
3291       msg.msg_flags = 0;
3292
3293     /* We always set the close-on-exec flag so we don't leak file
3294      * descriptors into child processes.  Note that gunixfdmessage.c
3295      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3296      */
3297 #ifdef MSG_CMSG_CLOEXEC
3298     msg.msg_flags |= MSG_CMSG_CLOEXEC;
3299 #endif
3300
3301     /* do it */
3302     while (1)
3303       {
3304         if (socket->priv->blocking &&
3305             !g_socket_condition_wait (socket,
3306                                       G_IO_IN, cancellable, error))
3307           return -1;
3308
3309         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3310 #ifdef MSG_CMSG_CLOEXEC 
3311         if (result < 0 && get_socket_errno () == EINVAL)
3312           {
3313             /* We must be running on an old kernel.  Call without the flag. */
3314             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3315             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3316           }
3317 #endif
3318
3319         if (result < 0)
3320           {
3321             int errsv = get_socket_errno ();
3322
3323             if (errsv == EINTR)
3324               continue;
3325
3326             if (socket->priv->blocking &&
3327                 (errsv == EWOULDBLOCK ||
3328                  errsv == EAGAIN))
3329               continue;
3330
3331             g_set_error (error, G_IO_ERROR,
3332                          socket_io_error_from_errno (errsv),
3333                          _("Error receiving message: %s"), socket_strerror (errsv));
3334
3335             return -1;
3336           }
3337         break;
3338       }
3339
3340     /* decode address */
3341     if (address != NULL)
3342       {
3343         if (msg.msg_namelen > 0)
3344           *address = g_socket_address_new_from_native (msg.msg_name,
3345                                                        msg.msg_namelen);
3346         else
3347           *address = NULL;
3348       }
3349
3350     /* decode control messages */
3351     {
3352       GPtrArray *my_messages = NULL;
3353       struct cmsghdr *cmsg;
3354
3355       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3356         {
3357           GSocketControlMessage *message;
3358
3359           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3360                                                           cmsg->cmsg_type,
3361                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3362                                                           CMSG_DATA (cmsg));
3363           if (message == NULL)
3364             /* We've already spewed about the problem in the
3365                deserialization code, so just continue */
3366             continue;
3367
3368           if (messages == NULL)
3369             {
3370               /* we have to do it this way if the user ignores the
3371                * messages so that we will close any received fds.
3372                */
3373               g_object_unref (message);
3374             }
3375           else
3376             {
3377               if (my_messages == NULL)
3378                 my_messages = g_ptr_array_new ();
3379               g_ptr_array_add (my_messages, message);
3380             }
3381         }
3382
3383       if (num_messages)
3384         *num_messages = my_messages != NULL ? my_messages->len : 0;
3385
3386       if (messages)
3387         {
3388           if (my_messages == NULL)
3389             {
3390               *messages = NULL;
3391             }
3392           else
3393             {
3394               g_ptr_array_add (my_messages, NULL);
3395               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3396             }
3397         }
3398       else
3399         {
3400           g_assert (my_messages == NULL);
3401         }
3402     }
3403
3404     /* capture the flags */
3405     if (flags != NULL)
3406       *flags = msg.msg_flags;
3407
3408     return result;
3409   }
3410 #else
3411   {
3412     struct sockaddr_storage addr;
3413     int addrlen;
3414     DWORD bytes_received;
3415     DWORD win_flags;
3416     int result;
3417     WSABUF *bufs;
3418     gint i;
3419
3420     /* iov */
3421     bufs = g_newa (WSABUF, num_vectors);
3422     for (i = 0; i < num_vectors; i++)
3423       {
3424         bufs[i].buf = (char *)vectors[i].buffer;
3425         bufs[i].len = (gulong)vectors[i].size;
3426       }
3427
3428     /* flags */
3429     if (flags != NULL)
3430       win_flags = *flags;
3431     else
3432       win_flags = 0;
3433
3434     /* do it */
3435     while (1)
3436       {
3437         if (socket->priv->blocking &&
3438             !g_socket_condition_wait (socket,
3439                                       G_IO_IN, cancellable, error))
3440           return -1;
3441
3442         addrlen = sizeof addr;
3443         if (address)
3444           result = WSARecvFrom (socket->priv->fd,
3445                                 bufs, num_vectors,
3446                                 &bytes_received, &win_flags,
3447                                 (struct sockaddr *)&addr, &addrlen,
3448                                 NULL, NULL);
3449         else
3450           result = WSARecv (socket->priv->fd,
3451                             bufs, num_vectors,
3452                             &bytes_received, &win_flags,
3453                             NULL, NULL);
3454         if (result != 0)
3455           {
3456             int errsv = get_socket_errno ();
3457
3458             if (errsv == WSAEINTR)
3459               continue;
3460
3461             win32_unset_event_mask (socket, FD_READ);
3462
3463             if (socket->priv->blocking &&
3464                 errsv == WSAEWOULDBLOCK)
3465               continue;
3466
3467             g_set_error (error, G_IO_ERROR,
3468                          socket_io_error_from_errno (errsv),
3469                          _("Error receiving message: %s"), socket_strerror (errsv));
3470
3471             return -1;
3472           }
3473         win32_unset_event_mask (socket, FD_READ);
3474         break;
3475       }
3476
3477     /* decode address */
3478     if (address != NULL)
3479       {
3480         if (addrlen > 0)
3481           *address = g_socket_address_new_from_native (&addr, addrlen);
3482         else
3483           *address = NULL;
3484       }
3485
3486     /* capture the flags */
3487     if (flags != NULL)
3488       *flags = win_flags;
3489
3490     if (messages != NULL)
3491       *messages = NULL;
3492     if (num_messages != NULL)
3493       *num_messages = 0;
3494
3495     return bytes_received;
3496   }
3497 #endif
3498 }
3499
3500 /**
3501  * g_socket_get_credentials:
3502  * @socket: a #GSocket.
3503  * @error: #GError for error reporting, or %NULL to ignore.
3504  *
3505  * Returns the credentials of the foreign process connected to this
3506  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3507  * sockets).
3508  *
3509  * If this operation isn't supported on the OS, the method fails with
3510  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3511  * by reading the %SO_PEERCRED option on the underlying socket.
3512  *
3513  * Other ways to obtain credentials from a foreign peer includes the
3514  * #GUnixCredentialsMessage type and
3515  * g_unix_connection_send_credentials() /
3516  * g_unix_connection_receive_credentials() functions.
3517  *
3518  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3519  * that must be freed with g_object_unref().
3520  *
3521  * Since: 2.26
3522  */
3523 GCredentials *
3524 g_socket_get_credentials (GSocket   *socket,
3525                           GError   **error)
3526 {
3527   GCredentials *ret;
3528
3529   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3530   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3531
3532   ret = NULL;
3533
3534 #if defined(__linux__) || defined(__OpenBSD__)
3535   {
3536     socklen_t optlen;
3537 #if defined(__linux__)
3538     struct ucred native_creds;
3539     optlen = sizeof (struct ucred);
3540 #elif defined(__OpenBSD__)
3541     struct sockpeercred native_creds;
3542     optlen = sizeof (struct sockpeercred);
3543 #endif
3544     if (getsockopt (socket->priv->fd,
3545                     SOL_SOCKET,
3546                     SO_PEERCRED,
3547                     (void *)&native_creds,
3548                     &optlen) != 0)
3549       {
3550         int errsv = get_socket_errno ();
3551         g_set_error (error,
3552                      G_IO_ERROR,
3553                      socket_io_error_from_errno (errsv),
3554                      _("Unable to get pending error: %s"),
3555                      socket_strerror (errsv));
3556       }
3557     else
3558       {
3559         ret = g_credentials_new ();
3560         g_credentials_set_native (ret,
3561 #if defined(__linux__)
3562                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
3563 #elif defined(__OpenBSD__)
3564                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3565 #endif
3566                                   &native_creds);
3567       }
3568   }
3569 #else
3570   g_set_error_literal (error,
3571                        G_IO_ERROR,
3572                        G_IO_ERROR_NOT_SUPPORTED,
3573                        _("g_socket_get_credentials not implemented for this OS"));
3574 #endif
3575
3576   return ret;
3577 }