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