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