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