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