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