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