switch GSocket to monotonic time for timeouts
[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 #include <errno.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <stdlib.h>
36
37 #ifndef G_OS_WIN32
38 # include <fcntl.h>
39 # include <unistd.h>
40 #endif
41
42 #ifdef HAVE_SYS_UIO_H
43 #include <sys/uio.h>
44 #endif
45
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
50 #include "gioerror.h"
51 #include "gioenums.h"
52 #include "gioerror.h"
53 #include "gnetworkingprivate.h"
54 #include "gsocketaddress.h"
55 #include "gsocketcontrolmessage.h"
56 #include "gcredentials.h"
57 #include "glibintl.h"
58
59 /**
60  * SECTION:gsocket
61  * @short_description: Low-level socket object
62  * @include: gio/gio.h
63  * @see_also: #GInitable
64  *
65  * A #GSocket is a low-level networking primitive. It is a more or less
66  * direct mapping of the BSD socket API in a portable GObject based API.
67  * It supports both the UNIX socket implementations and winsock2 on Windows.
68  *
69  * #GSocket is the platform independent base upon which the higher level
70  * network primitives are based. Applications are not typically meant to
71  * use it directly, but rather through classes like #GSocketClient,
72  * #GSocketService and #GSocketConnection. However there may be cases where
73  * direct use of #GSocket is useful.
74  *
75  * #GSocket implements the #GInitable interface, so if it is manually constructed
76  * by e.g. g_object_new() you must call g_initable_init() and check the
77  * results before using the object. This is done automatically in
78  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
79  * %NULL.
80  *
81  * Sockets operate in two general modes, blocking or non-blocking. When
82  * in blocking mode all operations block until the requested operation
83  * is finished or there is an error. In non-blocking mode all calls that
84  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
85  * To know when a call would successfully run you can call g_socket_condition_check(),
86  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
87  * attach it to a #GMainContext to get callbacks when I/O is possible.
88  * Note that all sockets are always set to non blocking mode in the system, and
89  * blocking mode is emulated in GSocket.
90  *
91  * When working in non-blocking mode applications should always be able to
92  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
93  * function said that I/O was possible. This can easily happen in case
94  * of a race condition in the application, but it can also happen for other
95  * reasons. For instance, on Windows a socket is always seen as writable
96  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
97  *
98  * #GSocket<!-- -->s can be either connection oriented or datagram based.
99  * For connection oriented types you must first establish a connection by
100  * either connecting to an address or accepting a connection from another
101  * address. For connectionless socket types the target/source address is
102  * specified or received in each I/O operation.
103  *
104  * All socket file descriptors are set to be close-on-exec.
105  *
106  * Note that creating a #GSocket causes the signal %SIGPIPE to be
107  * ignored for the remainder of the program. If you are writing a
108  * command-line utility that uses #GSocket, you may need to take into
109  * account the fact that your program will not automatically be killed
110  * if it tries to write to %stdout after it has been closed.
111  *
112  * Since: 2.22
113  */
114
115 static void     g_socket_initable_iface_init (GInitableIface  *iface);
116 static gboolean g_socket_initable_init       (GInitable       *initable,
117                                               GCancellable    *cancellable,
118                                               GError         **error);
119
120 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
121                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
122                                                 g_socket_initable_iface_init));
123
124 enum
125 {
126   PROP_0,
127   PROP_FAMILY,
128   PROP_TYPE,
129   PROP_PROTOCOL,
130   PROP_FD,
131   PROP_BLOCKING,
132   PROP_LISTEN_BACKLOG,
133   PROP_KEEPALIVE,
134   PROP_LOCAL_ADDRESS,
135   PROP_REMOTE_ADDRESS,
136   PROP_TIMEOUT
137 };
138
139 struct _GSocketPrivate
140 {
141   GSocketFamily   family;
142   GSocketType     type;
143   GSocketProtocol protocol;
144   gint            fd;
145   gint            listen_backlog;
146   guint           timeout;
147   GError         *construct_error;
148   GSocketAddress *remote_address;
149   guint           inited : 1;
150   guint           blocking : 1;
151   guint           keepalive : 1;
152   guint           closed : 1;
153   guint           connected : 1;
154   guint           listening : 1;
155   guint           timed_out : 1;
156   guint           connect_pending : 1;
157 #ifdef G_OS_WIN32
158   WSAEVENT        event;
159   int             current_events;
160   int             current_errors;
161   int             selected_events;
162   GList          *requested_conditions; /* list of requested GIOCondition * */
163 #endif
164 };
165
166 static int
167 get_socket_errno (void)
168 {
169 #ifndef G_OS_WIN32
170   return errno;
171 #else
172   return WSAGetLastError ();
173 #endif
174 }
175
176 static GIOErrorEnum
177 socket_io_error_from_errno (int err)
178 {
179 #ifndef G_OS_WIN32
180   return g_io_error_from_errno (err);
181 #else
182   switch (err)
183     {
184     case WSAEADDRINUSE:
185       return G_IO_ERROR_ADDRESS_IN_USE;
186     case WSAEWOULDBLOCK:
187       return G_IO_ERROR_WOULD_BLOCK;
188     case WSAEACCES:
189       return G_IO_ERROR_PERMISSION_DENIED;
190     case WSA_INVALID_HANDLE:
191     case WSA_INVALID_PARAMETER:
192     case WSAEBADF:
193     case WSAENOTSOCK:
194       return G_IO_ERROR_INVALID_ARGUMENT;
195     case WSAEPROTONOSUPPORT:
196       return G_IO_ERROR_NOT_SUPPORTED;
197     case WSAECANCELLED:
198       return G_IO_ERROR_CANCELLED;
199     case WSAESOCKTNOSUPPORT:
200     case WSAEOPNOTSUPP:
201     case WSAEPFNOSUPPORT:
202     case WSAEAFNOSUPPORT:
203       return G_IO_ERROR_NOT_SUPPORTED;
204     default:
205       return G_IO_ERROR_FAILED;
206     }
207 #endif
208 }
209
210 static const char *
211 socket_strerror (int err)
212 {
213 #ifndef G_OS_WIN32
214   return g_strerror (err);
215 #else
216   static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
217   char *msg;
218
219   msg = g_win32_error_message (err);
220   g_static_private_set (&last_msg, msg, g_free);
221
222   return msg;
223 #endif
224 }
225
226 #ifdef G_OS_WIN32
227 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
228 static void
229 _win32_unset_event_mask (GSocket *socket, int mask)
230 {
231   socket->priv->current_events &= ~mask;
232   socket->priv->current_errors &= ~mask;
233 }
234 #else
235 #define win32_unset_event_mask(_socket, _mask)
236 #endif
237
238 static void
239 set_fd_nonblocking (int fd)
240 {
241 #ifndef G_OS_WIN32
242   glong arg;
243 #else
244   gulong arg;
245 #endif
246
247 #ifndef G_OS_WIN32
248   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
249     {
250       g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
251       arg = 0;
252     }
253
254   arg = arg | O_NONBLOCK;
255
256   if (fcntl (fd, F_SETFL, arg) < 0)
257       g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
258 #else
259   arg = TRUE;
260
261   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
262     {
263       int errsv = get_socket_errno ();
264       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
265     }
266 #endif
267 }
268
269 static gboolean
270 check_socket (GSocket *socket,
271               GError **error)
272 {
273   if (!socket->priv->inited)
274     {
275       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
276                            _("Invalid socket, not initialized"));
277       return FALSE;
278     }
279
280   if (socket->priv->construct_error)
281     {
282       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
283                    _("Invalid socket, initialization failed due to: %s"),
284                    socket->priv->construct_error->message);
285       return FALSE;
286     }
287
288   if (socket->priv->closed)
289     {
290       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
291                            _("Socket is already closed"));
292       return FALSE;
293     }
294
295   if (socket->priv->timed_out)
296     {
297       socket->priv->timed_out = FALSE;
298       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
299                            _("Socket I/O timed out"));
300       return FALSE;
301     }
302
303   return TRUE;
304 }
305
306 static void
307 g_socket_details_from_fd (GSocket *socket)
308 {
309   struct sockaddr_storage address;
310   gint fd;
311   guint addrlen;
312   guint optlen;
313   int value;
314   int errsv;
315 #ifdef G_OS_WIN32
316   /* See bug #611756 */
317   BOOL bool_val = FALSE;
318 #else
319   int bool_val;
320 #endif
321
322   fd = socket->priv->fd;
323   optlen = sizeof value;
324   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
325     {
326       errsv = get_socket_errno ();
327
328       switch (errsv)
329         {
330 #ifdef ENOTSOCK
331          case ENOTSOCK:
332 #endif
333 #ifdef WSAENOTSOCK
334          case WSAENOTSOCK:
335 #endif
336          case EBADF:
337           /* programmer error */
338           g_error ("creating GSocket from fd %d: %s\n",
339                    fd, socket_strerror (errsv));
340          default:
341            break;
342         }
343
344       goto err;
345     }
346
347   g_assert (optlen == sizeof value);
348   switch (value)
349     {
350      case SOCK_STREAM:
351       socket->priv->type = G_SOCKET_TYPE_STREAM;
352       break;
353
354      case SOCK_DGRAM:
355       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
356       break;
357
358      case SOCK_SEQPACKET:
359       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
360       break;
361
362      default:
363       socket->priv->type = G_SOCKET_TYPE_INVALID;
364       break;
365     }
366
367   addrlen = sizeof address;
368   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
369     {
370       errsv = get_socket_errno ();
371       goto err;
372     }
373
374   g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
375             sizeof address.ss_family <= addrlen);
376   switch (address.ss_family)
377     {
378      case G_SOCKET_FAMILY_IPV4:
379      case G_SOCKET_FAMILY_IPV6:
380        socket->priv->family = address.ss_family;
381        switch (socket->priv->type)
382          {
383          case G_SOCKET_TYPE_STREAM:
384            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
385            break;
386
387          case G_SOCKET_TYPE_DATAGRAM:
388            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
389            break;
390
391          case G_SOCKET_TYPE_SEQPACKET:
392            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
393            break;
394
395          default:
396            break;
397          }
398        break;
399
400      case G_SOCKET_FAMILY_UNIX:
401        socket->priv->family = G_SOCKET_FAMILY_UNIX;
402        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
403        break;
404
405      default:
406        socket->priv->family = G_SOCKET_FAMILY_INVALID;
407        break;
408     }
409
410   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
411     {
412       addrlen = sizeof address;
413       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
414         socket->priv->connected = TRUE;
415     }
416
417   optlen = sizeof bool_val;
418   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
419                   (void *)&bool_val, &optlen) == 0)
420     {
421 #ifndef G_OS_WIN32
422       /* Experimentation indicates that the SO_KEEPALIVE value is
423        * actually a char on Windows, even if documentation claims it
424        * to be a BOOL which is a typedef for int. So this g_assert()
425        * fails. See bug #611756.
426        */
427       g_assert (optlen == sizeof bool_val);
428 #endif
429       socket->priv->keepalive = !!bool_val;
430     }
431   else
432     {
433       /* Can't read, maybe not supported, assume FALSE */
434       socket->priv->keepalive = FALSE;
435     }
436
437   return;
438
439  err:
440   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
441                socket_io_error_from_errno (errsv),
442                _("creating GSocket from fd: %s"),
443                socket_strerror (errsv));
444 }
445
446 static gint
447 g_socket_create_socket (GSocketFamily   family,
448                         GSocketType     type,
449                         int             protocol,
450                         GError        **error)
451 {
452   gint native_type;
453   gint fd;
454
455   switch (type)
456     {
457      case G_SOCKET_TYPE_STREAM:
458       native_type = SOCK_STREAM;
459       break;
460
461      case G_SOCKET_TYPE_DATAGRAM:
462       native_type = SOCK_DGRAM;
463       break;
464
465      case G_SOCKET_TYPE_SEQPACKET:
466       native_type = SOCK_SEQPACKET;
467       break;
468
469      default:
470       g_assert_not_reached ();
471     }
472
473   if (protocol == -1)
474     {
475       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
476                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
477       return -1;
478     }
479
480 #ifdef SOCK_CLOEXEC
481   fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
482   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
483   if (fd < 0 && errno == EINVAL)
484 #endif
485     fd = socket (family, native_type, protocol);
486
487   if (fd < 0)
488     {
489       int errsv = get_socket_errno ();
490
491       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
492                    _("Unable to create socket: %s"), socket_strerror (errsv));
493     }
494
495 #ifndef G_OS_WIN32
496   {
497     int flags;
498
499     /* We always want to set close-on-exec to protect users. If you
500        need to so some weird inheritance to exec you can re-enable this
501        using lower level hacks with g_socket_get_fd(). */
502     flags = fcntl (fd, F_GETFD, 0);
503     if (flags != -1 &&
504         (flags & FD_CLOEXEC) == 0)
505       {
506         flags |= FD_CLOEXEC;
507         fcntl (fd, F_SETFD, flags);
508       }
509   }
510 #endif
511
512   return fd;
513 }
514
515 static void
516 g_socket_constructed (GObject *object)
517 {
518   GSocket *socket = G_SOCKET (object);
519
520   if (socket->priv->fd >= 0)
521     /* create socket->priv info from the fd */
522     g_socket_details_from_fd (socket);
523
524   else
525     /* create the fd from socket->priv info */
526     socket->priv->fd = g_socket_create_socket (socket->priv->family,
527                                                socket->priv->type,
528                                                socket->priv->protocol,
529                                                &socket->priv->construct_error);
530
531   /* Always use native nonblocking sockets, as
532      windows sets sockets to nonblocking automatically
533      in certain operations. This way we make things work
534      the same on all platforms */
535   if (socket->priv->fd != -1)
536     set_fd_nonblocking (socket->priv->fd);
537 }
538
539 static void
540 g_socket_get_property (GObject    *object,
541                        guint       prop_id,
542                        GValue     *value,
543                        GParamSpec *pspec)
544 {
545   GSocket *socket = G_SOCKET (object);
546   GSocketAddress *address;
547
548   switch (prop_id)
549     {
550       case PROP_FAMILY:
551         g_value_set_enum (value, socket->priv->family);
552         break;
553
554       case PROP_TYPE:
555         g_value_set_enum (value, socket->priv->type);
556         break;
557
558       case PROP_PROTOCOL:
559         g_value_set_enum (value, socket->priv->protocol);
560         break;
561
562       case PROP_FD:
563         g_value_set_int (value, socket->priv->fd);
564         break;
565
566       case PROP_BLOCKING:
567         g_value_set_boolean (value, socket->priv->blocking);
568         break;
569
570       case PROP_LISTEN_BACKLOG:
571         g_value_set_int (value, socket->priv->listen_backlog);
572         break;
573
574       case PROP_KEEPALIVE:
575         g_value_set_boolean (value, socket->priv->keepalive);
576         break;
577
578       case PROP_LOCAL_ADDRESS:
579         address = g_socket_get_local_address (socket, NULL);
580         g_value_take_object (value, address);
581         break;
582
583       case PROP_REMOTE_ADDRESS:
584         address = g_socket_get_remote_address (socket, NULL);
585         g_value_take_object (value, address);
586         break;
587
588       case PROP_TIMEOUT:
589         g_value_set_uint (value, socket->priv->timeout);
590         break;
591
592       default:
593         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
594     }
595 }
596
597 static void
598 g_socket_set_property (GObject      *object,
599                        guint         prop_id,
600                        const GValue *value,
601                        GParamSpec   *pspec)
602 {
603   GSocket *socket = G_SOCKET (object);
604
605   switch (prop_id)
606     {
607       case PROP_FAMILY:
608         socket->priv->family = g_value_get_enum (value);
609         break;
610
611       case PROP_TYPE:
612         socket->priv->type = g_value_get_enum (value);
613         break;
614
615       case PROP_PROTOCOL:
616         socket->priv->protocol = g_value_get_enum (value);
617         break;
618
619       case PROP_FD:
620         socket->priv->fd = g_value_get_int (value);
621         break;
622
623       case PROP_BLOCKING:
624         g_socket_set_blocking (socket, g_value_get_boolean (value));
625         break;
626
627       case PROP_LISTEN_BACKLOG:
628         g_socket_set_listen_backlog (socket, g_value_get_int (value));
629         break;
630
631       case PROP_KEEPALIVE:
632         g_socket_set_keepalive (socket, g_value_get_boolean (value));
633         break;
634
635       case PROP_TIMEOUT:
636         g_socket_set_timeout (socket, g_value_get_uint (value));
637         break;
638
639       default:
640         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
641     }
642 }
643
644 static void
645 g_socket_finalize (GObject *object)
646 {
647   GSocket *socket = G_SOCKET (object);
648
649   g_clear_error (&socket->priv->construct_error);
650
651   if (socket->priv->fd != -1 &&
652       !socket->priv->closed)
653     g_socket_close (socket, NULL);
654
655   if (socket->priv->remote_address)
656     g_object_unref (socket->priv->remote_address);
657
658 #ifdef G_OS_WIN32
659   if (socket->priv->event != WSA_INVALID_EVENT)
660     {
661       WSACloseEvent (socket->priv->event);
662       socket->priv->event = WSA_INVALID_EVENT;
663     }
664
665   g_assert (socket->priv->requested_conditions == NULL);
666 #endif
667
668   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
669     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
670 }
671
672 static void
673 g_socket_class_init (GSocketClass *klass)
674 {
675   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
676   volatile GType type;
677
678   /* Make sure winsock has been initialized */
679   type = g_inet_address_get_type ();
680
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: 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: 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: 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 is
1758  * some data to receive or there is an error. If there is no data available
1759  * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1760  * will be returned. To be notified when data is available, wait for the
1761  * %G_IO_IN condition.
1762  *
1763  * On error -1 is returned and @error is set accordingly.
1764  *
1765  * Returns: Number of bytes read, or -1 on error
1766  *
1767  * Since: 2.22
1768  */
1769 gssize
1770 g_socket_receive (GSocket       *socket,
1771                   gchar         *buffer,
1772                   gsize          size,
1773                   GCancellable  *cancellable,
1774                   GError       **error)
1775 {
1776   return g_socket_receive_with_blocking (socket, buffer, size,
1777                                          socket->priv->blocking,
1778                                          cancellable, error);
1779 }
1780
1781 /**
1782  * g_socket_receive_with_blocking:
1783  * @socket: a #GSocket
1784  * @buffer: a buffer to read data into (which should be at least @size
1785  *     bytes long).
1786  * @size: the number of bytes you want to read from the socket
1787  * @blocking: whether to do blocking or non-blocking I/O
1788  * @cancellable: a %GCancellable or %NULL
1789  * @error: #GError for error reporting, or %NULL to ignore.
1790  *
1791  * This behaves exactly the same as g_socket_receive(), except that
1792  * the choice of blocking or non-blocking behavior is determined by
1793  * the @blocking argument rather than by @socket's properties.
1794  *
1795  * Returns: Number of bytes read, or -1 on error
1796  *
1797  * Since: 2.26
1798  */
1799 gssize
1800 g_socket_receive_with_blocking (GSocket       *socket,
1801                                 gchar         *buffer,
1802                                 gsize          size,
1803                                 gboolean       blocking,
1804                                 GCancellable  *cancellable,
1805                                 GError       **error)
1806 {
1807   gssize ret;
1808
1809   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1810
1811   if (!check_socket (socket, error))
1812     return -1;
1813
1814   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1815     return -1;
1816
1817   while (1)
1818     {
1819       if (blocking &&
1820           !g_socket_condition_wait (socket,
1821                                     G_IO_IN, cancellable, error))
1822         return -1;
1823
1824       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1825         {
1826           int errsv = get_socket_errno ();
1827
1828           if (errsv == EINTR)
1829             continue;
1830
1831           if (blocking)
1832             {
1833 #ifdef WSAEWOULDBLOCK
1834               if (errsv == WSAEWOULDBLOCK)
1835                 continue;
1836 #else
1837               if (errsv == EWOULDBLOCK ||
1838                   errsv == EAGAIN)
1839                 continue;
1840 #endif
1841             }
1842
1843           win32_unset_event_mask (socket, FD_READ);
1844
1845           g_set_error (error, G_IO_ERROR,
1846                        socket_io_error_from_errno (errsv),
1847                        _("Error receiving data: %s"), socket_strerror (errsv));
1848           return -1;
1849         }
1850
1851       win32_unset_event_mask (socket, FD_READ);
1852
1853       break;
1854     }
1855
1856   return ret;
1857 }
1858
1859 /**
1860  * g_socket_receive_from:
1861  * @socket: a #GSocket
1862  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1863  * @buffer: a buffer to read data into (which should be at least @size
1864  *     bytes long).
1865  * @size: the number of bytes you want to read from the socket
1866  * @cancellable: a %GCancellable or %NULL
1867  * @error: #GError for error reporting, or %NULL to ignore.
1868  *
1869  * Receive data (up to @size bytes) from a socket.
1870  *
1871  * If @address is non-%NULL then @address will be set equal to the
1872  * source address of the received packet.
1873  * @address is owned by the caller.
1874  *
1875  * See g_socket_receive() for additional information.
1876  *
1877  * Returns: Number of bytes read, or -1 on error
1878  *
1879  * Since: 2.22
1880  */
1881 gssize
1882 g_socket_receive_from (GSocket         *socket,
1883                        GSocketAddress **address,
1884                        gchar           *buffer,
1885                        gsize            size,
1886                        GCancellable    *cancellable,
1887                        GError         **error)
1888 {
1889   GInputVector v;
1890
1891   v.buffer = buffer;
1892   v.size = size;
1893
1894   return g_socket_receive_message (socket,
1895                                    address,
1896                                    &v, 1,
1897                                    NULL, 0, NULL,
1898                                    cancellable,
1899                                    error);
1900 }
1901
1902 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1903  * one, which can be confusing and annoying. So if possible, we want
1904  * to suppress the signal entirely.
1905  */
1906 #ifdef MSG_NOSIGNAL
1907 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1908 #else
1909 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1910 #endif
1911
1912 /**
1913  * g_socket_send:
1914  * @socket: a #GSocket
1915  * @buffer: the buffer containing the data to send.
1916  * @size: the number of bytes to send
1917  * @cancellable: a %GCancellable or %NULL
1918  * @error: #GError for error reporting, or %NULL to ignore.
1919  *
1920  * Tries to send @size bytes from @buffer on the socket. This is
1921  * mainly used by connection-oriented sockets; it is identical to
1922  * g_socket_send_to() with @address set to %NULL.
1923  *
1924  * If the socket is in blocking mode the call will block until there is
1925  * space for the data in the socket queue. If there is no space available
1926  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1927  * will be returned. To be notified when space is available, wait for the
1928  * %G_IO_OUT condition. Note though that you may still receive
1929  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1930  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1931  * very common due to the way the underlying APIs work.)
1932  *
1933  * On error -1 is returned and @error is set accordingly.
1934  *
1935  * Returns: Number of bytes written (which may be less than @size), or -1
1936  * on error
1937  *
1938  * Since: 2.22
1939  */
1940 gssize
1941 g_socket_send (GSocket       *socket,
1942                const gchar   *buffer,
1943                gsize          size,
1944                GCancellable  *cancellable,
1945                GError       **error)
1946 {
1947   return g_socket_send_with_blocking (socket, buffer, size,
1948                                       socket->priv->blocking,
1949                                       cancellable, error);
1950 }
1951
1952 /**
1953  * g_socket_send_with_blocking:
1954  * @socket: a #GSocket
1955  * @buffer: the buffer containing the data to send.
1956  * @size: the number of bytes to send
1957  * @blocking: whether to do blocking or non-blocking I/O
1958  * @cancellable: a %GCancellable or %NULL
1959  * @error: #GError for error reporting, or %NULL to ignore.
1960  *
1961  * This behaves exactly the same as g_socket_send(), except that
1962  * the choice of blocking or non-blocking behavior is determined by
1963  * the @blocking argument rather than by @socket's properties.
1964  *
1965  * Returns: Number of bytes written (which may be less than @size), or -1
1966  * on error
1967  *
1968  * Since: 2.26
1969  */
1970 gssize
1971 g_socket_send_with_blocking (GSocket       *socket,
1972                              const gchar   *buffer,
1973                              gsize          size,
1974                              gboolean       blocking,
1975                              GCancellable  *cancellable,
1976                              GError       **error)
1977 {
1978   gssize ret;
1979
1980   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1981
1982   if (!check_socket (socket, error))
1983     return -1;
1984
1985   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1986     return -1;
1987
1988   while (1)
1989     {
1990       if (blocking &&
1991           !g_socket_condition_wait (socket,
1992                                     G_IO_OUT, cancellable, error))
1993         return -1;
1994
1995       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1996         {
1997           int errsv = get_socket_errno ();
1998
1999           if (errsv == EINTR)
2000             continue;
2001
2002 #ifdef WSAEWOULDBLOCK
2003           if (errsv == WSAEWOULDBLOCK)
2004             win32_unset_event_mask (socket, FD_WRITE);
2005 #endif
2006
2007           if (blocking)
2008             {
2009 #ifdef WSAEWOULDBLOCK
2010               if (errsv == WSAEWOULDBLOCK)
2011                 continue;
2012 #else
2013               if (errsv == EWOULDBLOCK ||
2014                   errsv == EAGAIN)
2015                 continue;
2016 #endif
2017             }
2018
2019           g_set_error (error, G_IO_ERROR,
2020                        socket_io_error_from_errno (errsv),
2021                        _("Error sending data: %s"), socket_strerror (errsv));
2022           return -1;
2023         }
2024       break;
2025     }
2026
2027   return ret;
2028 }
2029
2030 /**
2031  * g_socket_send_to:
2032  * @socket: a #GSocket
2033  * @address: a #GSocketAddress, or %NULL
2034  * @buffer: the buffer containing the data to send.
2035  * @size: the number of bytes to send
2036  * @cancellable: a %GCancellable or %NULL
2037  * @error: #GError for error reporting, or %NULL to ignore.
2038  *
2039  * Tries to send @size bytes from @buffer to @address. If @address is
2040  * %NULL then the message is sent to the default receiver (set by
2041  * g_socket_connect()).
2042  *
2043  * See g_socket_send() for additional information.
2044  *
2045  * Returns: Number of bytes written (which may be less than @size), or -1
2046  * on error
2047  *
2048  * Since: 2.22
2049  */
2050 gssize
2051 g_socket_send_to (GSocket         *socket,
2052                   GSocketAddress  *address,
2053                   const gchar     *buffer,
2054                   gsize            size,
2055                   GCancellable    *cancellable,
2056                   GError         **error)
2057 {
2058   GOutputVector v;
2059
2060   v.buffer = buffer;
2061   v.size = size;
2062
2063   return g_socket_send_message (socket,
2064                                 address,
2065                                 &v, 1,
2066                                 NULL, 0,
2067                                 0,
2068                                 cancellable,
2069                                 error);
2070 }
2071
2072 /**
2073  * g_socket_shutdown:
2074  * @socket: a #GSocket
2075  * @shutdown_read: whether to shut down the read side
2076  * @shutdown_write: whether to shut down the write side
2077  * @error: #GError for error reporting, or %NULL to ignore.
2078  *
2079  * Shut down part of a full-duplex connection.
2080  *
2081  * If @shutdown_read is %TRUE then the recieving side of the connection
2082  * is shut down, and further reading is disallowed.
2083  *
2084  * If @shutdown_write is %TRUE then the sending side of the connection
2085  * is shut down, and further writing is disallowed.
2086  *
2087  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2088  *
2089  * One example where this is used is graceful disconnect for TCP connections
2090  * where you close the sending side, then wait for the other side to close
2091  * the connection, thus ensuring that the other side saw all sent data.
2092  *
2093  * Returns: %TRUE on success, %FALSE on error
2094  *
2095  * Since: 2.22
2096  */
2097 gboolean
2098 g_socket_shutdown (GSocket   *socket,
2099                    gboolean   shutdown_read,
2100                    gboolean   shutdown_write,
2101                    GError   **error)
2102 {
2103   int how;
2104
2105   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2106
2107   if (!check_socket (socket, NULL))
2108     return FALSE;
2109
2110   /* Do nothing? */
2111   if (!shutdown_read && !shutdown_write)
2112     return TRUE;
2113
2114 #ifndef G_OS_WIN32
2115   if (shutdown_read && shutdown_write)
2116     how = SHUT_RDWR;
2117   else if (shutdown_read)
2118     how = SHUT_RD;
2119   else
2120     how = SHUT_WR;
2121 #else
2122   if (shutdown_read && shutdown_write)
2123     how = SD_BOTH;
2124   else if (shutdown_read)
2125     how = SD_RECEIVE;
2126   else
2127     how = SD_SEND;
2128 #endif
2129
2130   if (shutdown (socket->priv->fd, how) != 0)
2131     {
2132       int errsv = get_socket_errno ();
2133       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2134                    _("Unable to create socket: %s"), socket_strerror (errsv));
2135       return FALSE;
2136     }
2137
2138   if (shutdown_read && shutdown_write)
2139     socket->priv->connected = FALSE;
2140
2141   return TRUE;
2142 }
2143
2144 /**
2145  * g_socket_close:
2146  * @socket: a #GSocket
2147  * @error: #GError for error reporting, or %NULL to ignore.
2148  *
2149  * Closes the socket, shutting down any active connection.
2150  *
2151  * Closing a socket does not wait for all outstanding I/O operations
2152  * to finish, so the caller should not rely on them to be guaranteed
2153  * to complete even if the close returns with no error.
2154  *
2155  * Once the socket is closed, all other operations will return
2156  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2157  * return an error.
2158  *
2159  * Sockets will be automatically closed when the last reference
2160  * is dropped, but you might want to call this function to make sure
2161  * resources are released as early as possible.
2162  *
2163  * Beware that due to the way that TCP works, it is possible for
2164  * recently-sent data to be lost if either you close a socket while the
2165  * %G_IO_IN condition is set, or else if the remote connection tries to
2166  * send something to you after you close the socket but before it has
2167  * finished reading all of the data you sent. There is no easy generic
2168  * way to avoid this problem; the easiest fix is to design the network
2169  * protocol such that the client will never send data "out of turn".
2170  * Another solution is for the server to half-close the connection by
2171  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2172  * and then wait for the client to notice this and close its side of the
2173  * connection, after which the server can safely call g_socket_close().
2174  * (This is what #GTcpConnection does if you call
2175  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2176  * only works if the client will close its connection after the server
2177  * does.)
2178  *
2179  * Returns: %TRUE on success, %FALSE on error
2180  *
2181  * Since: 2.22
2182  */
2183 gboolean
2184 g_socket_close (GSocket  *socket,
2185                 GError  **error)
2186 {
2187   int res;
2188
2189   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2190
2191   if (socket->priv->closed)
2192     return TRUE; /* Multiple close not an error */
2193
2194   if (!check_socket (socket, NULL))
2195     return FALSE;
2196
2197   while (1)
2198     {
2199 #ifdef G_OS_WIN32
2200       res = closesocket (socket->priv->fd);
2201 #else
2202       res = close (socket->priv->fd);
2203 #endif
2204       if (res == -1)
2205         {
2206           int errsv = get_socket_errno ();
2207
2208           if (errsv == EINTR)
2209             continue;
2210
2211           g_set_error (error, G_IO_ERROR,
2212                        socket_io_error_from_errno (errsv),
2213                        _("Error closing socket: %s"),
2214                        socket_strerror (errsv));
2215           return FALSE;
2216         }
2217       break;
2218     }
2219
2220   socket->priv->connected = FALSE;
2221   socket->priv->closed = TRUE;
2222   if (socket->priv->remote_address)
2223     {
2224       g_object_unref (socket->priv->remote_address);
2225       socket->priv->remote_address = NULL;
2226     }
2227
2228   return TRUE;
2229 }
2230
2231 /**
2232  * g_socket_is_closed:
2233  * @socket: a #GSocket
2234  *
2235  * Checks whether a socket is closed.
2236  *
2237  * Returns: %TRUE if socket is closed, %FALSE otherwise
2238  *
2239  * Since: 2.22
2240  */
2241 gboolean
2242 g_socket_is_closed (GSocket *socket)
2243 {
2244   return socket->priv->closed;
2245 }
2246
2247 #ifdef G_OS_WIN32
2248 /* Broken source, used on errors */
2249 static gboolean
2250 broken_prepare  (GSource *source,
2251                  gint    *timeout)
2252 {
2253   return FALSE;
2254 }
2255
2256 static gboolean
2257 broken_check (GSource *source)
2258 {
2259   return FALSE;
2260 }
2261
2262 static gboolean
2263 broken_dispatch (GSource     *source,
2264                  GSourceFunc  callback,
2265                  gpointer     user_data)
2266 {
2267   return TRUE;
2268 }
2269
2270 static GSourceFuncs broken_funcs =
2271 {
2272   broken_prepare,
2273   broken_check,
2274   broken_dispatch,
2275   NULL
2276 };
2277
2278 static gint
2279 network_events_for_condition (GIOCondition condition)
2280 {
2281   int event_mask = 0;
2282
2283   if (condition & G_IO_IN)
2284     event_mask |= (FD_READ | FD_ACCEPT);
2285   if (condition & G_IO_OUT)
2286     event_mask |= (FD_WRITE | FD_CONNECT);
2287   event_mask |= FD_CLOSE;
2288
2289   return event_mask;
2290 }
2291
2292 static void
2293 ensure_event (GSocket *socket)
2294 {
2295   if (socket->priv->event == WSA_INVALID_EVENT)
2296     socket->priv->event = WSACreateEvent();
2297 }
2298
2299 static void
2300 update_select_events (GSocket *socket)
2301 {
2302   int event_mask;
2303   GIOCondition *ptr;
2304   GList *l;
2305   WSAEVENT event;
2306
2307   ensure_event (socket);
2308
2309   event_mask = 0;
2310   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2311     {
2312       ptr = l->data;
2313       event_mask |= network_events_for_condition (*ptr);
2314     }
2315
2316   if (event_mask != socket->priv->selected_events)
2317     {
2318       /* If no events selected, disable event so we can unset
2319          nonblocking mode */
2320
2321       if (event_mask == 0)
2322         event = NULL;
2323       else
2324         event = socket->priv->event;
2325
2326       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2327         socket->priv->selected_events = event_mask;
2328     }
2329 }
2330
2331 static void
2332 add_condition_watch (GSocket      *socket,
2333                      GIOCondition *condition)
2334 {
2335   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2336
2337   socket->priv->requested_conditions =
2338     g_list_prepend (socket->priv->requested_conditions, condition);
2339
2340   update_select_events (socket);
2341 }
2342
2343 static void
2344 remove_condition_watch (GSocket      *socket,
2345                         GIOCondition *condition)
2346 {
2347   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2348
2349   socket->priv->requested_conditions =
2350     g_list_remove (socket->priv->requested_conditions, condition);
2351
2352   update_select_events (socket);
2353 }
2354
2355 static GIOCondition
2356 update_condition (GSocket *socket)
2357 {
2358   WSANETWORKEVENTS events;
2359   GIOCondition condition;
2360
2361   if (WSAEnumNetworkEvents (socket->priv->fd,
2362                             socket->priv->event,
2363                             &events) == 0)
2364     {
2365       socket->priv->current_events |= events.lNetworkEvents;
2366       if (events.lNetworkEvents & FD_WRITE &&
2367           events.iErrorCode[FD_WRITE_BIT] != 0)
2368         socket->priv->current_errors |= FD_WRITE;
2369       if (events.lNetworkEvents & FD_CONNECT &&
2370           events.iErrorCode[FD_CONNECT_BIT] != 0)
2371         socket->priv->current_errors |= FD_CONNECT;
2372     }
2373
2374   condition = 0;
2375   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2376     condition |= G_IO_IN;
2377
2378   if (socket->priv->current_events & FD_CLOSE ||
2379       socket->priv->closed)
2380     condition |= G_IO_HUP;
2381
2382   /* Never report both G_IO_OUT and HUP, these are
2383      mutually exclusive (can't write to a closed socket) */
2384   if ((condition & G_IO_HUP) == 0 &&
2385       socket->priv->current_events & FD_WRITE)
2386     {
2387       if (socket->priv->current_errors & FD_WRITE)
2388         condition |= G_IO_ERR;
2389       else
2390         condition |= G_IO_OUT;
2391     }
2392   else
2393     {
2394       if (socket->priv->current_events & FD_CONNECT)
2395         {
2396           if (socket->priv->current_errors & FD_CONNECT)
2397             condition |= (G_IO_HUP | G_IO_ERR);
2398           else
2399             condition |= G_IO_OUT;
2400         }
2401     }
2402
2403   return condition;
2404 }
2405 #endif
2406
2407 typedef struct {
2408   GSource       source;
2409   GPollFD       pollfd;
2410   GSocket      *socket;
2411   GIOCondition  condition;
2412   GCancellable *cancellable;
2413   GPollFD       cancel_pollfd;
2414   GTimeSpec     timeout_time;
2415 } GSocketSource;
2416
2417 static gboolean
2418 socket_source_prepare (GSource *source,
2419                        gint    *timeout)
2420 {
2421   GSocketSource *socket_source = (GSocketSource *)source;
2422
2423   if (g_cancellable_is_cancelled (socket_source->cancellable))
2424     return TRUE;
2425
2426   if (socket_source->timeout_time.tv_sec)
2427     {
2428       GTimeSpec now;
2429
2430       g_source_get_time (source, &now);
2431       *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2432                   (socket_source->timeout_time.tv_nsec - now.tv_nsec) / 1000000);
2433       if (*timeout < 0)
2434         {
2435           socket_source->socket->priv->timed_out = TRUE;
2436           socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2437           return TRUE;
2438         }
2439     }
2440   else
2441     *timeout = -1;
2442
2443 #ifdef G_OS_WIN32
2444   socket_source->pollfd.revents = update_condition (socket_source->socket);
2445 #endif
2446
2447   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2448     return TRUE;
2449
2450   return FALSE;
2451 }
2452
2453 static gboolean
2454 socket_source_check (GSource *source)
2455 {
2456   int timeout;
2457
2458   return socket_source_prepare (source, &timeout);
2459 }
2460
2461 static gboolean
2462 socket_source_dispatch (GSource     *source,
2463                         GSourceFunc  callback,
2464                         gpointer     user_data)
2465 {
2466   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2467   GSocketSource *socket_source = (GSocketSource *)source;
2468
2469   return (*func) (socket_source->socket,
2470                   socket_source->pollfd.revents & socket_source->condition,
2471                   user_data);
2472 }
2473
2474 static void
2475 socket_source_finalize (GSource *source)
2476 {
2477   GSocketSource *socket_source = (GSocketSource *)source;
2478   GSocket *socket;
2479
2480   socket = socket_source->socket;
2481
2482 #ifdef G_OS_WIN32
2483   remove_condition_watch (socket, &socket_source->condition);
2484 #endif
2485
2486   g_object_unref (socket);
2487
2488   if (socket_source->cancellable)
2489     {
2490       g_cancellable_release_fd (socket_source->cancellable);
2491       g_object_unref (socket_source->cancellable);
2492     }
2493 }
2494
2495 static GSourceFuncs socket_source_funcs =
2496 {
2497   socket_source_prepare,
2498   socket_source_check,
2499   socket_source_dispatch,
2500   socket_source_finalize
2501 };
2502
2503 static GSource *
2504 socket_source_new (GSocket      *socket,
2505                    GIOCondition  condition,
2506                    GCancellable *cancellable)
2507 {
2508   GSource *source;
2509   GSocketSource *socket_source;
2510
2511 #ifdef G_OS_WIN32
2512   ensure_event (socket);
2513
2514   if (socket->priv->event == WSA_INVALID_EVENT)
2515     {
2516       g_warning ("Failed to create WSAEvent");
2517       return g_source_new (&broken_funcs, sizeof (GSource));
2518     }
2519 #endif
2520
2521   condition |= G_IO_HUP | G_IO_ERR;
2522
2523   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2524   g_source_set_name (source, "GSocket");
2525   socket_source = (GSocketSource *)source;
2526
2527   socket_source->socket = g_object_ref (socket);
2528   socket_source->condition = condition;
2529
2530   if (g_cancellable_make_pollfd (cancellable,
2531                                  &socket_source->cancel_pollfd))
2532     {
2533       socket_source->cancellable = g_object_ref (cancellable);
2534       g_source_add_poll (source, &socket_source->cancel_pollfd);
2535     }
2536
2537 #ifdef G_OS_WIN32
2538   add_condition_watch (socket, &socket_source->condition);
2539   socket_source->pollfd.fd = (gintptr) socket->priv->event;
2540 #else
2541   socket_source->pollfd.fd = socket->priv->fd;
2542 #endif
2543
2544   socket_source->pollfd.events = condition;
2545   socket_source->pollfd.revents = 0;
2546   g_source_add_poll (source, &socket_source->pollfd);
2547
2548   if (socket->priv->timeout)
2549     {
2550       g_get_monotonic_time (&socket_source->timeout_time);
2551       socket_source->timeout_time.tv_sec += socket->priv->timeout;
2552     }
2553   else
2554     {
2555       socket_source->timeout_time.tv_sec = 0;
2556       socket_source->timeout_time.tv_nsec = 0;
2557     }
2558
2559   return source;
2560 }
2561
2562 /**
2563  * g_socket_create_source:
2564  * @socket: a #GSocket
2565  * @condition: a #GIOCondition mask to monitor
2566  * @cancellable: a %GCancellable or %NULL
2567  *
2568  * Creates a %GSource that can be attached to a %GMainContext to monitor
2569  * for the availibility of the specified @condition on the socket.
2570  *
2571  * The callback on the source is of the #GSocketSourceFunc type.
2572  *
2573  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2574  * these conditions will always be reported output if they are true.
2575  *
2576  * @cancellable if not %NULL can be used to cancel the source, which will
2577  * cause the source to trigger, reporting the current condition (which
2578  * is likely 0 unless cancellation happened at the same time as a
2579  * condition change). You can check for this in the callback using
2580  * g_cancellable_is_cancelled().
2581  *
2582  * If @socket has a timeout set, and it is reached before @condition
2583  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2584  * %G_IO_OUT depending on @condition. However, @socket will have been
2585  * marked as having had a timeout, and so the next #GSocket I/O method
2586  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2587  *
2588  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2589  *
2590  * Since: 2.22
2591  */
2592 GSource *
2593 g_socket_create_source (GSocket      *socket,
2594                         GIOCondition  condition,
2595                         GCancellable *cancellable)
2596 {
2597   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2598
2599   return socket_source_new (socket, condition, cancellable);
2600 }
2601
2602 /**
2603  * g_socket_condition_check:
2604  * @socket: a #GSocket
2605  * @condition: a #GIOCondition mask to check
2606  *
2607  * Checks on the readiness of @socket to perform operations.
2608  * The operations specified in @condition are checked for and masked
2609  * against the currently-satisfied conditions on @socket. The result
2610  * is returned.
2611  *
2612  * Note that on Windows, it is possible for an operation to return
2613  * %G_IO_ERROR_WOULD_BLOCK even immediately after
2614  * g_socket_condition_check() has claimed that the socket is ready for
2615  * writing. Rather than calling g_socket_condition_check() and then
2616  * writing to the socket if it succeeds, it is generally better to
2617  * simply try writing to the socket right away, and try again later if
2618  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2619  *
2620  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2621  * these conditions will always be set in the output if they are true.
2622  *
2623  * This call never blocks.
2624  *
2625  * Returns: the @GIOCondition mask of the current state
2626  *
2627  * Since: 2.22
2628  */
2629 GIOCondition
2630 g_socket_condition_check (GSocket      *socket,
2631                           GIOCondition  condition)
2632 {
2633   if (!check_socket (socket, NULL))
2634     return 0;
2635
2636 #ifdef G_OS_WIN32
2637   {
2638     GIOCondition current_condition;
2639
2640     condition |= G_IO_ERR | G_IO_HUP;
2641
2642     add_condition_watch (socket, &condition);
2643     current_condition = update_condition (socket);
2644     remove_condition_watch (socket, &condition);
2645     return condition & current_condition;
2646   }
2647 #else
2648   {
2649     GPollFD poll_fd;
2650     gint result;
2651     poll_fd.fd = socket->priv->fd;
2652     poll_fd.events = condition;
2653
2654     do
2655       result = g_poll (&poll_fd, 1, 0);
2656     while (result == -1 && get_socket_errno () == EINTR);
2657
2658     return poll_fd.revents;
2659   }
2660 #endif
2661 }
2662
2663 /**
2664  * g_socket_condition_wait:
2665  * @socket: a #GSocket
2666  * @condition: a #GIOCondition mask to wait for
2667  * @cancellable: a #GCancellable, or %NULL
2668  * @error: a #GError pointer, or %NULL
2669  *
2670  * Waits for @condition to become true on @socket. When the condition
2671  * is met, %TRUE is returned.
2672  *
2673  * If @cancellable is cancelled before the condition is met, or if the
2674  * socket has a timeout set and it is reached before the condition is
2675  * met, then %FALSE is returned and @error, if non-%NULL, is set to
2676  * the appropriate value (%G_IO_ERROR_CANCELLED or
2677  * %G_IO_ERROR_TIMED_OUT).
2678  *
2679  * Returns: %TRUE if the condition was met, %FALSE otherwise
2680  *
2681  * Since: 2.22
2682  */
2683 gboolean
2684 g_socket_condition_wait (GSocket       *socket,
2685                          GIOCondition   condition,
2686                          GCancellable  *cancellable,
2687                          GError       **error)
2688 {
2689   if (!check_socket (socket, error))
2690     return FALSE;
2691
2692   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2693     return FALSE;
2694
2695 #ifdef G_OS_WIN32
2696   {
2697     GIOCondition current_condition;
2698     WSAEVENT events[2];
2699     DWORD res, timeout;
2700     GPollFD cancel_fd;
2701     int num_events;
2702
2703     /* Always check these */
2704     condition |=  G_IO_ERR | G_IO_HUP;
2705
2706     add_condition_watch (socket, &condition);
2707
2708     num_events = 0;
2709     events[num_events++] = socket->priv->event;
2710
2711     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2712       events[num_events++] = (WSAEVENT)cancel_fd.fd;
2713
2714     if (socket->priv->timeout)
2715       timeout = socket->priv->timeout * 1000;
2716     else
2717       timeout = WSA_INFINITE;
2718
2719     current_condition = update_condition (socket);
2720     while ((condition & current_condition) == 0)
2721       {
2722         res = WSAWaitForMultipleEvents(num_events, events,
2723                                        FALSE, timeout, FALSE);
2724         if (res == WSA_WAIT_FAILED)
2725           {
2726             int errsv = get_socket_errno ();
2727
2728             g_set_error (error, G_IO_ERROR,
2729                          socket_io_error_from_errno (errsv),
2730                          _("Waiting for socket condition: %s"),
2731                          socket_strerror (errsv));
2732             break;
2733           }
2734         else if (res == WSA_WAIT_TIMEOUT)
2735           {
2736             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2737                                  _("Socket I/O timed out"));
2738             break;
2739           }
2740
2741         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2742           break;
2743
2744         current_condition = update_condition (socket);
2745       }
2746     remove_condition_watch (socket, &condition);
2747     if (num_events > 1)
2748       g_cancellable_release_fd (cancellable);
2749
2750     return (condition & current_condition) != 0;
2751   }
2752 #else
2753   {
2754     GPollFD poll_fd[2];
2755     gint result;
2756     gint num;
2757     gint timeout;
2758
2759     poll_fd[0].fd = socket->priv->fd;
2760     poll_fd[0].events = condition;
2761     num = 1;
2762
2763     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2764       num++;
2765
2766     if (socket->priv->timeout)
2767       timeout = socket->priv->timeout * 1000;
2768     else
2769       timeout = -1;
2770
2771     do
2772       result = g_poll (poll_fd, num, timeout);
2773     while (result == -1 && get_socket_errno () == EINTR);
2774     
2775     if (num > 1)
2776       g_cancellable_release_fd (cancellable);
2777
2778     if (result == 0)
2779       {
2780         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2781                              _("Socket I/O timed out"));
2782         return FALSE;
2783       }
2784
2785     return !g_cancellable_set_error_if_cancelled (cancellable, error);
2786   }
2787   #endif
2788 }
2789
2790 /**
2791  * g_socket_send_message:
2792  * @socket: a #GSocket
2793  * @address: a #GSocketAddress, or %NULL
2794  * @vectors: an array of #GOutputVector structs
2795  * @num_vectors: the number of elements in @vectors, or -1
2796  * @messages: a pointer to an array of #GSocketControlMessages, or
2797  *   %NULL.
2798  * @num_messages: number of elements in @messages, or -1.
2799  * @flags: an int containing #GSocketMsgFlags flags
2800  * @cancellable: a %GCancellable or %NULL
2801  * @error: #GError for error reporting, or %NULL to ignore.
2802  *
2803  * Send data to @address on @socket.  This is the most complicated and
2804  * fully-featured version of this call. For easier use, see
2805  * g_socket_send() and g_socket_send_to().
2806  *
2807  * If @address is %NULL then the message is sent to the default receiver
2808  * (set by g_socket_connect()).
2809  *
2810  * @vectors must point to an array of #GOutputVector structs and
2811  * @num_vectors must be the length of this array. (If @num_vectors is -1,
2812  * then @vectors is assumed to be terminated by a #GOutputVector with a
2813  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2814  * that the sent data will be gathered from. Using multiple
2815  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2816  * data from multiple sources into a single buffer, and more
2817  * network-efficient than making multiple calls to g_socket_send().
2818  *
2819  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2820  * #GSocketControlMessage instances. These correspond to the control
2821  * messages to be sent on the socket.
2822  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2823  * array.
2824  *
2825  * @flags modify how the message is sent. The commonly available arguments
2826  * for this are available in the #GSocketMsgFlags enum, but the
2827  * values there are the same as the system values, and the flags
2828  * are passed in as-is, so you can pass in system-specific flags too.
2829  *
2830  * If the socket is in blocking mode the call will block until there is
2831  * space for the data in the socket queue. If there is no space available
2832  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2833  * will be returned. To be notified when space is available, wait for the
2834  * %G_IO_OUT condition. Note though that you may still receive
2835  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2836  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2837  * very common due to the way the underlying APIs work.)
2838  *
2839  * On error -1 is returned and @error is set accordingly.
2840  *
2841  * Returns: Number of bytes written (which may be less than @size), or -1
2842  * on error
2843  *
2844  * Since: 2.22
2845  */
2846 gssize
2847 g_socket_send_message (GSocket                *socket,
2848                        GSocketAddress         *address,
2849                        GOutputVector          *vectors,
2850                        gint                    num_vectors,
2851                        GSocketControlMessage **messages,
2852                        gint                    num_messages,
2853                        gint                    flags,
2854                        GCancellable           *cancellable,
2855                        GError                **error)
2856 {
2857   GOutputVector one_vector;
2858   char zero;
2859
2860   if (!check_socket (socket, error))
2861     return -1;
2862
2863   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2864     return -1;
2865
2866   if (num_vectors == -1)
2867     {
2868       for (num_vectors = 0;
2869            vectors[num_vectors].buffer != NULL;
2870            num_vectors++)
2871         ;
2872     }
2873
2874   if (num_messages == -1)
2875     {
2876       for (num_messages = 0;
2877            messages != NULL && messages[num_messages] != NULL;
2878            num_messages++)
2879         ;
2880     }
2881
2882   if (num_vectors == 0)
2883     {
2884       zero = '\0';
2885
2886       one_vector.buffer = &zero;
2887       one_vector.size = 1;
2888       num_vectors = 1;
2889       vectors = &one_vector;
2890     }
2891
2892 #ifndef G_OS_WIN32
2893   {
2894     struct msghdr msg;
2895     gssize result;
2896
2897    msg.msg_flags = 0;
2898
2899     /* name */
2900     if (address)
2901       {
2902         msg.msg_namelen = g_socket_address_get_native_size (address);
2903         msg.msg_name = g_alloca (msg.msg_namelen);
2904         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2905           return -1;
2906       }
2907     else
2908       {
2909         msg.msg_name = NULL;
2910         msg.msg_namelen = 0;
2911       }
2912
2913     /* iov */
2914     {
2915       /* this entire expression will be evaluated at compile time */
2916       if (sizeof *msg.msg_iov == sizeof *vectors &&
2917           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2918           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2919           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2920           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2921           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2922           G_STRUCT_OFFSET (GOutputVector, size))
2923         /* ABI is compatible */
2924         {
2925           msg.msg_iov = (struct iovec *) vectors;
2926           msg.msg_iovlen = num_vectors;
2927         }
2928       else
2929         /* ABI is incompatible */
2930         {
2931           gint i;
2932
2933           msg.msg_iov = g_newa (struct iovec, num_vectors);
2934           for (i = 0; i < num_vectors; i++)
2935             {
2936               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2937               msg.msg_iov[i].iov_len = vectors[i].size;
2938             }
2939           msg.msg_iovlen = num_vectors;
2940         }
2941     }
2942
2943     /* control */
2944     {
2945       struct cmsghdr *cmsg;
2946       gint i;
2947
2948       msg.msg_controllen = 0;
2949       for (i = 0; i < num_messages; i++)
2950         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2951
2952       if (msg.msg_controllen == 0)
2953         msg.msg_control = NULL;
2954       else
2955         {
2956           msg.msg_control = g_alloca (msg.msg_controllen);
2957           memset (msg.msg_control, '\0', msg.msg_controllen);
2958         }
2959
2960       cmsg = CMSG_FIRSTHDR (&msg);
2961       for (i = 0; i < num_messages; i++)
2962         {
2963           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2964           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2965           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2966           g_socket_control_message_serialize (messages[i],
2967                                               CMSG_DATA (cmsg));
2968           cmsg = CMSG_NXTHDR (&msg, cmsg);
2969         }
2970       g_assert (cmsg == NULL);
2971     }
2972
2973     while (1)
2974       {
2975         if (socket->priv->blocking &&
2976             !g_socket_condition_wait (socket,
2977                                       G_IO_OUT, cancellable, error))
2978           return -1;
2979
2980         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2981         if (result < 0)
2982           {
2983             int errsv = get_socket_errno ();
2984
2985             if (errsv == EINTR)
2986               continue;
2987
2988             if (socket->priv->blocking &&
2989                 (errsv == EWOULDBLOCK ||
2990                  errsv == EAGAIN))
2991               continue;
2992
2993             g_set_error (error, G_IO_ERROR,
2994                          socket_io_error_from_errno (errsv),
2995                          _("Error sending message: %s"), socket_strerror (errsv));
2996
2997             return -1;
2998           }
2999         break;
3000       }
3001
3002     return result;
3003   }
3004 #else
3005   {
3006     struct sockaddr_storage addr;
3007     guint addrlen;
3008     DWORD bytes_sent;
3009     int result;
3010     WSABUF *bufs;
3011     gint i;
3012
3013     /* Win32 doesn't support control messages.
3014        Actually this is possible for raw and datagram sockets
3015        via WSASendMessage on Vista or later, but that doesn't
3016        seem very useful */
3017     if (num_messages != 0)
3018       {
3019         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3020                              _("GSocketControlMessage not supported on windows"));
3021         return -1;
3022       }
3023
3024     /* iov */
3025     bufs = g_newa (WSABUF, num_vectors);
3026     for (i = 0; i < num_vectors; i++)
3027       {
3028         bufs[i].buf = (char *)vectors[i].buffer;
3029         bufs[i].len = (gulong)vectors[i].size;
3030       }
3031
3032     /* name */
3033     addrlen = 0; /* Avoid warning */
3034     if (address)
3035       {
3036         addrlen = g_socket_address_get_native_size (address);
3037         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3038           return -1;
3039       }
3040
3041     while (1)
3042       {
3043         if (socket->priv->blocking &&
3044             !g_socket_condition_wait (socket,
3045                                       G_IO_OUT, cancellable, error))
3046           return -1;
3047
3048         if (address)
3049           result = WSASendTo (socket->priv->fd,
3050                               bufs, num_vectors,
3051                               &bytes_sent, flags,
3052                               (const struct sockaddr *)&addr, addrlen,
3053                               NULL, NULL);
3054         else
3055           result = WSASend (socket->priv->fd,
3056                             bufs, num_vectors,
3057                             &bytes_sent, flags,
3058                             NULL, NULL);
3059
3060         if (result != 0)
3061           {
3062             int errsv = get_socket_errno ();
3063
3064             if (errsv == WSAEINTR)
3065               continue;
3066
3067             if (errsv == WSAEWOULDBLOCK)
3068               win32_unset_event_mask (socket, FD_WRITE);
3069
3070             if (socket->priv->blocking &&
3071                 errsv == WSAEWOULDBLOCK)
3072               continue;
3073
3074             g_set_error (error, G_IO_ERROR,
3075                          socket_io_error_from_errno (errsv),
3076                          _("Error sending message: %s"), socket_strerror (errsv));
3077
3078             return -1;
3079           }
3080         break;
3081       }
3082
3083     return bytes_sent;
3084   }
3085 #endif
3086 }
3087
3088 /**
3089  * g_socket_receive_message:
3090  * @socket: a #GSocket
3091  * @address: a pointer to a #GSocketAddress pointer, or %NULL
3092  * @vectors: an array of #GInputVector structs
3093  * @num_vectors: the number of elements in @vectors, or -1
3094  * @messages: a pointer which may be filled with an array of
3095  *     #GSocketControlMessages, or %NULL
3096  * @num_messages: a pointer which will be filled with the number of
3097  *    elements in @messages, or %NULL
3098  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3099  * @cancellable: a %GCancellable or %NULL
3100  * @error: a #GError pointer, or %NULL
3101  *
3102  * Receive data from a socket.  This is the most complicated and
3103  * fully-featured version of this call. For easier use, see
3104  * g_socket_receive() and g_socket_receive_from().
3105  *
3106  * If @address is non-%NULL then @address will be set equal to the
3107  * source address of the received packet.
3108  * @address is owned by the caller.
3109  *
3110  * @vector must point to an array of #GInputVector structs and
3111  * @num_vectors must be the length of this array.  These structs
3112  * describe the buffers that received data will be scattered into.
3113  * If @num_vectors is -1, then @vectors is assumed to be terminated
3114  * by a #GInputVector with a %NULL buffer pointer.
3115  *
3116  * As a special case, if @num_vectors is 0 (in which case, @vectors
3117  * may of course be %NULL), then a single byte is received and
3118  * discarded. This is to facilitate the common practice of sending a
3119  * single '\0' byte for the purposes of transferring ancillary data.
3120  *
3121  * @messages, if non-%NULL, will be set to point to a newly-allocated
3122  * array of #GSocketControlMessage instances or %NULL if no such
3123  * messages was received. These correspond to the control messages
3124  * received from the kernel, one #GSocketControlMessage per message
3125  * from the kernel. This array is %NULL-terminated and must be freed
3126  * by the caller using g_free() after calling g_object_unref() on each
3127  * element. If @messages is %NULL, any control messages received will
3128  * be discarded.
3129  *
3130  * @num_messages, if non-%NULL, will be set to the number of control
3131  * messages received.
3132  *
3133  * If both @messages and @num_messages are non-%NULL, then
3134  * @num_messages gives the number of #GSocketControlMessage instances
3135  * in @messages (ie: not including the %NULL terminator).
3136  *
3137  * @flags is an in/out parameter. The commonly available arguments
3138  * for this are available in the #GSocketMsgFlags enum, but the
3139  * values there are the same as the system values, and the flags
3140  * are passed in as-is, so you can pass in system-specific flags too
3141  * (and g_socket_receive_message() may pass system-specific flags out).
3142  *
3143  * As with g_socket_receive(), data may be discarded if @socket is
3144  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3145  * provide enough buffer space to read a complete message. You can pass
3146  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3147  * removing it from the receive queue, but there is no portable way to find
3148  * out the length of the message other than by reading it into a
3149  * sufficiently-large buffer.
3150  *
3151  * If the socket is in blocking mode the call will block until there
3152  * is some data to receive or there is an error. If there is no data
3153  * available and the socket is in non-blocking mode, a
3154  * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3155  * data is available, wait for the %G_IO_IN condition.
3156  *
3157  * On error -1 is returned and @error is set accordingly.
3158  *
3159  * Returns: Number of bytes read, or -1 on error
3160  *
3161  * Since: 2.22
3162  */
3163 gssize
3164 g_socket_receive_message (GSocket                 *socket,
3165                           GSocketAddress         **address,
3166                           GInputVector            *vectors,
3167                           gint                     num_vectors,
3168                           GSocketControlMessage ***messages,
3169                           gint                    *num_messages,
3170                           gint                    *flags,
3171                           GCancellable            *cancellable,
3172                           GError                 **error)
3173 {
3174   GInputVector one_vector;
3175   char one_byte;
3176
3177   if (!check_socket (socket, error))
3178     return -1;
3179
3180   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3181     return -1;
3182
3183   if (num_vectors == -1)
3184     {
3185       for (num_vectors = 0;
3186            vectors[num_vectors].buffer != NULL;
3187            num_vectors++)
3188         ;
3189     }
3190
3191   if (num_vectors == 0)
3192     {
3193       one_vector.buffer = &one_byte;
3194       one_vector.size = 1;
3195       num_vectors = 1;
3196       vectors = &one_vector;
3197     }
3198
3199 #ifndef G_OS_WIN32
3200   {
3201     struct msghdr msg;
3202     gssize result;
3203     struct sockaddr_storage one_sockaddr;
3204
3205     /* name */
3206     if (address)
3207       {
3208         msg.msg_name = &one_sockaddr;
3209         msg.msg_namelen = sizeof (struct sockaddr_storage);
3210       }
3211     else
3212       {
3213         msg.msg_name = NULL;
3214         msg.msg_namelen = 0;
3215       }
3216
3217     /* iov */
3218     /* this entire expression will be evaluated at compile time */
3219     if (sizeof *msg.msg_iov == sizeof *vectors &&
3220         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3221         G_STRUCT_OFFSET (struct iovec, iov_base) ==
3222         G_STRUCT_OFFSET (GInputVector, buffer) &&
3223         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3224         G_STRUCT_OFFSET (struct iovec, iov_len) ==
3225         G_STRUCT_OFFSET (GInputVector, size))
3226       /* ABI is compatible */
3227       {
3228         msg.msg_iov = (struct iovec *) vectors;
3229         msg.msg_iovlen = num_vectors;
3230       }
3231     else
3232       /* ABI is incompatible */
3233       {
3234         gint i;
3235
3236         msg.msg_iov = g_newa (struct iovec, num_vectors);
3237         for (i = 0; i < num_vectors; i++)
3238           {
3239             msg.msg_iov[i].iov_base = vectors[i].buffer;
3240             msg.msg_iov[i].iov_len = vectors[i].size;
3241           }
3242         msg.msg_iovlen = num_vectors;
3243       }
3244
3245     /* control */
3246     msg.msg_control = g_alloca (2048);
3247     msg.msg_controllen = 2048;
3248
3249     /* flags */
3250     if (flags != NULL)
3251       msg.msg_flags = *flags;
3252     else
3253       msg.msg_flags = 0;
3254
3255     /* do it */
3256     while (1)
3257       {
3258         if (socket->priv->blocking &&
3259             !g_socket_condition_wait (socket,
3260                                       G_IO_IN, cancellable, error))
3261           return -1;
3262
3263         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3264
3265         if (result < 0)
3266           {
3267             int errsv = get_socket_errno ();
3268
3269             if (errsv == EINTR)
3270               continue;
3271
3272             if (socket->priv->blocking &&
3273                 (errsv == EWOULDBLOCK ||
3274                  errsv == EAGAIN))
3275               continue;
3276
3277             g_set_error (error, G_IO_ERROR,
3278                          socket_io_error_from_errno (errsv),
3279                          _("Error receiving message: %s"), socket_strerror (errsv));
3280
3281             return -1;
3282           }
3283         break;
3284       }
3285
3286     /* decode address */
3287     if (address != NULL)
3288       {
3289         if (msg.msg_namelen > 0)
3290           *address = g_socket_address_new_from_native (msg.msg_name,
3291                                                        msg.msg_namelen);
3292         else
3293           *address = NULL;
3294       }
3295
3296     /* decode control messages */
3297     {
3298       GPtrArray *my_messages = NULL;
3299       const gchar *scm_pointer;
3300       struct cmsghdr *cmsg;
3301       gsize scm_size;
3302
3303       scm_pointer = (const gchar *) msg.msg_control;
3304       scm_size = msg.msg_controllen;
3305
3306       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3307         {
3308           GSocketControlMessage *message;
3309
3310           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3311                                                           cmsg->cmsg_type,
3312                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3313                                                           CMSG_DATA (cmsg));
3314           if (message == NULL)
3315             /* We've already spewed about the problem in the
3316                deserialization code, so just continue */
3317             continue;
3318
3319           if (messages == NULL)
3320             {
3321               /* we have to do it this way if the user ignores the
3322                * messages so that we will close any received fds.
3323                */
3324               g_object_unref (message);
3325             }
3326           else
3327             {
3328               if (my_messages == NULL)
3329                 my_messages = g_ptr_array_new ();
3330               g_ptr_array_add (my_messages, message);
3331             }
3332         }
3333
3334       if (num_messages)
3335         *num_messages = my_messages != NULL ? my_messages->len : 0;
3336
3337       if (messages)
3338         {
3339           if (my_messages == NULL)
3340             {
3341               *messages = NULL;
3342             }
3343           else
3344             {
3345               g_ptr_array_add (my_messages, NULL);
3346               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3347             }
3348         }
3349       else
3350         {
3351           g_assert (my_messages == NULL);
3352         }
3353     }
3354
3355     /* capture the flags */
3356     if (flags != NULL)
3357       *flags = msg.msg_flags;
3358
3359     return result;
3360   }
3361 #else
3362   {
3363     struct sockaddr_storage addr;
3364     int addrlen;
3365     DWORD bytes_received;
3366     DWORD win_flags;
3367     int result;
3368     WSABUF *bufs;
3369     gint i;
3370
3371     /* iov */
3372     bufs = g_newa (WSABUF, num_vectors);
3373     for (i = 0; i < num_vectors; i++)
3374       {
3375         bufs[i].buf = (char *)vectors[i].buffer;
3376         bufs[i].len = (gulong)vectors[i].size;
3377       }
3378
3379     /* flags */
3380     if (flags != NULL)
3381       win_flags = *flags;
3382     else
3383       win_flags = 0;
3384
3385     /* do it */
3386     while (1)
3387       {
3388         if (socket->priv->blocking &&
3389             !g_socket_condition_wait (socket,
3390                                       G_IO_IN, cancellable, error))
3391           return -1;
3392
3393         addrlen = sizeof addr;
3394         if (address)
3395           result = WSARecvFrom (socket->priv->fd,
3396                                 bufs, num_vectors,
3397                                 &bytes_received, &win_flags,
3398                                 (struct sockaddr *)&addr, &addrlen,
3399                                 NULL, NULL);
3400         else
3401           result = WSARecv (socket->priv->fd,
3402                             bufs, num_vectors,
3403                             &bytes_received, &win_flags,
3404                             NULL, NULL);
3405         if (result != 0)
3406           {
3407             int errsv = get_socket_errno ();
3408
3409             if (errsv == WSAEINTR)
3410               continue;
3411
3412             win32_unset_event_mask (socket, FD_READ);
3413
3414             if (socket->priv->blocking &&
3415                 errsv == WSAEWOULDBLOCK)
3416               continue;
3417
3418             g_set_error (error, G_IO_ERROR,
3419                          socket_io_error_from_errno (errsv),
3420                          _("Error receiving message: %s"), socket_strerror (errsv));
3421
3422             return -1;
3423           }
3424         win32_unset_event_mask (socket, FD_READ);
3425         break;
3426       }
3427
3428     /* decode address */
3429     if (address != NULL)
3430       {
3431         if (addrlen > 0)
3432           *address = g_socket_address_new_from_native (&addr, addrlen);
3433         else
3434           *address = NULL;
3435       }
3436
3437     /* capture the flags */
3438     if (flags != NULL)
3439       *flags = win_flags;
3440
3441     if (messages != NULL)
3442       *messages = NULL;
3443     if (num_messages != NULL)
3444       *num_messages = 0;
3445
3446     return bytes_received;
3447   }
3448 #endif
3449 }
3450
3451 /**
3452  * g_socket_get_credentials:
3453  * @socket: a #GSocket.
3454  * @error: #GError for error reporting, or %NULL to ignore.
3455  *
3456  * Returns the credentials of the foreign process connected to this
3457  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3458  * sockets).
3459  *
3460  * If this operation isn't supported on the OS, the method fails with
3461  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3462  * by reading the %SO_PEERCRED option on the underlying socket.
3463  *
3464  * Other ways to obtain credentials from a foreign peer includes the
3465  * #GUnixCredentialsMessage type and
3466  * g_unix_connection_send_credentials() /
3467  * g_unix_connection_receive_credentials() functions.
3468  *
3469  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3470  * that must be freed with g_object_unref().
3471  *
3472  * Since: 2.26
3473  */
3474 GCredentials *
3475 g_socket_get_credentials (GSocket   *socket,
3476                           GError   **error)
3477 {
3478   GCredentials *ret;
3479
3480   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3481   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3482
3483   ret = NULL;
3484
3485 #ifdef __linux__
3486   {
3487     struct ucred native_creds;
3488     socklen_t optlen;
3489     optlen = sizeof (struct ucred);
3490     if (getsockopt (socket->priv->fd,
3491                     SOL_SOCKET,
3492                     SO_PEERCRED,
3493                     (void *)&native_creds,
3494                     &optlen) != 0)
3495       {
3496         int errsv = get_socket_errno ();
3497         g_set_error (error,
3498                      G_IO_ERROR,
3499                      socket_io_error_from_errno (errsv),
3500                      _("Unable to get pending error: %s"),
3501                      socket_strerror (errsv));
3502       }
3503     else
3504       {
3505         ret = g_credentials_new ();
3506         g_credentials_set_native (ret,
3507                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
3508                                   &native_creds);
3509       }
3510   }
3511 #else
3512   g_set_error_literal (error,
3513                        G_IO_ERROR,
3514                        G_IO_ERROR_NOT_SUPPORTED,
3515                        _("g_socket_get_credentials not implemented for this OS"));
3516 #endif
3517
3518   return ret;
3519 }