gio/: fully remove gioalias hacks
[platform/upstream/glib.git] / gio / gsocket.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2008 Christian Kellner, Samuel Cormier-Iijima
4  * Copyright © 2009 Codethink Limited
5  * Copyright © 2009 Red Hat, Inc
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Authors: Christian Kellner <gicmo@gnome.org>
23  *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
24  *          Ryan Lortie <desrt@desrt.ca>
25  *          Alexander Larsson <alexl@redhat.com>
26  */
27
28 #include "config.h"
29
30 #include "gsocket.h"
31
32 #include <errno.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <stdlib.h>
36
37 #ifndef G_OS_WIN32
38 # include <fcntl.h>
39 # include <unistd.h>
40 #endif
41
42 #ifdef HAVE_SYS_UIO_H
43 #include <sys/uio.h>
44 #endif
45
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
50 #include "gioerror.h"
51 #include "gioenums.h"
52 #include "gioerror.h"
53 #include "gnetworkingprivate.h"
54 #include "gsocketaddress.h"
55 #include "gsocketcontrolmessage.h"
56 #include "glibintl.h"
57
58
59 /**
60  * SECTION:gsocket
61  * @short_description: Low-level socket object
62  * @include: gio/gio.h
63  * @see_also: #GInitable
64  *
65  * A #GSocket is a low-level networking primitive. It is a more or less
66  * direct mapping of the BSD socket API in a portable GObject based API.
67  * It supports both the UNIX socket implementations and winsock2 on Windows.
68  *
69  * #GSocket is the platform independent base upon which the higher level
70  * network primitives are based. Applications are not typically meant to
71  * use it directly, but rather through classes like #GSocketClient,
72  * #GSocketService and #GSocketConnection. However there may be cases where
73  * direct use of #GSocket is useful.
74  *
75  * #GSocket implements the #GInitable interface, so if it is manually constructed
76  * by e.g. g_object_new() you must call g_initable_init() and check the
77  * results before using the object. This is done automatically in
78  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
79  * %NULL.
80  *
81  * Sockets operate in two general modes, blocking or non-blocking. When
82  * in blocking mode all operations block until the requested operation
83  * is finished or there is an error. In non-blocking mode all calls that
84  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
85  * To know when a call would successfully run you can call g_socket_condition_check(),
86  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
87  * attach it to a #GMainContext to get callbacks when I/O is possible.
88  * Note that all sockets are always set to non blocking mode in the system, and
89  * blocking mode is emulated in GSocket.
90  *
91  * When working in non-blocking mode applications should always be able to
92  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
93  * function said that I/O was possible. This can easily happen in case
94  * of a race condition in the application, but it can also happen for other
95  * reasons. For instance, on Windows a socket is always seen as writable
96  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
97  *
98  * #GSocket<!-- -->s can be either connection oriented or datagram based.
99  * For connection oriented types you must first establish a connection by
100  * either connecting to an address or accepting a connection from another
101  * address. For connectionless socket types the target/source address is
102  * specified or received in each I/O operation.
103  *
104  * All socket file descriptors are set to be close-on-exec.
105  *
106  * Note that creating a #GSocket causes the signal %SIGPIPE to be
107  * ignored for the remainder of the program. If you are writing a
108  * command-line utility that uses #GSocket, you may need to take into
109  * account the fact that your program will not automatically be killed
110  * if it tries to write to %stdout after it has been closed.
111  *
112  * Since: 2.22
113  */
114
115 static void     g_socket_initable_iface_init (GInitableIface  *iface);
116 static gboolean g_socket_initable_init       (GInitable       *initable,
117                                               GCancellable    *cancellable,
118                                               GError         **error);
119
120 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
121                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
122                                                 g_socket_initable_iface_init));
123
124 enum
125 {
126   PROP_0,
127   PROP_FAMILY,
128   PROP_TYPE,
129   PROP_PROTOCOL,
130   PROP_FD,
131   PROP_BLOCKING,
132   PROP_LISTEN_BACKLOG,
133   PROP_KEEPALIVE,
134   PROP_LOCAL_ADDRESS,
135   PROP_REMOTE_ADDRESS,
136   PROP_TIMEOUT
137 };
138
139 struct _GSocketPrivate
140 {
141   GSocketFamily   family;
142   GSocketType     type;
143   GSocketProtocol protocol;
144   gint            fd;
145   gint            listen_backlog;
146   guint           timeout;
147   GError         *construct_error;
148   guint           inited : 1;
149   guint           blocking : 1;
150   guint           keepalive : 1;
151   guint           closed : 1;
152   guint           connected : 1;
153   guint           listening : 1;
154   guint           timed_out : 1;
155 #ifdef G_OS_WIN32
156   WSAEVENT        event;
157   int             current_events;
158   int             current_errors;
159   int             selected_events;
160   GList          *requested_conditions; /* list of requested GIOCondition * */
161 #endif
162 };
163
164 static int
165 get_socket_errno (void)
166 {
167 #ifndef G_OS_WIN32
168   return errno;
169 #else
170   return WSAGetLastError ();
171 #endif
172 }
173
174 static GIOErrorEnum
175 socket_io_error_from_errno (int err)
176 {
177 #ifndef G_OS_WIN32
178   return g_io_error_from_errno (err);
179 #else
180   switch (err)
181     {
182     case WSAEADDRINUSE:
183       return G_IO_ERROR_ADDRESS_IN_USE;
184     case WSAEWOULDBLOCK:
185       return G_IO_ERROR_WOULD_BLOCK;
186     case WSAEACCES:
187       return G_IO_ERROR_PERMISSION_DENIED;
188     case WSA_INVALID_HANDLE:
189     case WSA_INVALID_PARAMETER:
190     case WSAEBADF:
191     case WSAENOTSOCK:
192       return G_IO_ERROR_INVALID_ARGUMENT;
193     case WSAEPROTONOSUPPORT:
194       return G_IO_ERROR_NOT_SUPPORTED;
195     case WSAECANCELLED:
196       return G_IO_ERROR_CANCELLED;
197     case WSAESOCKTNOSUPPORT:
198     case WSAEOPNOTSUPP:
199     case WSAEPFNOSUPPORT:
200     case WSAEAFNOSUPPORT:
201       return G_IO_ERROR_NOT_SUPPORTED;
202     default:
203       return G_IO_ERROR_FAILED;
204     }
205 #endif
206 }
207
208 static const char *
209 socket_strerror (int err)
210 {
211 #ifndef G_OS_WIN32
212   return g_strerror (err);
213 #else
214   static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
215   char *msg;
216
217   msg = g_win32_error_message (err);
218   g_static_private_set (&last_msg, msg, g_free);
219
220   return msg;
221 #endif
222 }
223
224 #ifdef G_OS_WIN32
225 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
226 static void
227 _win32_unset_event_mask (GSocket *socket, int mask)
228 {
229   socket->priv->current_events &= ~mask;
230   socket->priv->current_errors &= ~mask;
231 }
232 #else
233 #define win32_unset_event_mask(_socket, _mask)
234 #endif
235
236 static void
237 set_fd_nonblocking (int fd)
238 {
239 #ifndef G_OS_WIN32
240   glong arg;
241 #else
242   gulong arg;
243 #endif
244
245 #ifndef G_OS_WIN32
246   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
247     {
248       g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
249       arg = 0;
250     }
251
252   arg = arg | O_NONBLOCK;
253
254   if (fcntl (fd, F_SETFL, arg) < 0)
255       g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
256 #else
257   arg = TRUE;
258
259   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
260     {
261       int errsv = get_socket_errno ();
262       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
263     }
264 #endif
265 }
266
267 static gboolean
268 check_socket (GSocket *socket,
269               GError **error)
270 {
271   if (!socket->priv->inited)
272     {
273       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
274                            _("Invalid socket, not initialized"));
275       return FALSE;
276     }
277
278   if (socket->priv->construct_error)
279     {
280       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
281                    _("Invalid socket, initialization failed due to: %s"),
282                    socket->priv->construct_error->message);
283       return FALSE;
284     }
285
286   if (socket->priv->closed)
287     {
288       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
289                            _("Socket is already closed"));
290       return FALSE;
291     }
292
293   if (socket->priv->timed_out)
294     {
295       socket->priv->timed_out = FALSE;
296       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
297                            _("Socket I/O timed out"));
298       return FALSE;
299     }
300
301   return TRUE;
302 }
303
304 static void
305 g_socket_details_from_fd (GSocket *socket)
306 {
307   struct sockaddr_storage address;
308   gint fd;
309   guint addrlen;
310   guint optlen;
311   int value;
312   int errsv;
313 #ifdef G_OS_WIN32
314   /* See bug #611756 */
315   BOOL bool_val = FALSE;
316 #else
317   int bool_val;
318 #endif
319
320   fd = socket->priv->fd;
321   optlen = sizeof value;
322   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
323     {
324       errsv = get_socket_errno ();
325
326       switch (errsv)
327         {
328 #ifdef ENOTSOCK
329          case ENOTSOCK:
330 #endif
331 #ifdef WSAENOTSOCK
332          case WSAENOTSOCK:
333 #endif
334          case EBADF:
335           /* programmer error */
336           g_error ("creating GSocket from fd %d: %s\n",
337                    fd, socket_strerror (errsv));
338          default:
339            break;
340         }
341
342       goto err;
343     }
344
345   g_assert (optlen == sizeof value);
346   switch (value)
347     {
348      case SOCK_STREAM:
349       socket->priv->type = G_SOCKET_TYPE_STREAM;
350       break;
351
352      case SOCK_DGRAM:
353       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
354       break;
355
356      case SOCK_SEQPACKET:
357       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
358       break;
359
360      default:
361       socket->priv->type = G_SOCKET_TYPE_INVALID;
362       break;
363     }
364
365   addrlen = sizeof address;
366   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
367     {
368       errsv = get_socket_errno ();
369       goto err;
370     }
371
372   g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
373             sizeof address.ss_family <= addrlen);
374   switch (address.ss_family)
375     {
376      case G_SOCKET_FAMILY_IPV4:
377      case G_SOCKET_FAMILY_IPV6:
378      case G_SOCKET_FAMILY_UNIX:
379       socket->priv->family = address.ss_family;
380       break;
381
382      default:
383       socket->priv->family = G_SOCKET_FAMILY_INVALID;
384       break;
385     }
386
387   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
388     {
389       addrlen = sizeof address;
390       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
391         socket->priv->connected = TRUE;
392     }
393
394   optlen = sizeof bool_val;
395   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
396                   (void *)&bool_val, &optlen) == 0)
397     {
398 #ifndef G_OS_WIN32
399       /* Experimentation indicates that the SO_KEEPALIVE value is
400        * actually a char on Windows, even if documentation claims it
401        * to be a BOOL which is a typedef for int. So this g_assert()
402        * fails. See bug #611756.
403        */
404       g_assert (optlen == sizeof bool_val);
405 #endif
406       socket->priv->keepalive = !!bool_val;
407     }
408   else
409     {
410       /* Can't read, maybe not supported, assume FALSE */
411       socket->priv->keepalive = FALSE;
412     }
413
414   return;
415
416  err:
417   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
418                socket_io_error_from_errno (errsv),
419                _("creating GSocket from fd: %s"),
420                socket_strerror (errsv));
421 }
422
423 static gint
424 g_socket_create_socket (GSocketFamily   family,
425                         GSocketType     type,
426                         int             protocol,
427                         GError        **error)
428 {
429   gint native_type;
430   gint fd;
431
432   switch (type)
433     {
434      case G_SOCKET_TYPE_STREAM:
435       native_type = SOCK_STREAM;
436       break;
437
438      case G_SOCKET_TYPE_DATAGRAM:
439       native_type = SOCK_DGRAM;
440       break;
441
442      case G_SOCKET_TYPE_SEQPACKET:
443       native_type = SOCK_SEQPACKET;
444       break;
445
446      default:
447       g_assert_not_reached ();
448     }
449
450   if (protocol == -1)
451     {
452       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
453                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
454       return -1;
455     }
456
457 #ifdef SOCK_CLOEXEC
458   native_type |= SOCK_CLOEXEC;
459 #endif
460   fd = socket (family, native_type, protocol);
461
462   if (fd < 0)
463     {
464       int errsv = get_socket_errno ();
465
466       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
467                    _("Unable to create socket: %s"), socket_strerror (errsv));
468     }
469
470 #ifndef G_OS_WIN32
471   {
472     int flags;
473
474     /* We always want to set close-on-exec to protect users. If you
475        need to so some weird inheritance to exec you can re-enable this
476        using lower level hacks with g_socket_get_fd(). */
477     flags = fcntl (fd, F_GETFD, 0);
478     if (flags != -1 &&
479         (flags & FD_CLOEXEC) == 0)
480       {
481         flags |= FD_CLOEXEC;
482         fcntl (fd, F_SETFD, flags);
483       }
484   }
485 #endif
486
487   return fd;
488 }
489
490 static void
491 g_socket_constructed (GObject *object)
492 {
493   GSocket *socket = G_SOCKET (object);
494
495   if (socket->priv->fd >= 0)
496     /* create socket->priv info from the fd */
497     g_socket_details_from_fd (socket);
498
499   else
500     /* create the fd from socket->priv info */
501     socket->priv->fd = g_socket_create_socket (socket->priv->family,
502                                                socket->priv->type,
503                                                socket->priv->protocol,
504                                                &socket->priv->construct_error);
505
506   /* Always use native nonblocking sockets, as
507      windows sets sockets to nonblocking automatically
508      in certain operations. This way we make things work
509      the same on all platforms */
510   if (socket->priv->fd != -1)
511     set_fd_nonblocking (socket->priv->fd);
512 }
513
514 static void
515 g_socket_get_property (GObject    *object,
516                        guint       prop_id,
517                        GValue     *value,
518                        GParamSpec *pspec)
519 {
520   GSocket *socket = G_SOCKET (object);
521   GSocketAddress *address;
522
523   switch (prop_id)
524     {
525       case PROP_FAMILY:
526         g_value_set_enum (value, socket->priv->family);
527         break;
528
529       case PROP_TYPE:
530         g_value_set_enum (value, socket->priv->type);
531         break;
532
533       case PROP_PROTOCOL:
534         g_value_set_enum (value, socket->priv->protocol);
535         break;
536
537       case PROP_FD:
538         g_value_set_int (value, socket->priv->fd);
539         break;
540
541       case PROP_BLOCKING:
542         g_value_set_boolean (value, socket->priv->blocking);
543         break;
544
545       case PROP_LISTEN_BACKLOG:
546         g_value_set_int (value, socket->priv->listen_backlog);
547         break;
548
549       case PROP_KEEPALIVE:
550         g_value_set_boolean (value, socket->priv->keepalive);
551         break;
552
553       case PROP_LOCAL_ADDRESS:
554         address = g_socket_get_local_address (socket, NULL);
555         g_value_take_object (value, address);
556         break;
557
558       case PROP_REMOTE_ADDRESS:
559         address = g_socket_get_remote_address (socket, NULL);
560         g_value_take_object (value, address);
561         break;
562
563       case PROP_TIMEOUT:
564         g_value_set_uint (value, socket->priv->timeout);
565         break;
566
567       default:
568         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
569     }
570 }
571
572 static void
573 g_socket_set_property (GObject      *object,
574                        guint         prop_id,
575                        const GValue *value,
576                        GParamSpec   *pspec)
577 {
578   GSocket *socket = G_SOCKET (object);
579
580   switch (prop_id)
581     {
582       case PROP_FAMILY:
583         socket->priv->family = g_value_get_enum (value);
584         break;
585
586       case PROP_TYPE:
587         socket->priv->type = g_value_get_enum (value);
588         break;
589
590       case PROP_PROTOCOL:
591         socket->priv->protocol = g_value_get_enum (value);
592         break;
593
594       case PROP_FD:
595         socket->priv->fd = g_value_get_int (value);
596         break;
597
598       case PROP_BLOCKING:
599         g_socket_set_blocking (socket, g_value_get_boolean (value));
600         break;
601
602       case PROP_LISTEN_BACKLOG:
603         g_socket_set_listen_backlog (socket, g_value_get_int (value));
604         break;
605
606       case PROP_KEEPALIVE:
607         g_socket_set_keepalive (socket, g_value_get_boolean (value));
608         break;
609
610       case PROP_TIMEOUT:
611         g_socket_set_timeout (socket, g_value_get_uint (value));
612         break;
613
614       default:
615         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
616     }
617 }
618
619 static void
620 g_socket_finalize (GObject *object)
621 {
622   GSocket *socket = G_SOCKET (object);
623
624   g_clear_error (&socket->priv->construct_error);
625
626   if (socket->priv->fd != -1 &&
627       !socket->priv->closed)
628     g_socket_close (socket, NULL);
629
630 #ifdef G_OS_WIN32
631   if (socket->priv->event != WSA_INVALID_EVENT)
632     {
633       WSACloseEvent (socket->priv->event);
634       socket->priv->event = WSA_INVALID_EVENT;
635     }
636
637   g_assert (socket->priv->requested_conditions == NULL);
638 #endif
639
640   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
641     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
642 }
643
644 static void
645 g_socket_class_init (GSocketClass *klass)
646 {
647   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
648   volatile GType type;
649
650   /* Make sure winsock has been initialized */
651   type = g_inet_address_get_type ();
652
653 #ifdef SIGPIPE
654   /* There is no portable, thread-safe way to avoid having the process
655    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
656    * forced to simply ignore the signal process-wide.
657    */
658   signal (SIGPIPE, SIG_IGN);
659 #endif
660
661   g_type_class_add_private (klass, sizeof (GSocketPrivate));
662
663   gobject_class->finalize = g_socket_finalize;
664   gobject_class->constructed = g_socket_constructed;
665   gobject_class->set_property = g_socket_set_property;
666   gobject_class->get_property = g_socket_get_property;
667
668   g_object_class_install_property (gobject_class, PROP_FAMILY,
669                                    g_param_spec_enum ("family",
670                                                       P_("Socket family"),
671                                                       P_("The sockets address family"),
672                                                       G_TYPE_SOCKET_FAMILY,
673                                                       G_SOCKET_FAMILY_INVALID,
674                                                       G_PARAM_CONSTRUCT_ONLY |
675                                                       G_PARAM_READWRITE |
676                                                       G_PARAM_STATIC_STRINGS));
677
678   g_object_class_install_property (gobject_class, PROP_TYPE,
679                                    g_param_spec_enum ("type",
680                                                       P_("Socket type"),
681                                                       P_("The sockets type"),
682                                                       G_TYPE_SOCKET_TYPE,
683                                                       G_SOCKET_TYPE_STREAM,
684                                                       G_PARAM_CONSTRUCT_ONLY |
685                                                       G_PARAM_READWRITE |
686                                                       G_PARAM_STATIC_STRINGS));
687
688   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
689                                    g_param_spec_enum ("protocol",
690                                                       P_("Socket protocol"),
691                                                       P_("The id of the protocol to use, or -1 for unknown"),
692                                                       G_TYPE_SOCKET_PROTOCOL,
693                                                       G_SOCKET_PROTOCOL_UNKNOWN,
694                                                       G_PARAM_CONSTRUCT_ONLY |
695                                                       G_PARAM_READWRITE |
696                                                       G_PARAM_STATIC_STRINGS));
697
698   g_object_class_install_property (gobject_class, PROP_FD,
699                                    g_param_spec_int ("fd",
700                                                      P_("File descriptor"),
701                                                      P_("The sockets file descriptor"),
702                                                      G_MININT,
703                                                      G_MAXINT,
704                                                      -1,
705                                                      G_PARAM_CONSTRUCT_ONLY |
706                                                      G_PARAM_READWRITE |
707                                                      G_PARAM_STATIC_STRINGS));
708
709   g_object_class_install_property (gobject_class, PROP_BLOCKING,
710                                    g_param_spec_boolean ("blocking",
711                                                          P_("blocking"),
712                                                          P_("Whether or not I/O on this socket is blocking"),
713                                                          TRUE,
714                                                          G_PARAM_READWRITE |
715                                                          G_PARAM_STATIC_STRINGS));
716
717   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
718                                    g_param_spec_int ("listen-backlog",
719                                                      P_("Listen backlog"),
720                                                      P_("Outstanding connections in the listen queue"),
721                                                      0,
722                                                      SOMAXCONN,
723                                                      10,
724                                                      G_PARAM_READWRITE |
725                                                      G_PARAM_STATIC_STRINGS));
726
727   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
728                                    g_param_spec_boolean ("keepalive",
729                                                          P_("Keep connection alive"),
730                                                          P_("Keep connection alive by sending periodic pings"),
731                                                          FALSE,
732                                                          G_PARAM_READWRITE |
733                                                          G_PARAM_STATIC_STRINGS));
734
735   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
736                                    g_param_spec_object ("local-address",
737                                                         P_("Local address"),
738                                                         P_("The local address the socket is bound to"),
739                                                         G_TYPE_SOCKET_ADDRESS,
740                                                         G_PARAM_READABLE |
741                                                         G_PARAM_STATIC_STRINGS));
742
743   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
744                                    g_param_spec_object ("remote-address",
745                                                         P_("Remote address"),
746                                                         P_("The remote address the socket is connected to"),
747                                                         G_TYPE_SOCKET_ADDRESS,
748                                                         G_PARAM_READABLE |
749                                                         G_PARAM_STATIC_STRINGS));
750
751   /**
752    * GSocket:timeout:
753    *
754    * The timeout in seconds on socket I/O
755    *
756    * Since: 2.26
757    */
758   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
759                                    g_param_spec_uint ("timeout",
760                                                       P_("Timeout"),
761                                                       P_("The timeout in seconds on socket I/O"),
762                                                       0,
763                                                       G_MAXUINT,
764                                                       0,
765                                                       G_PARAM_READWRITE |
766                                                       G_PARAM_STATIC_STRINGS));
767 }
768
769 static void
770 g_socket_initable_iface_init (GInitableIface *iface)
771 {
772   iface->init = g_socket_initable_init;
773 }
774
775 static void
776 g_socket_init (GSocket *socket)
777 {
778   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
779
780   socket->priv->fd = -1;
781   socket->priv->blocking = TRUE;
782   socket->priv->listen_backlog = 10;
783   socket->priv->construct_error = NULL;
784 #ifdef G_OS_WIN32
785   socket->priv->event = WSA_INVALID_EVENT;
786 #endif
787 }
788
789 static gboolean
790 g_socket_initable_init (GInitable *initable,
791                         GCancellable *cancellable,
792                         GError  **error)
793 {
794   GSocket  *socket;
795
796   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
797
798   socket = G_SOCKET (initable);
799
800   if (cancellable != NULL)
801     {
802       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
803                            _("Cancellable initialization not supported"));
804       return FALSE;
805     }
806
807   socket->priv->inited = TRUE;
808
809   if (socket->priv->construct_error)
810     {
811       if (error)
812         *error = g_error_copy (socket->priv->construct_error);
813       return FALSE;
814     }
815
816
817   return TRUE;
818 }
819
820 /**
821  * g_socket_new:
822  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
823  * @type: the socket type to use.
824  * @protocol: the id of the protocol to use, or 0 for default.
825  * @error: #GError for error reporting, or %NULL to ignore.
826  *
827  * Creates a new #GSocket with the defined family, type and protocol.
828  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
829  * for the family and type is used.
830  *
831  * The @protocol is a family and type specific int that specifies what
832  * kind of protocol to use. #GSocketProtocol lists several common ones.
833  * Many families only support one protocol, and use 0 for this, others
834  * support several and using 0 means to use the default protocol for
835  * the family and type.
836  *
837  * The protocol id is passed directly to the operating
838  * system, so you can use protocols not listed in #GSocketProtocol if you
839  * know the protocol number used for it.
840  *
841  * Returns: a #GSocket or %NULL on error.
842  *     Free the returned object with g_object_unref().
843  *
844  * Since: 2.22
845  */
846 GSocket *
847 g_socket_new (GSocketFamily     family,
848               GSocketType       type,
849               GSocketProtocol   protocol,
850               GError          **error)
851 {
852   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
853                                    NULL, error,
854                                    "family", family,
855                                    "type", type,
856                                    "protocol", protocol,
857                                    NULL));
858 }
859
860 /**
861  * g_socket_new_from_fd:
862  * @fd: a native socket file descriptor.
863  * @error: #GError for error reporting, or %NULL to ignore.
864  *
865  * Creates a new #GSocket from a native file descriptor
866  * or winsock SOCKET handle.
867  *
868  * This reads all the settings from the file descriptor so that
869  * all properties should work. Note that the file descriptor
870  * will be set to non-blocking mode, independent on the blocking
871  * mode of the #GSocket.
872  *
873  * Returns: a #GSocket or %NULL on error.
874  *     Free the returned object with g_object_unref().
875  *
876  * Since: 2.22
877  */
878 GSocket *
879 g_socket_new_from_fd (gint     fd,
880                       GError **error)
881 {
882   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
883                                    NULL, error,
884                                    "fd", fd,
885                                    NULL));
886 }
887
888 /**
889  * g_socket_set_blocking:
890  * @socket: a #GSocket.
891  * @blocking: Whether to use blocking I/O or not.
892  *
893  * Sets the blocking mode of the socket. In blocking mode
894  * all operations block until they succeed or there is an error. In
895  * non-blocking mode all functions return results immediately or
896  * with a %G_IO_ERROR_WOULD_BLOCK error.
897  *
898  * All sockets are created in blocking mode. However, note that the
899  * platform level socket is always non-blocking, and blocking mode
900  * is a GSocket level feature.
901  *
902  * Since: 2.22
903  */
904 void
905 g_socket_set_blocking (GSocket  *socket,
906                        gboolean  blocking)
907 {
908   g_return_if_fail (G_IS_SOCKET (socket));
909
910   blocking = !!blocking;
911
912   if (socket->priv->blocking == blocking)
913     return;
914
915   socket->priv->blocking = blocking;
916   g_object_notify (G_OBJECT (socket), "blocking");
917 }
918
919 /**
920  * g_socket_get_blocking:
921  * @socket: a #GSocket.
922  *
923  * Gets the blocking mode of the socket. For details on blocking I/O,
924  * see g_socket_set_blocking().
925  *
926  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
927  *
928  * Since: 2.22
929  */
930 gboolean
931 g_socket_get_blocking (GSocket *socket)
932 {
933   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
934
935   return socket->priv->blocking;
936 }
937
938 /**
939  * g_socket_set_keepalive:
940  * @socket: a #GSocket.
941  * @keepalive: Value for the keepalive flag
942  *
943  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
944  * this flag is set on a socket, the system will attempt to verify that the
945  * remote socket endpoint is still present if a sufficiently long period of
946  * time passes with no data being exchanged. If the system is unable to
947  * verify the presence of the remote endpoint, it will automatically close
948  * the connection.
949  *
950  * This option is only functional on certain kinds of sockets. (Notably,
951  * %G_SOCKET_PROTOCOL_TCP sockets.)
952  *
953  * The exact time between pings is system- and protocol-dependent, but will
954  * normally be at least two hours. Most commonly, you would set this flag
955  * on a server socket if you want to allow clients to remain idle for long
956  * periods of time, but also want to ensure that connections are eventually
957  * garbage-collected if clients crash or become unreachable.
958  *
959  * Since: 2.22
960  */
961 void
962 g_socket_set_keepalive (GSocket  *socket,
963                         gboolean  keepalive)
964 {
965   int value;
966
967   g_return_if_fail (G_IS_SOCKET (socket));
968
969   keepalive = !!keepalive;
970   if (socket->priv->keepalive == keepalive)
971     return;
972
973   value = (gint) keepalive;
974   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
975                   (gpointer) &value, sizeof (value)) < 0)
976     {
977       int errsv = get_socket_errno ();
978       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
979       return;
980     }
981
982   socket->priv->keepalive = keepalive;
983   g_object_notify (G_OBJECT (socket), "keepalive");
984 }
985
986 /**
987  * g_socket_get_keepalive:
988  * @socket: a #GSocket.
989  *
990  * Gets the keepalive mode of the socket. For details on this,
991  * see g_socket_set_keepalive().
992  *
993  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
994  *
995  * Since: 2.22
996  */
997 gboolean
998 g_socket_get_keepalive (GSocket *socket)
999 {
1000   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1001
1002   return socket->priv->keepalive;
1003 }
1004
1005 /**
1006  * g_socket_get_listen_backlog:
1007  * @socket: a #GSocket.
1008  *
1009  * Gets the listen backlog setting of the socket. For details on this,
1010  * see g_socket_set_listen_backlog().
1011  *
1012  * Returns: the maximum number of pending connections.
1013  *
1014  * Since: 2.22
1015  */
1016 gint
1017 g_socket_get_listen_backlog  (GSocket *socket)
1018 {
1019   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1020
1021   return socket->priv->listen_backlog;
1022 }
1023
1024 /**
1025  * g_socket_set_listen_backlog:
1026  * @socket: a #GSocket.
1027  * @backlog: the maximum number of pending connections.
1028  *
1029  * Sets the maximum number of outstanding connections allowed
1030  * when listening on this socket. If more clients than this are
1031  * connecting to the socket and the application is not handling them
1032  * on time then the new connections will be refused.
1033  *
1034  * Note that this must be called before g_socket_listen() and has no
1035  * effect if called after that.
1036  *
1037  * Since: 2.22
1038  */
1039 void
1040 g_socket_set_listen_backlog (GSocket *socket,
1041                              gint     backlog)
1042 {
1043   g_return_if_fail (G_IS_SOCKET (socket));
1044   g_return_if_fail (!socket->priv->listening);
1045
1046   if (backlog != socket->priv->listen_backlog)
1047     {
1048       socket->priv->listen_backlog = backlog;
1049       g_object_notify (G_OBJECT (socket), "listen-backlog");
1050     }
1051 }
1052
1053 /**
1054  * g_socket_get_timeout:
1055  * @socket: a #GSocket.
1056  *
1057  * Gets the timeout setting of the socket. For details on this, see
1058  * g_socket_set_timeout().
1059  *
1060  * Returns: the timeout in seconds
1061  *
1062  * Since: 2.26
1063  */
1064 guint
1065 g_socket_get_timeout (GSocket *socket)
1066 {
1067   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1068
1069   return socket->priv->timeout;
1070 }
1071
1072 /**
1073  * g_socket_set_timeout:
1074  * @socket: a #GSocket.
1075  * @timeout: the timeout for @socket, in seconds, or 0 for none
1076  *
1077  * Sets the time in seconds after which I/O operations on @socket will
1078  * time out if they have not yet completed.
1079  *
1080  * On a blocking socket, this means that any blocking #GSocket
1081  * operation will time out after @timeout seconds of inactivity,
1082  * returning %G_IO_ERROR_TIMED_OUT.
1083  *
1084  * On a non-blocking socket, calls to g_socket_condition_wait() will
1085  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1086  * created with g_socket_create_source() will trigger after
1087  * @timeout seconds of inactivity, with the requested condition
1088  * set, at which point calling g_socket_receive(), g_socket_send(),
1089  * g_socket_check_connect_result(), etc, will fail with
1090  * %G_IO_ERROR_TIMED_OUT.
1091  *
1092  * If @timeout is 0 (the default), operations will never time out
1093  * on their own.
1094  *
1095  * Note that if an I/O operation is interrupted by a signal, this may
1096  * cause the timeout to be reset.
1097  *
1098  * Since: 2.26
1099  */
1100 void
1101 g_socket_set_timeout (GSocket *socket,
1102                       guint    timeout)
1103 {
1104   g_return_if_fail (G_IS_SOCKET (socket));
1105
1106   if (timeout != socket->priv->timeout)
1107     {
1108       socket->priv->timeout = timeout;
1109       g_object_notify (G_OBJECT (socket), "timeout");
1110     }
1111 }
1112
1113 /**
1114  * g_socket_get_family:
1115  * @socket: a #GSocket.
1116  *
1117  * Gets the socket family of the socket.
1118  *
1119  * Returns: a #GSocketFamily
1120  *
1121  * Since: 2.22
1122  */
1123 GSocketFamily
1124 g_socket_get_family (GSocket *socket)
1125 {
1126   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1127
1128   return socket->priv->family;
1129 }
1130
1131 /**
1132  * g_socket_get_socket_type:
1133  * @socket: a #GSocket.
1134  *
1135  * Gets the socket type of the socket.
1136  *
1137  * Returns: a #GSocketType
1138  *
1139  * Since: 2.22
1140  */
1141 GSocketType
1142 g_socket_get_socket_type (GSocket *socket)
1143 {
1144   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1145
1146   return socket->priv->type;
1147 }
1148
1149 /**
1150  * g_socket_get_protocol:
1151  * @socket: a #GSocket.
1152  *
1153  * Gets the socket protocol id the socket was created with.
1154  * In case the protocol is unknown, -1 is returned.
1155  *
1156  * Returns: a protocol id, or -1 if unknown
1157  *
1158  * Since: 2.22
1159  */
1160 GSocketProtocol
1161 g_socket_get_protocol (GSocket *socket)
1162 {
1163   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1164
1165   return socket->priv->protocol;
1166 }
1167
1168 /**
1169  * g_socket_get_fd:
1170  * @socket: a #GSocket.
1171  *
1172  * Returns the underlying OS socket object. On unix this
1173  * is a socket file descriptor, and on windows this is
1174  * a Winsock2 SOCKET handle. This may be useful for
1175  * doing platform specific or otherwise unusual operations
1176  * on the socket.
1177  *
1178  * Returns: the file descriptor of the socket.
1179  *
1180  * Since: 2.22
1181  */
1182 int
1183 g_socket_get_fd (GSocket *socket)
1184 {
1185   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1186
1187   return socket->priv->fd;
1188 }
1189
1190 /**
1191  * g_socket_get_local_address:
1192  * @socket: a #GSocket.
1193  * @error: #GError for error reporting, or %NULL to ignore.
1194  *
1195  * Try to get the local address of a bound socket. This is only
1196  * useful if the socket has been bound to a local address,
1197  * either explicitly or implicitly when connecting.
1198  *
1199  * Returns: a #GSocketAddress or %NULL on error.
1200  *     Free the returned object with g_object_unref().
1201  *
1202  * Since: 2.22
1203  */
1204 GSocketAddress *
1205 g_socket_get_local_address (GSocket  *socket,
1206                             GError  **error)
1207 {
1208   struct sockaddr_storage buffer;
1209   guint32 len = sizeof (buffer);
1210
1211   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1212
1213   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1214     {
1215       int errsv = get_socket_errno ();
1216       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1217                    _("could not get local address: %s"), socket_strerror (errsv));
1218       return NULL;
1219     }
1220
1221   return g_socket_address_new_from_native (&buffer, len);
1222 }
1223
1224 /**
1225  * g_socket_get_remote_address:
1226  * @socket: a #GSocket.
1227  * @error: #GError for error reporting, or %NULL to ignore.
1228  *
1229  * Try to get the remove address of a connected socket. This is only
1230  * useful for connection oriented sockets that have been connected.
1231  *
1232  * Returns: a #GSocketAddress or %NULL on error.
1233  *     Free the returned object with g_object_unref().
1234  *
1235  * Since: 2.22
1236  */
1237 GSocketAddress *
1238 g_socket_get_remote_address (GSocket  *socket,
1239                              GError  **error)
1240 {
1241   struct sockaddr_storage buffer;
1242   guint32 len = sizeof (buffer);
1243
1244   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1245
1246   if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1247     {
1248       int errsv = get_socket_errno ();
1249       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1250                    _("could not get remote address: %s"), socket_strerror (errsv));
1251       return NULL;
1252     }
1253
1254   return g_socket_address_new_from_native (&buffer, len);
1255 }
1256
1257 /**
1258  * g_socket_is_connected:
1259  * @socket: a #GSocket.
1260  *
1261  * Check whether the socket is connected. This is only useful for
1262  * connection-oriented sockets.
1263  *
1264  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1265  *
1266  * Since: 2.22
1267  */
1268 gboolean
1269 g_socket_is_connected (GSocket *socket)
1270 {
1271   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1272
1273   return socket->priv->connected;
1274 }
1275
1276 /**
1277  * g_socket_listen:
1278  * @socket: a #GSocket.
1279  * @error: #GError for error reporting, or %NULL to ignore.
1280  *
1281  * Marks the socket as a server socket, i.e. a socket that is used
1282  * to accept incoming requests using g_socket_accept().
1283  *
1284  * Before calling this the socket must be bound to a local address using
1285  * g_socket_bind().
1286  *
1287  * To set the maximum amount of outstanding clients, use
1288  * g_socket_set_listen_backlog().
1289  *
1290  * Returns: %TRUE on success, %FALSE on error.
1291  *
1292  * Since: 2.22
1293  */
1294 gboolean
1295 g_socket_listen (GSocket  *socket,
1296                  GError  **error)
1297 {
1298   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1299
1300   if (!check_socket (socket, error))
1301     return FALSE;
1302
1303   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1304     {
1305       int errsv = get_socket_errno ();
1306
1307       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1308                    _("could not listen: %s"), socket_strerror (errsv));
1309       return FALSE;
1310     }
1311
1312   socket->priv->listening = TRUE;
1313
1314   return TRUE;
1315 }
1316
1317 /**
1318  * g_socket_bind:
1319  * @socket: a #GSocket.
1320  * @address: a #GSocketAddress specifying the local address.
1321  * @allow_reuse: whether to allow reusing this address
1322  * @error: #GError for error reporting, or %NULL to ignore.
1323  *
1324  * When a socket is created it is attached to an address family, but it
1325  * doesn't have an address in this family. g_socket_bind() assigns the
1326  * address (sometimes called name) of the socket.
1327  *
1328  * It is generally required to bind to a local address before you can
1329  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1330  * In certain situations, you may also want to bind a socket that will be
1331  * used to initiate connections, though this is not normally required.
1332  *
1333  * @allow_reuse should be %TRUE for server sockets (sockets that you will
1334  * eventually call g_socket_accept() on), and %FALSE for client sockets.
1335  * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1336  * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1337  * that address was previously used by another socket that has not yet been
1338  * fully cleaned-up by the kernel. Failing to set this flag on a server
1339  * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1340  * the server program is stopped and then immediately restarted.)
1341  *
1342  * Returns: %TRUE on success, %FALSE on error.
1343  *
1344  * Since: 2.22
1345  */
1346 gboolean
1347 g_socket_bind (GSocket         *socket,
1348                GSocketAddress  *address,
1349                gboolean         reuse_address,
1350                GError         **error)
1351 {
1352   struct sockaddr_storage addr;
1353
1354   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1355
1356   if (!check_socket (socket, error))
1357     return FALSE;
1358
1359   /* SO_REUSEADDR on windows means something else and is not what we want.
1360      It always allows the unix variant of SO_REUSEADDR anyway */
1361 #ifndef G_OS_WIN32
1362   {
1363     int value;
1364
1365     value = (int) !!reuse_address;
1366     /* Ignore errors here, the only likely error is "not supported", and
1367        this is a "best effort" thing mainly */
1368     setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1369                 (gpointer) &value, sizeof (value));
1370   }
1371 #endif
1372
1373   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1374     return FALSE;
1375
1376   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1377             g_socket_address_get_native_size (address)) < 0)
1378     {
1379       int errsv = get_socket_errno ();
1380       g_set_error (error,
1381                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1382                    _("Error binding to address: %s"), socket_strerror (errsv));
1383       return FALSE;
1384     }
1385
1386   return TRUE;
1387 }
1388
1389 /**
1390  * g_socket_speaks_ipv4:
1391  * @socket: a #GSocket
1392  *
1393  * Checks if a socket is capable of speaking IPv4.
1394  *
1395  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
1396  * and under some combinations of circumstances IPv6 sockets are also
1397  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
1398  * information.
1399  *
1400  * No other types of sockets are currently considered as being capable
1401  * of speaking IPv4.
1402  *
1403  * Returns: %TRUE if this socket can be used with IPv4.
1404  *
1405  * Since: 2.22
1406  **/
1407 gboolean
1408 g_socket_speaks_ipv4 (GSocket *socket)
1409 {
1410   switch (socket->priv->family)
1411     {
1412     case G_SOCKET_FAMILY_IPV4:
1413       return TRUE;
1414
1415     case G_SOCKET_FAMILY_IPV6:
1416 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1417       {
1418         guint sizeof_int = sizeof (int);
1419         gint v6_only;
1420
1421         if (getsockopt (socket->priv->fd,
1422                         IPPROTO_IPV6, IPV6_V6ONLY,
1423                         &v6_only, &sizeof_int) != 0)
1424           return FALSE;
1425
1426         return !v6_only;
1427       }
1428 #else
1429       return FALSE;
1430 #endif
1431
1432     default:
1433       return FALSE;
1434     }
1435 }
1436
1437 /**
1438  * g_socket_accept:
1439  * @socket: a #GSocket.
1440  * @cancellable: a %GCancellable or %NULL
1441  * @error: #GError for error reporting, or %NULL to ignore.
1442  *
1443  * Accept incoming connections on a connection-based socket. This removes
1444  * the first outstanding connection request from the listening socket and
1445  * creates a #GSocket object for it.
1446  *
1447  * The @socket must be bound to a local address with g_socket_bind() and
1448  * must be listening for incoming connections (g_socket_listen()).
1449  *
1450  * If there are no outstanding connections then the operation will block
1451  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1452  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1453  *
1454  * Returns: a new #GSocket, or %NULL on error.
1455  *     Free the returned object with g_object_unref().
1456  *
1457  * Since: 2.22
1458  */
1459 GSocket *
1460 g_socket_accept (GSocket       *socket,
1461                  GCancellable  *cancellable,
1462                  GError       **error)
1463 {
1464   GSocket *new_socket;
1465   gint ret;
1466
1467   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1468
1469   if (!check_socket (socket, error))
1470     return NULL;
1471
1472   while (TRUE)
1473     {
1474       if (socket->priv->blocking &&
1475           !g_socket_condition_wait (socket,
1476                                     G_IO_IN, cancellable, error))
1477         return NULL;
1478
1479       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1480         {
1481           int errsv = get_socket_errno ();
1482
1483           win32_unset_event_mask (socket, FD_ACCEPT);
1484
1485           if (errsv == EINTR)
1486             continue;
1487
1488           if (socket->priv->blocking)
1489             {
1490 #ifdef WSAEWOULDBLOCK
1491               if (errsv == WSAEWOULDBLOCK)
1492                 continue;
1493 #else
1494               if (errsv == EWOULDBLOCK ||
1495                   errsv == EAGAIN)
1496                 continue;
1497 #endif
1498             }
1499
1500           g_set_error (error, G_IO_ERROR,
1501                        socket_io_error_from_errno (errsv),
1502                        _("Error accepting connection: %s"), socket_strerror (errsv));
1503           return NULL;
1504         }
1505       break;
1506     }
1507
1508   win32_unset_event_mask (socket, FD_ACCEPT);
1509
1510 #ifdef G_OS_WIN32
1511   {
1512     /* The socket inherits the accepting sockets event mask and even object,
1513        we need to remove that */
1514     WSAEventSelect (ret, NULL, 0);
1515   }
1516 #else
1517   {
1518     int flags;
1519
1520     /* We always want to set close-on-exec to protect users. If you
1521        need to so some weird inheritance to exec you can re-enable this
1522        using lower level hacks with g_socket_get_fd(). */
1523     flags = fcntl (ret, F_GETFD, 0);
1524     if (flags != -1 &&
1525         (flags & FD_CLOEXEC) == 0)
1526       {
1527         flags |= FD_CLOEXEC;
1528         fcntl (ret, F_SETFD, flags);
1529       }
1530   }
1531 #endif
1532
1533   new_socket = g_socket_new_from_fd (ret, error);
1534   if (new_socket == NULL)
1535     {
1536 #ifdef G_OS_WIN32
1537       closesocket (ret);
1538 #else
1539       close (ret);
1540 #endif
1541     }
1542   else
1543     new_socket->priv->protocol = socket->priv->protocol;
1544
1545   return new_socket;
1546 }
1547
1548 /**
1549  * g_socket_connect:
1550  * @socket: a #GSocket.
1551  * @address: a #GSocketAddress specifying the remote address.
1552  * @cancellable: a %GCancellable or %NULL
1553  * @error: #GError for error reporting, or %NULL to ignore.
1554  *
1555  * Connect the socket to the specified remote address.
1556  *
1557  * For connection oriented socket this generally means we attempt to make
1558  * a connection to the @address. For a connection-less socket it sets
1559  * the default address for g_socket_send() and discards all incoming datagrams
1560  * from other sources.
1561  *
1562  * Generally connection oriented sockets can only connect once, but
1563  * connection-less sockets can connect multiple times to change the
1564  * default address.
1565  *
1566  * If the connect call needs to do network I/O it will block, unless
1567  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1568  * and the user can be notified of the connection finishing by waiting
1569  * for the G_IO_OUT condition. The result of the connection can then be
1570  * checked with g_socket_check_connect_result().
1571  *
1572  * Returns: %TRUE if connected, %FALSE on error.
1573  *
1574  * Since: 2.22
1575  */
1576 gboolean
1577 g_socket_connect (GSocket         *socket,
1578                   GSocketAddress  *address,
1579                   GCancellable    *cancellable,
1580                   GError         **error)
1581 {
1582   struct sockaddr_storage buffer;
1583
1584   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1585
1586   if (!check_socket (socket, error))
1587     return FALSE;
1588
1589   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1590     return FALSE;
1591
1592   while (1)
1593     {
1594       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1595                    g_socket_address_get_native_size (address)) < 0)
1596         {
1597           int errsv = get_socket_errno ();
1598
1599           if (errsv == EINTR)
1600             continue;
1601
1602 #ifndef G_OS_WIN32
1603           if (errsv == EINPROGRESS)
1604 #else
1605           if (errsv == WSAEWOULDBLOCK)
1606 #endif
1607             {
1608               if (socket->priv->blocking)
1609                 {
1610                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1611                     {
1612                       if (g_socket_check_connect_result (socket, error))
1613                         break;
1614                     }
1615                   g_prefix_error (error, _("Error connecting: "));
1616                 }
1617               else
1618                 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1619                                      _("Connection in progress"));
1620             }
1621           else
1622             g_set_error (error, G_IO_ERROR,
1623                          socket_io_error_from_errno (errsv),
1624                          _("Error connecting: %s"), socket_strerror (errsv));
1625
1626           return FALSE;
1627         }
1628       break;
1629     }
1630
1631   win32_unset_event_mask (socket, FD_CONNECT);
1632
1633   socket->priv->connected = TRUE;
1634
1635   return TRUE;
1636 }
1637
1638 /**
1639  * g_socket_check_connect_result:
1640  * @socket: a #GSocket
1641  * @error: #GError for error reporting, or %NULL to ignore.
1642  *
1643  * Checks and resets the pending connect error for the socket.
1644  * This is used to check for errors when g_socket_connect() is
1645  * used in non-blocking mode.
1646  *
1647  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1648  *
1649  * Since: 2.22
1650  */
1651 gboolean
1652 g_socket_check_connect_result (GSocket  *socket,
1653                                GError  **error)
1654 {
1655   guint optlen;
1656   int value;
1657
1658   if (!check_socket (socket, error))
1659     return FALSE;
1660
1661   optlen = sizeof (value);
1662   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1663     {
1664       int errsv = get_socket_errno ();
1665
1666       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1667                    _("Unable to get pending error: %s"), socket_strerror (errsv));
1668       return FALSE;
1669     }
1670
1671   if (value != 0)
1672     {
1673       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1674                            socket_strerror (value));
1675       return FALSE;
1676     }
1677   return TRUE;
1678 }
1679
1680 /**
1681  * g_socket_receive:
1682  * @socket: a #GSocket
1683  * @buffer: a buffer to read data into (which should be at least @size
1684  *     bytes long).
1685  * @size: the number of bytes you want to read from the socket
1686  * @cancellable: a %GCancellable or %NULL
1687  * @error: #GError for error reporting, or %NULL to ignore.
1688  *
1689  * Receive data (up to @size bytes) from a socket. This is mainly used by
1690  * connection-oriented sockets; it is identical to g_socket_receive_from()
1691  * with @address set to %NULL.
1692  *
1693  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1694  * g_socket_receive() will always read either 0 or 1 complete messages from
1695  * the socket. If the received message is too large to fit in @buffer, then
1696  * the data beyond @size bytes will be discarded, without any explicit
1697  * indication that this has occurred.
1698  *
1699  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1700  * number of bytes, up to @size. If more than @size bytes have been
1701  * received, the additional data will be returned in future calls to
1702  * g_socket_receive().
1703  *
1704  * If the socket is in blocking mode the call will block until there is
1705  * some data to receive or there is an error. If there is no data available
1706  * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1707  * will be returned. To be notified when data is available, wait for the
1708  * %G_IO_IN condition.
1709  *
1710  * On error -1 is returned and @error is set accordingly.
1711  *
1712  * Returns: Number of bytes read, or -1 on error
1713  *
1714  * Since: 2.22
1715  */
1716 gssize
1717 g_socket_receive (GSocket       *socket,
1718                   gchar         *buffer,
1719                   gsize          size,
1720                   GCancellable  *cancellable,
1721                   GError       **error)
1722 {
1723   gssize ret;
1724
1725   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1726
1727   if (!check_socket (socket, error))
1728     return -1;
1729
1730   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1731     return -1;
1732
1733   while (1)
1734     {
1735       if (socket->priv->blocking &&
1736           !g_socket_condition_wait (socket,
1737                                     G_IO_IN, cancellable, error))
1738         return -1;
1739
1740       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1741         {
1742           int errsv = get_socket_errno ();
1743
1744           if (errsv == EINTR)
1745             continue;
1746
1747           if (socket->priv->blocking)
1748             {
1749 #ifdef WSAEWOULDBLOCK
1750               if (errsv == WSAEWOULDBLOCK)
1751                 continue;
1752 #else
1753               if (errsv == EWOULDBLOCK ||
1754                   errsv == EAGAIN)
1755                 continue;
1756 #endif
1757             }
1758
1759           win32_unset_event_mask (socket, FD_READ);
1760
1761           g_set_error (error, G_IO_ERROR,
1762                        socket_io_error_from_errno (errsv),
1763                        _("Error receiving data: %s"), socket_strerror (errsv));
1764           return -1;
1765         }
1766
1767       win32_unset_event_mask (socket, FD_READ);
1768
1769       break;
1770     }
1771
1772   return ret;
1773 }
1774
1775 /**
1776  * g_socket_receive_from:
1777  * @socket: a #GSocket
1778  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1779  * @buffer: a buffer to read data into (which should be at least @size
1780  *     bytes long).
1781  * @size: the number of bytes you want to read from the socket
1782  * @cancellable: a %GCancellable or %NULL
1783  * @error: #GError for error reporting, or %NULL to ignore.
1784  *
1785  * Receive data (up to @size bytes) from a socket.
1786  *
1787  * If @address is non-%NULL then @address will be set equal to the
1788  * source address of the received packet.
1789  * @address is owned by the caller.
1790  *
1791  * See g_socket_receive() for additional information.
1792  *
1793  * Returns: Number of bytes read, or -1 on error
1794  *
1795  * Since: 2.22
1796  */
1797 gssize
1798 g_socket_receive_from (GSocket         *socket,
1799                        GSocketAddress **address,
1800                        gchar           *buffer,
1801                        gsize            size,
1802                        GCancellable    *cancellable,
1803                        GError         **error)
1804 {
1805   GInputVector v;
1806
1807   v.buffer = buffer;
1808   v.size = size;
1809
1810   return g_socket_receive_message (socket,
1811                                    address,
1812                                    &v, 1,
1813                                    NULL, 0, NULL,
1814                                    cancellable,
1815                                    error);
1816 }
1817
1818 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1819  * one, which can be confusing and annoying. So if possible, we want
1820  * to suppress the signal entirely.
1821  */
1822 #ifdef MSG_NOSIGNAL
1823 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1824 #else
1825 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1826 #endif
1827
1828 /**
1829  * g_socket_send:
1830  * @socket: a #GSocket
1831  * @buffer: the buffer containing the data to send.
1832  * @size: the number of bytes to send
1833  * @cancellable: a %GCancellable or %NULL
1834  * @error: #GError for error reporting, or %NULL to ignore.
1835  *
1836  * Tries to send @size bytes from @buffer on the socket. This is
1837  * mainly used by connection-oriented sockets; it is identical to
1838  * g_socket_send_to() with @address set to %NULL.
1839  *
1840  * If the socket is in blocking mode the call will block until there is
1841  * space for the data in the socket queue. If there is no space available
1842  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1843  * will be returned. To be notified when space is available, wait for the
1844  * %G_IO_OUT condition. Note though that you may still receive
1845  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1846  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1847  * very common due to the way the underlying APIs work.)
1848  *
1849  * On error -1 is returned and @error is set accordingly.
1850  *
1851  * Returns: Number of bytes written (which may be less than @size), or -1
1852  * on error
1853  *
1854  * Since: 2.22
1855  */
1856 gssize
1857 g_socket_send (GSocket       *socket,
1858                const gchar   *buffer,
1859                gsize          size,
1860                GCancellable  *cancellable,
1861                GError       **error)
1862 {
1863   gssize ret;
1864
1865   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1866
1867   if (!check_socket (socket, error))
1868     return -1;
1869
1870   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1871     return -1;
1872
1873   while (1)
1874     {
1875       if (socket->priv->blocking &&
1876           !g_socket_condition_wait (socket,
1877                                     G_IO_OUT, cancellable, error))
1878         return -1;
1879
1880       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1881         {
1882           int errsv = get_socket_errno ();
1883
1884           if (errsv == EINTR)
1885             continue;
1886
1887 #ifdef WSAEWOULDBLOCK
1888           if (errsv == WSAEWOULDBLOCK)
1889             win32_unset_event_mask (socket, FD_WRITE);
1890 #endif
1891
1892           if (socket->priv->blocking)
1893             {
1894 #ifdef WSAEWOULDBLOCK
1895               if (errsv == WSAEWOULDBLOCK)
1896                 continue;
1897 #else
1898               if (errsv == EWOULDBLOCK ||
1899                   errsv == EAGAIN)
1900                 continue;
1901 #endif
1902             }
1903
1904           g_set_error (error, G_IO_ERROR,
1905                        socket_io_error_from_errno (errsv),
1906                        _("Error sending data: %s"), socket_strerror (errsv));
1907           return -1;
1908         }
1909       break;
1910     }
1911
1912   return ret;
1913 }
1914
1915 /**
1916  * g_socket_send_to:
1917  * @socket: a #GSocket
1918  * @address: a #GSocketAddress, or %NULL
1919  * @buffer: the buffer containing the data to send.
1920  * @size: the number of bytes to send
1921  * @cancellable: a %GCancellable or %NULL
1922  * @error: #GError for error reporting, or %NULL to ignore.
1923  *
1924  * Tries to send @size bytes from @buffer to @address. If @address is
1925  * %NULL then the message is sent to the default receiver (set by
1926  * g_socket_connect()).
1927  *
1928  * See g_socket_send() for additional information.
1929  *
1930  * Returns: Number of bytes written (which may be less than @size), or -1
1931  * on error
1932  *
1933  * Since: 2.22
1934  */
1935 gssize
1936 g_socket_send_to (GSocket         *socket,
1937                   GSocketAddress  *address,
1938                   const gchar     *buffer,
1939                   gsize            size,
1940                   GCancellable    *cancellable,
1941                   GError         **error)
1942 {
1943   GOutputVector v;
1944
1945   v.buffer = buffer;
1946   v.size = size;
1947
1948   return g_socket_send_message (socket,
1949                                 address,
1950                                 &v, 1,
1951                                 NULL, 0,
1952                                 0,
1953                                 cancellable,
1954                                 error);
1955 }
1956
1957 /**
1958  * g_socket_shutdown:
1959  * @socket: a #GSocket
1960  * @shutdown_read: whether to shut down the read side
1961  * @shutdown_write: whether to shut down the write side
1962  * @error: #GError for error reporting, or %NULL to ignore.
1963  *
1964  * Shut down part of a full-duplex connection.
1965  *
1966  * If @shutdown_read is %TRUE then the recieving side of the connection
1967  * is shut down, and further reading is disallowed.
1968  *
1969  * If @shutdown_write is %TRUE then the sending side of the connection
1970  * is shut down, and further writing is disallowed.
1971  *
1972  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
1973  *
1974  * One example where this is used is graceful disconnect for TCP connections
1975  * where you close the sending side, then wait for the other side to close
1976  * the connection, thus ensuring that the other side saw all sent data.
1977  *
1978  * Returns: %TRUE on success, %FALSE on error
1979  *
1980  * Since: 2.22
1981  */
1982 gboolean
1983 g_socket_shutdown (GSocket   *socket,
1984                    gboolean   shutdown_read,
1985                    gboolean   shutdown_write,
1986                    GError   **error)
1987 {
1988   int how;
1989
1990   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
1991
1992   if (!check_socket (socket, NULL))
1993     return FALSE;
1994
1995   /* Do nothing? */
1996   if (!shutdown_read && !shutdown_write)
1997     return TRUE;
1998
1999 #ifndef G_OS_WIN32
2000   if (shutdown_read && shutdown_write)
2001     how = SHUT_RDWR;
2002   else if (shutdown_read)
2003     how = SHUT_RD;
2004   else
2005     how = SHUT_WR;
2006 #else
2007   if (shutdown_read && shutdown_write)
2008     how = SD_BOTH;
2009   else if (shutdown_read)
2010     how = SD_RECEIVE;
2011   else
2012     how = SD_SEND;
2013 #endif
2014
2015   if (shutdown (socket->priv->fd, how) != 0)
2016     {
2017       int errsv = get_socket_errno ();
2018       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2019                    _("Unable to create socket: %s"), socket_strerror (errsv));
2020       return FALSE;
2021     }
2022
2023   if (shutdown_read && shutdown_write)
2024     socket->priv->connected = FALSE;
2025
2026   return TRUE;
2027 }
2028
2029 /**
2030  * g_socket_close:
2031  * @socket: a #GSocket
2032  * @error: #GError for error reporting, or %NULL to ignore.
2033  *
2034  * Closes the socket, shutting down any active connection.
2035  *
2036  * Closing a socket does not wait for all outstanding I/O operations
2037  * to finish, so the caller should not rely on them to be guaranteed
2038  * to complete even if the close returns with no error.
2039  *
2040  * Once the socket is closed, all other operations will return
2041  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2042  * return an error.
2043  *
2044  * Sockets will be automatically closed when the last reference
2045  * is dropped, but you might want to call this function to make sure
2046  * resources are released as early as possible.
2047  *
2048  * Beware that due to the way that TCP works, it is possible for
2049  * recently-sent data to be lost if either you close a socket while the
2050  * %G_IO_IN condition is set, or else if the remote connection tries to
2051  * send something to you after you close the socket but before it has
2052  * finished reading all of the data you sent. There is no easy generic
2053  * way to avoid this problem; the easiest fix is to design the network
2054  * protocol such that the client will never send data "out of turn".
2055  * Another solution is for the server to half-close the connection by
2056  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2057  * and then wait for the client to notice this and close its side of the
2058  * connection, after which the server can safely call g_socket_close().
2059  * (This is what #GTcpConnection does if you call
2060  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2061  * only works if the client will close its connection after the server
2062  * does.)
2063  *
2064  * Returns: %TRUE on success, %FALSE on error
2065  *
2066  * Since: 2.22
2067  */
2068 gboolean
2069 g_socket_close (GSocket  *socket,
2070                 GError  **error)
2071 {
2072   int res;
2073
2074   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2075
2076   if (socket->priv->closed)
2077     return TRUE; /* Multiple close not an error */
2078
2079   if (!check_socket (socket, NULL))
2080     return FALSE;
2081
2082   while (1)
2083     {
2084 #ifdef G_OS_WIN32
2085       res = closesocket (socket->priv->fd);
2086 #else
2087       res = close (socket->priv->fd);
2088 #endif
2089       if (res == -1)
2090         {
2091           int errsv = get_socket_errno ();
2092
2093           if (errsv == EINTR)
2094             continue;
2095
2096           g_set_error (error, G_IO_ERROR,
2097                        socket_io_error_from_errno (errsv),
2098                        _("Error closing socket: %s"),
2099                        socket_strerror (errsv));
2100           return FALSE;
2101         }
2102       break;
2103     }
2104
2105   socket->priv->connected = FALSE;
2106   socket->priv->closed = TRUE;
2107
2108   return TRUE;
2109 }
2110
2111 /**
2112  * g_socket_is_closed:
2113  * @socket: a #GSocket
2114  *
2115  * Checks whether a socket is closed.
2116  *
2117  * Returns: %TRUE if socket is closed, %FALSE otherwise
2118  *
2119  * Since: 2.22
2120  */
2121 gboolean
2122 g_socket_is_closed (GSocket *socket)
2123 {
2124   return socket->priv->closed;
2125 }
2126
2127 #ifdef G_OS_WIN32
2128 /* Broken source, used on errors */
2129 static gboolean
2130 broken_prepare  (GSource *source,
2131                  gint    *timeout)
2132 {
2133   return FALSE;
2134 }
2135
2136 static gboolean
2137 broken_check (GSource *source)
2138 {
2139   return FALSE;
2140 }
2141
2142 static gboolean
2143 broken_dispatch (GSource     *source,
2144                  GSourceFunc  callback,
2145                  gpointer     user_data)
2146 {
2147   return TRUE;
2148 }
2149
2150 static GSourceFuncs broken_funcs =
2151 {
2152   broken_prepare,
2153   broken_check,
2154   broken_dispatch,
2155   NULL
2156 };
2157
2158 static gint
2159 network_events_for_condition (GIOCondition condition)
2160 {
2161   int event_mask = 0;
2162
2163   if (condition & G_IO_IN)
2164     event_mask |= (FD_READ | FD_ACCEPT);
2165   if (condition & G_IO_OUT)
2166     event_mask |= (FD_WRITE | FD_CONNECT);
2167   event_mask |= FD_CLOSE;
2168
2169   return event_mask;
2170 }
2171
2172 static void
2173 ensure_event (GSocket *socket)
2174 {
2175   if (socket->priv->event == WSA_INVALID_EVENT)
2176     socket->priv->event = WSACreateEvent();
2177 }
2178
2179 static void
2180 update_select_events (GSocket *socket)
2181 {
2182   int event_mask;
2183   GIOCondition *ptr;
2184   GList *l;
2185   WSAEVENT event;
2186
2187   ensure_event (socket);
2188
2189   event_mask = 0;
2190   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2191     {
2192       ptr = l->data;
2193       event_mask |= network_events_for_condition (*ptr);
2194     }
2195
2196   if (event_mask != socket->priv->selected_events)
2197     {
2198       /* If no events selected, disable event so we can unset
2199          nonblocking mode */
2200
2201       if (event_mask == 0)
2202         event = NULL;
2203       else
2204         event = socket->priv->event;
2205
2206       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2207         socket->priv->selected_events = event_mask;
2208     }
2209 }
2210
2211 static void
2212 add_condition_watch (GSocket      *socket,
2213                      GIOCondition *condition)
2214 {
2215   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2216
2217   socket->priv->requested_conditions =
2218     g_list_prepend (socket->priv->requested_conditions, condition);
2219
2220   update_select_events (socket);
2221 }
2222
2223 static void
2224 remove_condition_watch (GSocket      *socket,
2225                         GIOCondition *condition)
2226 {
2227   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2228
2229   socket->priv->requested_conditions =
2230     g_list_remove (socket->priv->requested_conditions, condition);
2231
2232   update_select_events (socket);
2233 }
2234
2235 static GIOCondition
2236 update_condition (GSocket *socket)
2237 {
2238   WSANETWORKEVENTS events;
2239   GIOCondition condition;
2240
2241   if (WSAEnumNetworkEvents (socket->priv->fd,
2242                             socket->priv->event,
2243                             &events) == 0)
2244     {
2245       socket->priv->current_events |= events.lNetworkEvents;
2246       if (events.lNetworkEvents & FD_WRITE &&
2247           events.iErrorCode[FD_WRITE_BIT] != 0)
2248         socket->priv->current_errors |= FD_WRITE;
2249       if (events.lNetworkEvents & FD_CONNECT &&
2250           events.iErrorCode[FD_CONNECT_BIT] != 0)
2251         socket->priv->current_errors |= FD_CONNECT;
2252     }
2253
2254   condition = 0;
2255   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2256     condition |= G_IO_IN;
2257
2258   if (socket->priv->current_events & FD_CLOSE ||
2259       socket->priv->closed)
2260     condition |= G_IO_HUP;
2261
2262   /* Never report both G_IO_OUT and HUP, these are
2263      mutually exclusive (can't write to a closed socket) */
2264   if ((condition & G_IO_HUP) == 0 &&
2265       socket->priv->current_events & FD_WRITE)
2266     {
2267       if (socket->priv->current_errors & FD_WRITE)
2268         condition |= G_IO_ERR;
2269       else
2270         condition |= G_IO_OUT;
2271     }
2272   else
2273     {
2274       if (socket->priv->current_events & FD_CONNECT)
2275         {
2276           if (socket->priv->current_errors & FD_CONNECT)
2277             condition |= (G_IO_HUP | G_IO_ERR);
2278           else
2279             condition |= G_IO_OUT;
2280         }
2281     }
2282
2283   return condition;
2284 }
2285 #endif
2286
2287 typedef struct {
2288   GSource       source;
2289   GPollFD       pollfd;
2290   GSocket      *socket;
2291   GIOCondition  condition;
2292   GCancellable *cancellable;
2293   GPollFD       cancel_pollfd;
2294   GTimeVal      timeout_time;
2295 } GSocketSource;
2296
2297 static gboolean
2298 socket_source_prepare (GSource *source,
2299                        gint    *timeout)
2300 {
2301   GSocketSource *socket_source = (GSocketSource *)source;
2302
2303   if (g_cancellable_is_cancelled (socket_source->cancellable))
2304     return TRUE;
2305
2306   if (socket_source->timeout_time.tv_sec)
2307     {
2308       GTimeVal now;
2309
2310       g_source_get_current_time (source, &now);
2311       *timeout = ((socket_source->timeout_time.tv_sec - now.tv_sec) * 1000 +
2312                   (socket_source->timeout_time.tv_usec - now.tv_usec) / 1000);
2313       if (*timeout < 0)
2314         {
2315           socket_source->socket->priv->timed_out = TRUE;
2316           socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2317           return TRUE;
2318         }
2319     }
2320   else
2321     *timeout = -1;
2322
2323 #ifdef G_OS_WIN32
2324   socket_source->pollfd.revents = update_condition (socket_source->socket);
2325 #endif
2326
2327   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2328     return TRUE;
2329
2330   return FALSE;
2331 }
2332
2333 static gboolean
2334 socket_source_check (GSource *source)
2335 {
2336   int timeout;
2337
2338   return socket_source_prepare (source, &timeout);
2339 }
2340
2341 static gboolean
2342 socket_source_dispatch (GSource     *source,
2343                         GSourceFunc  callback,
2344                         gpointer     user_data)
2345 {
2346   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2347   GSocketSource *socket_source = (GSocketSource *)source;
2348
2349   return (*func) (socket_source->socket,
2350                   socket_source->pollfd.revents & socket_source->condition,
2351                   user_data);
2352 }
2353
2354 static void
2355 socket_source_finalize (GSource *source)
2356 {
2357   GSocketSource *socket_source = (GSocketSource *)source;
2358   GSocket *socket;
2359
2360   socket = socket_source->socket;
2361
2362 #ifdef G_OS_WIN32
2363   remove_condition_watch (socket, &socket_source->condition);
2364 #endif
2365
2366   g_object_unref (socket);
2367
2368   if (socket_source->cancellable)
2369     {
2370       g_cancellable_release_fd (socket_source->cancellable);
2371       g_object_unref (socket_source->cancellable);
2372     }
2373 }
2374
2375 static GSourceFuncs socket_source_funcs =
2376 {
2377   socket_source_prepare,
2378   socket_source_check,
2379   socket_source_dispatch,
2380   socket_source_finalize
2381 };
2382
2383 static GSource *
2384 socket_source_new (GSocket      *socket,
2385                    GIOCondition  condition,
2386                    GCancellable *cancellable)
2387 {
2388   GSource *source;
2389   GSocketSource *socket_source;
2390
2391 #ifdef G_OS_WIN32
2392   ensure_event (socket);
2393
2394   if (socket->priv->event == WSA_INVALID_EVENT)
2395     {
2396       g_warning ("Failed to create WSAEvent");
2397       return g_source_new (&broken_funcs, sizeof (GSource));
2398     }
2399 #endif
2400
2401   condition |= G_IO_HUP | G_IO_ERR;
2402
2403   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2404   socket_source = (GSocketSource *)source;
2405
2406   socket_source->socket = g_object_ref (socket);
2407   socket_source->condition = condition;
2408
2409   if (g_cancellable_make_pollfd (cancellable,
2410                                  &socket_source->cancel_pollfd))
2411     {
2412       socket_source->cancellable = g_object_ref (cancellable);
2413       g_source_add_poll (source, &socket_source->cancel_pollfd);
2414     }
2415
2416 #ifdef G_OS_WIN32
2417   add_condition_watch (socket, &socket_source->condition);
2418   socket_source->pollfd.fd = (gintptr) socket->priv->event;
2419 #else
2420   socket_source->pollfd.fd = socket->priv->fd;
2421 #endif
2422
2423   socket_source->pollfd.events = condition;
2424   socket_source->pollfd.revents = 0;
2425   g_source_add_poll (source, &socket_source->pollfd);
2426
2427   if (socket->priv->timeout)
2428     {
2429       g_get_current_time (&socket_source->timeout_time);
2430       socket_source->timeout_time.tv_sec += socket->priv->timeout;
2431     }
2432   else
2433     {
2434       socket_source->timeout_time.tv_sec = 0;
2435       socket_source->timeout_time.tv_usec = 0;
2436     }
2437
2438   return source;
2439 }
2440
2441 /**
2442  * g_socket_create_source:
2443  * @socket: a #GSocket
2444  * @condition: a #GIOCondition mask to monitor
2445  * @cancellable: a %GCancellable or %NULL
2446  *
2447  * Creates a %GSource that can be attached to a %GMainContext to monitor
2448  * for the availibility of the specified @condition on the socket.
2449  *
2450  * The callback on the source is of the #GSocketSourceFunc type.
2451  *
2452  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2453  * these conditions will always be reported output if they are true.
2454  *
2455  * @cancellable if not %NULL can be used to cancel the source, which will
2456  * cause the source to trigger, reporting the current condition (which
2457  * is likely 0 unless cancellation happened at the same time as a
2458  * condition change). You can check for this in the callback using
2459  * g_cancellable_is_cancelled().
2460  *
2461  * If @socket has a timeout set, and it is reached before @condition
2462  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2463  * %G_IO_OUT depending on @condition. However, @socket will have been
2464  * marked as having had a timeout, and so the next #GSocket I/O method
2465  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2466  *
2467  * Returns: a newly allocated %GSource, free with g_source_unref().
2468  *
2469  * Since: 2.22
2470  */
2471 GSource *
2472 g_socket_create_source (GSocket      *socket,
2473                         GIOCondition  condition,
2474                         GCancellable *cancellable)
2475 {
2476   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2477
2478   return socket_source_new (socket, condition, cancellable);
2479 }
2480
2481 /**
2482  * g_socket_condition_check:
2483  * @socket: a #GSocket
2484  * @condition: a #GIOCondition mask to check
2485  *
2486  * Checks on the readiness of @socket to perform operations.
2487  * The operations specified in @condition are checked for and masked
2488  * against the currently-satisfied conditions on @socket. The result
2489  * is returned.
2490  *
2491  * Note that on Windows, it is possible for an operation to return
2492  * %G_IO_ERROR_WOULD_BLOCK even immediately after
2493  * g_socket_condition_check() has claimed that the socket is ready for
2494  * writing. Rather than calling g_socket_condition_check() and then
2495  * writing to the socket if it succeeds, it is generally better to
2496  * simply try writing to the socket right away, and try again later if
2497  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
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 (num_messages != NULL)
3315       *num_messages = 0;
3316
3317     return bytes_received;
3318   }
3319 #endif
3320 }