GSocketInput/OutputStream: fix non-blocking 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
30 #include "gsocket.h"
31
32 #include <errno.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <stdlib.h>
36
37 #ifndef G_OS_WIN32
38 # include <fcntl.h>
39 # include <unistd.h>
40 #endif
41
42 #ifdef HAVE_SYS_UIO_H
43 #include <sys/uio.h>
44 #endif
45
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
50 #include "gioerror.h"
51 #include "gioenums.h"
52 #include "gioerror.h"
53 #include "gnetworkingprivate.h"
54 #include "gsocketaddress.h"
55 #include "gsocketcontrolmessage.h"
56 #include "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  * Note that on Windows, it is possible for an operation to return
2493  * %G_IO_ERROR_WOULD_BLOCK even immediately after
2494  * g_socket_condition_check() has claimed that the socket is ready for
2495  * writing. Rather than calling g_socket_condition_check() and then
2496  * writing to the socket if it succeeds, it is generally better to
2497  * simply try writing to the socket right away, and try again later if
2498  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2499  *
2500  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2501  * these conditions will always be set in the output if they are true.
2502  *
2503  * This call never blocks.
2504  *
2505  * Returns: the @GIOCondition mask of the current state
2506  *
2507  * Since: 2.22
2508  */
2509 GIOCondition
2510 g_socket_condition_check (GSocket      *socket,
2511                           GIOCondition  condition)
2512 {
2513   if (!check_socket (socket, NULL))
2514     return 0;
2515
2516 #ifdef G_OS_WIN32
2517   {
2518     GIOCondition current_condition;
2519
2520     condition |= G_IO_ERR | G_IO_HUP;
2521
2522     add_condition_watch (socket, &condition);
2523     current_condition = update_condition (socket);
2524     remove_condition_watch (socket, &condition);
2525     return condition & current_condition;
2526   }
2527 #else
2528   {
2529     GPollFD poll_fd;
2530     gint result;
2531     poll_fd.fd = socket->priv->fd;
2532     poll_fd.events = condition;
2533
2534     do
2535       result = g_poll (&poll_fd, 1, 0);
2536     while (result == -1 && get_socket_errno () == EINTR);
2537
2538     return poll_fd.revents;
2539   }
2540 #endif
2541 }
2542
2543 /**
2544  * g_socket_condition_wait:
2545  * @socket: a #GSocket
2546  * @condition: a #GIOCondition mask to wait for
2547  * @cancellable: a #GCancellable, or %NULL
2548  * @error: a #GError pointer, or %NULL
2549  *
2550  * Waits for @condition to become true on @socket. When the condition
2551  * is met, %TRUE is returned.
2552  *
2553  * If @cancellable is cancelled before the condition is met, or if the
2554  * socket has a timeout set and it is reached before the condition is
2555  * met, then %FALSE is returned and @error, if non-%NULL, is set to
2556  * the appropriate value (%G_IO_ERROR_CANCELLED or
2557  * %G_IO_ERROR_TIMED_OUT).
2558  *
2559  * Returns: %TRUE if the condition was met, %FALSE otherwise
2560  *
2561  * Since: 2.22
2562  */
2563 gboolean
2564 g_socket_condition_wait (GSocket       *socket,
2565                          GIOCondition   condition,
2566                          GCancellable  *cancellable,
2567                          GError       **error)
2568 {
2569   if (!check_socket (socket, error))
2570     return FALSE;
2571
2572   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2573     return FALSE;
2574
2575 #ifdef G_OS_WIN32
2576   {
2577     GIOCondition current_condition;
2578     WSAEVENT events[2];
2579     DWORD res, timeout;
2580     GPollFD cancel_fd;
2581     int num_events;
2582
2583     /* Always check these */
2584     condition |=  G_IO_ERR | G_IO_HUP;
2585
2586     add_condition_watch (socket, &condition);
2587
2588     num_events = 0;
2589     events[num_events++] = socket->priv->event;
2590
2591     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2592       events[num_events++] = (WSAEVENT)cancel_fd.fd;
2593
2594     if (socket->priv->timeout)
2595       timeout = socket->priv->timeout * 1000;
2596     else
2597       timeout = WSA_INFINITE;
2598
2599     current_condition = update_condition (socket);
2600     while ((condition & current_condition) == 0)
2601       {
2602         res = WSAWaitForMultipleEvents(num_events, events,
2603                                        FALSE, timeout, FALSE);
2604         if (res == WSA_WAIT_FAILED)
2605           {
2606             int errsv = get_socket_errno ();
2607
2608             g_set_error (error, G_IO_ERROR,
2609                          socket_io_error_from_errno (errsv),
2610                          _("Waiting for socket condition: %s"),
2611                          socket_strerror (errsv));
2612             break;
2613           }
2614         else if (res == WSA_WAIT_TIMEOUT)
2615           {
2616             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2617                                  _("Socket I/O timed out"));
2618             break;
2619           }
2620
2621         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2622           break;
2623
2624         current_condition = update_condition (socket);
2625       }
2626     remove_condition_watch (socket, &condition);
2627     if (num_events > 1)
2628       g_cancellable_release_fd (cancellable);
2629
2630     return (condition & current_condition) != 0;
2631   }
2632 #else
2633   {
2634     GPollFD poll_fd[2];
2635     gint result;
2636     gint num;
2637     gint timeout;
2638
2639     poll_fd[0].fd = socket->priv->fd;
2640     poll_fd[0].events = condition;
2641     num = 1;
2642
2643     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2644       num++;
2645
2646     if (socket->priv->timeout)
2647       timeout = socket->priv->timeout * 1000;
2648     else
2649       timeout = -1;
2650
2651     do
2652       result = g_poll (poll_fd, num, timeout);
2653     while (result == -1 && get_socket_errno () == EINTR);
2654     
2655     if (num > 1)
2656       g_cancellable_release_fd (cancellable);
2657
2658     if (result == 0)
2659       {
2660         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2661                              _("Socket I/O timed out"));
2662         return FALSE;
2663       }
2664
2665     return !g_cancellable_set_error_if_cancelled (cancellable, error);
2666   }
2667   #endif
2668 }
2669
2670 /**
2671  * g_socket_send_message:
2672  * @socket: a #GSocket
2673  * @address: a #GSocketAddress, or %NULL
2674  * @vectors: an array of #GOutputVector structs
2675  * @num_vectors: the number of elements in @vectors, or -1
2676  * @messages: a pointer to an array of #GSocketControlMessages, or
2677  *   %NULL.
2678  * @num_messages: number of elements in @messages, or -1.
2679  * @flags: an int containing #GSocketMsgFlags flags
2680  * @cancellable: a %GCancellable or %NULL
2681  * @error: #GError for error reporting, or %NULL to ignore.
2682  *
2683  * Send data to @address on @socket.  This is the most complicated and
2684  * fully-featured version of this call. For easier use, see
2685  * g_socket_send() and g_socket_send_to().
2686  *
2687  * If @address is %NULL then the message is sent to the default receiver
2688  * (set by g_socket_connect()).
2689  *
2690  * @vectors must point to an array of #GOutputVector structs and
2691  * @num_vectors must be the length of this array. (If @num_vectors is -1,
2692  * then @vectors is assumed to be terminated by a #GOutputVector with a
2693  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2694  * that the sent data will be gathered from. Using multiple
2695  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2696  * data from multiple sources into a single buffer, and more
2697  * network-efficient than making multiple calls to g_socket_send().
2698  *
2699  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2700  * #GSocketControlMessage instances. These correspond to the control
2701  * messages to be sent on the socket.
2702  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2703  * array.
2704  *
2705  * @flags modify how the message is sent. The commonly available arguments
2706  * for this are available in the #GSocketMsgFlags enum, but the
2707  * values there are the same as the system values, and the flags
2708  * are passed in as-is, so you can pass in system-specific flags too.
2709  *
2710  * If the socket is in blocking mode the call will block until there is
2711  * space for the data in the socket queue. If there is no space available
2712  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2713  * will be returned. To be notified when space is available, wait for the
2714  * %G_IO_OUT condition. Note though that you may still receive
2715  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2716  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2717  * very common due to the way the underlying APIs work.)
2718  *
2719  * On error -1 is returned and @error is set accordingly.
2720  *
2721  * Returns: Number of bytes written (which may be less than @size), or -1
2722  * on error
2723  *
2724  * Since: 2.22
2725  */
2726 gssize
2727 g_socket_send_message (GSocket                *socket,
2728                        GSocketAddress         *address,
2729                        GOutputVector          *vectors,
2730                        gint                    num_vectors,
2731                        GSocketControlMessage **messages,
2732                        gint                    num_messages,
2733                        gint                    flags,
2734                        GCancellable           *cancellable,
2735                        GError                **error)
2736 {
2737   GOutputVector one_vector;
2738   char zero;
2739
2740   if (!check_socket (socket, error))
2741     return -1;
2742
2743   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2744     return -1;
2745
2746   if (num_vectors == -1)
2747     {
2748       for (num_vectors = 0;
2749            vectors[num_vectors].buffer != NULL;
2750            num_vectors++)
2751         ;
2752     }
2753
2754   if (num_messages == -1)
2755     {
2756       for (num_messages = 0;
2757            messages != NULL && messages[num_messages] != NULL;
2758            num_messages++)
2759         ;
2760     }
2761
2762   if (num_vectors == 0)
2763     {
2764       zero = '\0';
2765
2766       one_vector.buffer = &zero;
2767       one_vector.size = 1;
2768       num_vectors = 1;
2769       vectors = &one_vector;
2770     }
2771
2772 #ifndef G_OS_WIN32
2773   {
2774     struct msghdr msg;
2775     gssize result;
2776
2777     /* name */
2778     if (address)
2779       {
2780         msg.msg_namelen = g_socket_address_get_native_size (address);
2781         msg.msg_name = g_alloca (msg.msg_namelen);
2782         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2783           return -1;
2784       }
2785     else
2786       {
2787         msg.msg_name = NULL;
2788         msg.msg_namelen = 0;
2789       }
2790
2791     /* iov */
2792     {
2793       /* this entire expression will be evaluated at compile time */
2794       if (sizeof *msg.msg_iov == sizeof *vectors &&
2795           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2796           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2797           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2798           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2799           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2800           G_STRUCT_OFFSET (GOutputVector, size))
2801         /* ABI is compatible */
2802         {
2803           msg.msg_iov = (struct iovec *) vectors;
2804           msg.msg_iovlen = num_vectors;
2805         }
2806       else
2807         /* ABI is incompatible */
2808         {
2809           gint i;
2810
2811           msg.msg_iov = g_newa (struct iovec, num_vectors);
2812           for (i = 0; i < num_vectors; i++)
2813             {
2814               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2815               msg.msg_iov[i].iov_len = vectors[i].size;
2816             }
2817           msg.msg_iovlen = num_vectors;
2818         }
2819     }
2820
2821     /* control */
2822     {
2823       struct cmsghdr *cmsg;
2824       gint i;
2825
2826       msg.msg_controllen = 0;
2827       for (i = 0; i < num_messages; i++)
2828         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2829
2830       msg.msg_control = g_alloca (msg.msg_controllen);
2831
2832       cmsg = CMSG_FIRSTHDR (&msg);
2833       for (i = 0; i < num_messages; i++)
2834         {
2835           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2836           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2837           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2838           g_socket_control_message_serialize (messages[i],
2839                                               CMSG_DATA (cmsg));
2840           cmsg = CMSG_NXTHDR (&msg, cmsg);
2841         }
2842       g_assert (cmsg == NULL);
2843     }
2844
2845     while (1)
2846       {
2847         if (socket->priv->blocking &&
2848             !g_socket_condition_wait (socket,
2849                                       G_IO_OUT, cancellable, error))
2850           return -1;
2851
2852         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
2853         if (result < 0)
2854           {
2855             int errsv = get_socket_errno ();
2856
2857             if (errsv == EINTR)
2858               continue;
2859
2860             if (socket->priv->blocking &&
2861                 (errsv == EWOULDBLOCK ||
2862                  errsv == EAGAIN))
2863               continue;
2864
2865             g_set_error (error, G_IO_ERROR,
2866                          socket_io_error_from_errno (errsv),
2867                          _("Error sending message: %s"), socket_strerror (errsv));
2868
2869             return -1;
2870           }
2871         break;
2872       }
2873
2874     return result;
2875   }
2876 #else
2877   {
2878     struct sockaddr_storage addr;
2879     guint addrlen;
2880     DWORD bytes_sent;
2881     int result;
2882     WSABUF *bufs;
2883     gint i;
2884
2885     /* Win32 doesn't support control messages.
2886        Actually this is possible for raw and datagram sockets
2887        via WSASendMessage on Vista or later, but that doesn't
2888        seem very useful */
2889     if (num_messages != 0)
2890       {
2891         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2892                              _("GSocketControlMessage not supported on windows"));
2893         return -1;
2894       }
2895
2896     /* iov */
2897     bufs = g_newa (WSABUF, num_vectors);
2898     for (i = 0; i < num_vectors; i++)
2899       {
2900         bufs[i].buf = (char *)vectors[i].buffer;
2901         bufs[i].len = (gulong)vectors[i].size;
2902       }
2903
2904     /* name */
2905     addrlen = 0; /* Avoid warning */
2906     if (address)
2907       {
2908         addrlen = g_socket_address_get_native_size (address);
2909         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
2910           return -1;
2911       }
2912
2913     while (1)
2914       {
2915         if (socket->priv->blocking &&
2916             !g_socket_condition_wait (socket,
2917                                       G_IO_OUT, cancellable, error))
2918           return -1;
2919
2920         if (address)
2921           result = WSASendTo (socket->priv->fd,
2922                               bufs, num_vectors,
2923                               &bytes_sent, flags,
2924                               (const struct sockaddr *)&addr, addrlen,
2925                               NULL, NULL);
2926         else
2927           result = WSASend (socket->priv->fd,
2928                             bufs, num_vectors,
2929                             &bytes_sent, flags,
2930                             NULL, NULL);
2931
2932         if (result != 0)
2933           {
2934             int errsv = get_socket_errno ();
2935
2936             if (errsv == WSAEINTR)
2937               continue;
2938
2939             if (errsv == WSAEWOULDBLOCK)
2940               win32_unset_event_mask (socket, FD_WRITE);
2941
2942             if (socket->priv->blocking &&
2943                 errsv == WSAEWOULDBLOCK)
2944               continue;
2945
2946             g_set_error (error, G_IO_ERROR,
2947                          socket_io_error_from_errno (errsv),
2948                          _("Error sending message: %s"), socket_strerror (errsv));
2949
2950             return -1;
2951           }
2952         break;
2953       }
2954
2955     return bytes_sent;
2956   }
2957 #endif
2958 }
2959
2960 /**
2961  * g_socket_receive_message:
2962  * @socket: a #GSocket
2963  * @address: a pointer to a #GSocketAddress pointer, or %NULL
2964  * @vectors: an array of #GInputVector structs
2965  * @num_vectors: the number of elements in @vectors, or -1
2966  * @messages: a pointer which may be filled with an array of
2967  *     #GSocketControlMessages, or %NULL
2968  * @num_messages: a pointer which will be filled with the number of
2969  *    elements in @messages, or %NULL
2970  * @flags: a pointer to an int containing #GSocketMsgFlags flags
2971  * @cancellable: a %GCancellable or %NULL
2972  * @error: a #GError pointer, or %NULL
2973  *
2974  * Receive data from a socket.  This is the most complicated and
2975  * fully-featured version of this call. For easier use, see
2976  * g_socket_receive() and g_socket_receive_from().
2977  *
2978  * If @address is non-%NULL then @address will be set equal to the
2979  * source address of the received packet.
2980  * @address is owned by the caller.
2981  *
2982  * @vector must point to an array of #GInputVector structs and
2983  * @num_vectors must be the length of this array.  These structs
2984  * describe the buffers that received data will be scattered into.
2985  * If @num_vectors is -1, then @vectors is assumed to be terminated
2986  * by a #GInputVector with a %NULL buffer pointer.
2987  *
2988  * As a special case, if @num_vectors is 0 (in which case, @vectors
2989  * may of course be %NULL), then a single byte is received and
2990  * discarded. This is to facilitate the common practice of sending a
2991  * single '\0' byte for the purposes of transferring ancillary data.
2992  *
2993  * @messages, if non-%NULL, will be set to point to a newly-allocated
2994  * array of #GSocketControlMessage instances or %NULL if no such
2995  * messages was received. These correspond to the control messages
2996  * received from the kernel, one #GSocketControlMessage per message
2997  * from the kernel. This array is %NULL-terminated and must be freed
2998  * by the caller using g_free() after calling g_object_unref() on each
2999  * element. If @messages is %NULL, any control messages received will
3000  * be discarded.
3001  *
3002  * @num_messages, if non-%NULL, will be set to the number of control
3003  * messages received.
3004  *
3005  * If both @messages and @num_messages are non-%NULL, then
3006  * @num_messages gives the number of #GSocketControlMessage instances
3007  * in @messages (ie: not including the %NULL terminator).
3008  *
3009  * @flags is an in/out parameter. The commonly available arguments
3010  * for this are available in the #GSocketMsgFlags enum, but the
3011  * values there are the same as the system values, and the flags
3012  * are passed in as-is, so you can pass in system-specific flags too
3013  * (and g_socket_receive_message() may pass system-specific flags out).
3014  *
3015  * As with g_socket_receive(), data may be discarded if @socket is
3016  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3017  * provide enough buffer space to read a complete message. You can pass
3018  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3019  * removing it from the receive queue, but there is no portable way to find
3020  * out the length of the message other than by reading it into a
3021  * sufficiently-large buffer.
3022  *
3023  * If the socket is in blocking mode the call will block until there
3024  * is some data to receive or there is an error. If there is no data
3025  * available and the socket is in non-blocking mode, a
3026  * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3027  * data is available, wait for the %G_IO_IN condition.
3028  *
3029  * On error -1 is returned and @error is set accordingly.
3030  *
3031  * Returns: Number of bytes read, or -1 on error
3032  *
3033  * Since: 2.22
3034  */
3035 gssize
3036 g_socket_receive_message (GSocket                 *socket,
3037                           GSocketAddress         **address,
3038                           GInputVector            *vectors,
3039                           gint                     num_vectors,
3040                           GSocketControlMessage ***messages,
3041                           gint                    *num_messages,
3042                           gint                    *flags,
3043                           GCancellable            *cancellable,
3044                           GError                 **error)
3045 {
3046   GInputVector one_vector;
3047   char one_byte;
3048
3049   if (!check_socket (socket, error))
3050     return -1;
3051
3052   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3053     return -1;
3054
3055   if (num_vectors == -1)
3056     {
3057       for (num_vectors = 0;
3058            vectors[num_vectors].buffer != NULL;
3059            num_vectors++)
3060         ;
3061     }
3062
3063   if (num_vectors == 0)
3064     {
3065       one_vector.buffer = &one_byte;
3066       one_vector.size = 1;
3067       num_vectors = 1;
3068       vectors = &one_vector;
3069     }
3070
3071 #ifndef G_OS_WIN32
3072   {
3073     struct msghdr msg;
3074     gssize result;
3075     struct sockaddr_storage one_sockaddr;
3076
3077     /* name */
3078     if (address)
3079       {
3080         msg.msg_name = &one_sockaddr;
3081         msg.msg_namelen = sizeof (struct sockaddr_storage);
3082       }
3083     else
3084       {
3085         msg.msg_name = NULL;
3086         msg.msg_namelen = 0;
3087       }
3088
3089     /* iov */
3090     /* this entire expression will be evaluated at compile time */
3091     if (sizeof *msg.msg_iov == sizeof *vectors &&
3092         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3093         G_STRUCT_OFFSET (struct iovec, iov_base) ==
3094         G_STRUCT_OFFSET (GInputVector, buffer) &&
3095         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3096         G_STRUCT_OFFSET (struct iovec, iov_len) ==
3097         G_STRUCT_OFFSET (GInputVector, size))
3098       /* ABI is compatible */
3099       {
3100         msg.msg_iov = (struct iovec *) vectors;
3101         msg.msg_iovlen = num_vectors;
3102       }
3103     else
3104       /* ABI is incompatible */
3105       {
3106         gint i;
3107
3108         msg.msg_iov = g_newa (struct iovec, num_vectors);
3109         for (i = 0; i < num_vectors; i++)
3110           {
3111             msg.msg_iov[i].iov_base = vectors[i].buffer;
3112             msg.msg_iov[i].iov_len = vectors[i].size;
3113           }
3114         msg.msg_iovlen = num_vectors;
3115       }
3116
3117     /* control */
3118     msg.msg_control = g_alloca (2048);
3119     msg.msg_controllen = 2048;
3120
3121     /* flags */
3122     if (flags != NULL)
3123       msg.msg_flags = *flags;
3124     else
3125       msg.msg_flags = 0;
3126
3127     /* do it */
3128     while (1)
3129       {
3130         if (socket->priv->blocking &&
3131             !g_socket_condition_wait (socket,
3132                                       G_IO_IN, cancellable, error))
3133           return -1;
3134
3135         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3136
3137         if (result < 0)
3138           {
3139             int errsv = get_socket_errno ();
3140
3141             if (errsv == EINTR)
3142               continue;
3143
3144             if (socket->priv->blocking &&
3145                 (errsv == EWOULDBLOCK ||
3146                  errsv == EAGAIN))
3147               continue;
3148
3149             g_set_error (error, G_IO_ERROR,
3150                          socket_io_error_from_errno (errsv),
3151                          _("Error receiving message: %s"), socket_strerror (errsv));
3152
3153             return -1;
3154           }
3155         break;
3156       }
3157
3158     /* decode address */
3159     if (address != NULL)
3160       {
3161         if (msg.msg_namelen > 0)
3162           *address = g_socket_address_new_from_native (msg.msg_name,
3163                                                        msg.msg_namelen);
3164         else
3165           *address = NULL;
3166       }
3167
3168     /* decode control messages */
3169     {
3170       GPtrArray *my_messages = NULL;
3171       const gchar *scm_pointer;
3172       struct cmsghdr *cmsg;
3173       gsize scm_size;
3174
3175       scm_pointer = (const gchar *) msg.msg_control;
3176       scm_size = msg.msg_controllen;
3177
3178       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3179         {
3180           GSocketControlMessage *message;
3181
3182           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3183                                                           cmsg->cmsg_type,
3184                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3185                                                           CMSG_DATA (cmsg));
3186           if (message == NULL)
3187             /* We've already spewed about the problem in the
3188                deserialization code, so just continue */
3189             continue;
3190
3191           if (messages == NULL)
3192             {
3193               /* we have to do it this way if the user ignores the
3194                * messages so that we will close any received fds.
3195                */
3196               g_object_unref (message);
3197             }
3198           else
3199             {
3200               if (my_messages == NULL)
3201                 my_messages = g_ptr_array_new ();
3202               g_ptr_array_add (my_messages, message);
3203             }
3204         }
3205
3206       if (num_messages)
3207         *num_messages = my_messages != NULL ? my_messages->len : 0;
3208
3209       if (messages)
3210         {
3211           if (my_messages == NULL)
3212             {
3213               *messages = NULL;
3214             }
3215           else
3216             {
3217               g_ptr_array_add (my_messages, NULL);
3218               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3219             }
3220         }
3221       else
3222         {
3223           g_assert (my_messages == NULL);
3224         }
3225     }
3226
3227     /* capture the flags */
3228     if (flags != NULL)
3229       *flags = msg.msg_flags;
3230
3231     return result;
3232   }
3233 #else
3234   {
3235     struct sockaddr_storage addr;
3236     int addrlen;
3237     DWORD bytes_received;
3238     DWORD win_flags;
3239     int result;
3240     WSABUF *bufs;
3241     gint i;
3242
3243     /* iov */
3244     bufs = g_newa (WSABUF, num_vectors);
3245     for (i = 0; i < num_vectors; i++)
3246       {
3247         bufs[i].buf = (char *)vectors[i].buffer;
3248         bufs[i].len = (gulong)vectors[i].size;
3249       }
3250
3251     /* flags */
3252     if (flags != NULL)
3253       win_flags = *flags;
3254     else
3255       win_flags = 0;
3256
3257     /* do it */
3258     while (1)
3259       {
3260         if (socket->priv->blocking &&
3261             !g_socket_condition_wait (socket,
3262                                       G_IO_IN, cancellable, error))
3263           return -1;
3264
3265         addrlen = sizeof addr;
3266         if (address)
3267           result = WSARecvFrom (socket->priv->fd,
3268                                 bufs, num_vectors,
3269                                 &bytes_received, &win_flags,
3270                                 (struct sockaddr *)&addr, &addrlen,
3271                                 NULL, NULL);
3272         else
3273           result = WSARecv (socket->priv->fd,
3274                             bufs, num_vectors,
3275                             &bytes_received, &win_flags,
3276                             NULL, NULL);
3277         if (result != 0)
3278           {
3279             int errsv = get_socket_errno ();
3280
3281             if (errsv == WSAEINTR)
3282               continue;
3283
3284             win32_unset_event_mask (socket, FD_READ);
3285
3286             if (socket->priv->blocking &&
3287                 errsv == WSAEWOULDBLOCK)
3288               continue;
3289
3290             g_set_error (error, G_IO_ERROR,
3291                          socket_io_error_from_errno (errsv),
3292                          _("Error receiving message: %s"), socket_strerror (errsv));
3293
3294             return -1;
3295           }
3296         win32_unset_event_mask (socket, FD_READ);
3297         break;
3298       }
3299
3300     /* decode address */
3301     if (address != NULL)
3302       {
3303         if (addrlen > 0)
3304           *address = g_socket_address_new_from_native (&addr, addrlen);
3305         else
3306           *address = NULL;
3307       }
3308
3309     /* capture the flags */
3310     if (flags != NULL)
3311       *flags = win_flags;
3312
3313     if (messages != NULL)
3314       *messages = NULL;
3315     if (num_messages != NULL)
3316       *num_messages = 0;
3317
3318     return bytes_received;
3319   }
3320 #endif
3321 }
3322
3323 #define __G_SOCKET_C__
3324 #include "gioaliasdef.c"