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