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