Set optlen before calling getsockopt
[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) (user_data,
2093                   winsock_source->result_condition & winsock_source->condition);
2094 }
2095
2096 static void
2097 winsock_finalize (GSource *source)
2098 {
2099   GWinsockSource *winsock_source = (GWinsockSource *)source;
2100   GSocket *socket;
2101
2102   socket = winsock_source->socket;
2103
2104   remove_condition_watch (socket, &winsock_source->condition);
2105   g_object_unref (socket);
2106
2107   if (winsock_source->cancellable)
2108     g_object_unref (winsock_source->cancellable);
2109 }
2110
2111 static GSourceFuncs winsock_funcs =
2112 {
2113   winsock_prepare,
2114   winsock_check,
2115   winsock_dispatch,
2116   winsock_finalize
2117 };
2118
2119 static GSource *
2120 winsock_source_new (GSocket      *socket,
2121                     GIOCondition  condition,
2122                     GCancellable *cancellable)
2123 {
2124   GSource *source;
2125   GWinsockSource *winsock_source;
2126
2127   ensure_event (socket);
2128
2129   if (socket->priv->event == WSA_INVALID_EVENT)
2130     {
2131       g_warning ("Failed to create WSAEvent");
2132       return g_source_new (&broken_funcs, sizeof (GSource));
2133     }
2134
2135   condition |= G_IO_HUP | G_IO_ERR;
2136
2137   source = g_source_new (&winsock_funcs, sizeof (GWinsockSource));
2138   winsock_source = (GWinsockSource *)source;
2139
2140   winsock_source->socket = g_object_ref (socket);
2141   winsock_source->condition = condition;
2142   add_condition_watch (socket, &winsock_source->condition);
2143
2144   if (cancellable)
2145     {
2146       winsock_source->cancellable = g_object_ref (cancellable);
2147       g_cancellable_make_pollfd (cancellable,
2148                                  &winsock_source->cancel_pollfd);
2149       g_source_add_poll (source, &winsock_source->cancel_pollfd);
2150     }
2151
2152   winsock_source->pollfd.fd = (gintptr) socket->priv->event;
2153   winsock_source->pollfd.events = condition;
2154   g_source_add_poll (source, &winsock_source->pollfd);
2155
2156   return source;
2157 }
2158 #endif
2159
2160 /**
2161  * g_socket_create_source:
2162  * @socket: a #GSocket
2163  * @condition: a #GIOCondition mask to monitor
2164  * @cancellable: a %GCancellable or %NULL
2165  *
2166  * Creates a %GSource that can be attached to a %GMainContext to monitor
2167  * for the availibility of the specified @condition on the socket.
2168  *
2169  * The callback on the source is of the #GSocketSourceFunc type.
2170  *
2171  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2172  * these conditions will always be reported output if they are true.
2173  *
2174  * @cancellable if not %NULL can be used to cancel the source, which will
2175  * cause the source to trigger, reporting the current condition. You can
2176  * check for this in the callback using g_cancellable_is_cancelled().
2177  *
2178  * Returns: a newly allocated %GSource, free with g_source_unref().
2179  *
2180  * Since: 2.22
2181  **/
2182 GSource *
2183 g_socket_create_source (GSocket      *socket,
2184                         GIOCondition  condition,
2185                         GCancellable *cancellable)
2186 {
2187   GSource *source;
2188   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2189
2190 #ifdef G_OS_WIN32
2191   source = winsock_source_new (socket, condition, cancellable);
2192 #else
2193   source =_g_fd_source_new (socket->priv->fd, condition, cancellable);
2194 #endif
2195   return source;
2196 }
2197
2198 /**
2199  * g_socket_condition_check:
2200  * @socket: a #GSocket
2201  * @condition: a #GIOCondition mask to check
2202  *
2203  * Checks on the readiness of @socket to perform operations.  The
2204  * operations specified in @condition are checked for and masked
2205  * against the currently-satisfied conditions on @socket.  The result
2206  * is returned.
2207  *
2208  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2209  * these conditions will always be set in the output if they are true.
2210  *
2211  * This call never blocks.
2212  *
2213  * Returns: the @GIOCondition mask of the current state
2214  *
2215  * Since: 2.22
2216  **/
2217 GIOCondition
2218 g_socket_condition_check (GSocket       *socket,
2219                           GIOCondition   condition)
2220 {
2221   if (!check_socket (socket, NULL))
2222     return 0;
2223
2224 #ifdef G_OS_WIN32
2225   {
2226     GIOCondition current_condition;
2227
2228     condition |= G_IO_ERR | G_IO_HUP;
2229
2230     add_condition_watch (socket, &condition);
2231     current_condition = update_condition (socket);
2232     remove_condition_watch (socket, &condition);
2233     return condition & current_condition;
2234   }
2235 #else
2236   {
2237     GPollFD poll_fd;
2238     gint result;
2239     poll_fd.fd = socket->priv->fd;
2240     poll_fd.events = condition;
2241
2242     do
2243       result = g_poll (&poll_fd, 1, 0);
2244     while (result == -1 && get_socket_errno () == EINTR);
2245
2246     return poll_fd.revents;
2247   }
2248 #endif
2249 }
2250
2251 /**
2252  * g_socket_condition_wait:
2253  * @socket: a #GSocket
2254  * @condition: a #GIOCondition mask to wait for
2255  * @cancellable: a #GCancellable, or %NULL
2256  * @error: a #GError pointer, or %NULL
2257  *
2258  * Waits for @condition to become true on @socket.  When the condition
2259  * becomes true, %TRUE is returned.
2260  *
2261  * If @cancellable is cancelled before the condition becomes true then
2262  * %FALSE is returned and @error, if non-%NULL, is set to %G_IO_ERROR_CANCELLED.
2263  *
2264  * Returns: %TRUE if the condition was met, %FALSE otherwise
2265  *
2266  * Since: 2.22
2267  **/
2268 gboolean
2269 g_socket_condition_wait (GSocket       *socket,
2270                          GIOCondition   condition,
2271                          GCancellable  *cancellable,
2272                          GError       **error)
2273 {
2274   if (!check_socket (socket, error))
2275     return FALSE;
2276
2277   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2278     return FALSE;
2279
2280 #ifdef G_OS_WIN32
2281   {
2282     GIOCondition current_condition;
2283     WSAEVENT events[2];
2284     DWORD res;
2285     GPollFD cancel_fd;
2286     int num_events;
2287
2288     /* Always check these */
2289     condition |=  G_IO_ERR | G_IO_HUP;
2290
2291     add_condition_watch (socket, &condition);
2292
2293     num_events = 0;
2294     events[num_events++] = socket->priv->event;
2295
2296     if (cancellable)
2297       {
2298         g_cancellable_make_pollfd (cancellable, &cancel_fd);
2299         events[num_events++] = (WSAEVENT)cancel_fd.fd;
2300       }
2301
2302     current_condition = update_condition (socket);
2303     while ((condition & current_condition) == 0)
2304       {
2305         res = WSAWaitForMultipleEvents(num_events, events,
2306                                        FALSE, WSA_INFINITE, FALSE);
2307         if (res == WSA_WAIT_FAILED)
2308           {
2309             int errsv = get_socket_errno ();
2310
2311             g_set_error (error, G_IO_ERROR,
2312                          socket_io_error_from_errno (errsv),
2313                          _("Waiting for socket condition: %s"),
2314                          socket_strerror (errsv));
2315             break;
2316           }
2317
2318         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2319           break;
2320
2321         current_condition = update_condition (socket);
2322       }
2323     remove_condition_watch (socket, &condition);
2324
2325     return (condition & current_condition) != 0;
2326   }
2327 #else
2328   {
2329     GPollFD poll_fd[2];
2330     gint result;
2331     gint num;
2332
2333     poll_fd[0].fd = socket->priv->fd;
2334     poll_fd[0].events = condition;
2335     num = 1;
2336
2337     if (cancellable)
2338       {
2339         g_cancellable_make_pollfd (cancellable, &poll_fd[1]);
2340         num++;
2341       }
2342
2343     do
2344       result = g_poll (poll_fd, num, -1);
2345     while (result == -1 && get_socket_errno () == EINTR);
2346
2347     return cancellable == NULL ||
2348       !g_cancellable_set_error_if_cancelled (cancellable, error);
2349   }
2350   #endif
2351 }
2352
2353 /**
2354  * g_socket_send_to:
2355  * @socket: a #GSocket
2356  * @address: a #GSocketAddress, or %NULL
2357  * @vectors: an array of #GOutputVector structs
2358  * @num_vectors: the number of elements in @vectors, or -1
2359  * @messages: a pointer to an array of #GSocketControlMessages, or
2360  *   %NULL.
2361  * @num_messages: number of elements in @messages, or -1.
2362  * @flags: an int containing #GSocketMsgFlags flags
2363  * @error: #GError for error reporting, or %NULL to ignore.
2364  *
2365  * Send data to @address on @socket.  This is the most complicated and
2366  * fully-featured version of this call. For easier use, see
2367  * g_socket_send() and g_socket_send_to().
2368  *
2369  * If @address is %NULL then the message is sent to the default receiver
2370  * (set by g_socket_connect()).
2371  *
2372  * @vector must point to an array of #GOutputVector structs and
2373  * @num_vectors must be the length of this array.  These structs
2374  * describe the buffers that the sent data will be gathered from.
2375  * If @num_vector is -1, then @vector is assumed to be terminated
2376  * by a #GOutputVector with a %NULL buffer pointer.
2377  *
2378  *
2379  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2380  * #GSocketControlMessage instances. These correspond to the control
2381  * messages to be sent on the socket.
2382  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2383  * array.
2384  *
2385  * @flags modify how the message sent. The commonly available arguments
2386  * for this is available in the #GSocketMsgFlags enum, but the
2387  * values there are the same as the system values, and the flags
2388  * are passed in as-is, so you can pass in system specific flags too.
2389  *
2390  * If the socket is in blocking mode the call will block until there is
2391  * space for the data in the socket queue. If there is no space available
2392  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2393  * will be returned. To be notified of available space, wait for the %G_IO_OUT
2394  * condition.
2395  *
2396  * Note that on Windows you can't rely on a %G_IO_OUT condition
2397  * not producing a %G_IO_ERROR_WOULD_BLOCK error, as this is how Winsock
2398  * write notification works. However, robust apps should always be able to
2399  * handle this since it can easily appear in other cases too.
2400  *
2401  * On error -1 is returned and @error is set accordingly.
2402  *
2403  * Returns: Number of bytes read, or -1 on error
2404  *
2405  * Since: 2.22
2406  **/
2407 gssize
2408 g_socket_send_message (GSocket                *socket,
2409                        GSocketAddress         *address,
2410                        GOutputVector          *vectors,
2411                        gint                    num_vectors,
2412                        GSocketControlMessage **messages,
2413                        gint                    num_messages,
2414                        gint                    flags,
2415                        GError                **error)
2416 {
2417   GOutputVector one_vector;
2418   char zero;
2419
2420   if (!check_socket (socket, error))
2421     return -1;
2422
2423   if (num_vectors == -1)
2424     {
2425       for (num_vectors = 0;
2426            vectors[num_vectors].buffer != NULL;
2427            num_vectors++)
2428         ;
2429     }
2430
2431   if (num_messages == -1)
2432     {
2433       for (num_messages = 0;
2434            messages != NULL && messages[num_messages] != NULL;
2435            num_messages++)
2436         ;
2437     }
2438
2439   if (num_vectors == 0)
2440     {
2441       zero = '\0';
2442
2443       one_vector.buffer = &zero;
2444       one_vector.size = 1;
2445       num_vectors = 1;
2446       vectors = &one_vector;
2447     }
2448
2449 #ifndef G_OS_WIN32
2450   {
2451     struct msghdr msg;
2452     gssize result;
2453
2454     /* name */
2455     if (address)
2456       {
2457         msg.msg_namelen = g_socket_address_get_native_size (address);
2458         msg.msg_name = g_alloca (msg.msg_namelen);
2459         g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen);
2460       }
2461
2462     /* iov */
2463     {
2464       /* this entire expression will be evaluated at compile time */
2465       if (sizeof *msg.msg_iov == sizeof *vectors &&
2466           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2467           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2468           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2469           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2470           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2471           G_STRUCT_OFFSET (GOutputVector, size))
2472         /* ABI is compatible */
2473         {
2474           msg.msg_iov = (struct iovec *) vectors;
2475           msg.msg_iovlen = num_vectors;
2476         }
2477       else
2478         /* ABI is incompatible */
2479         {
2480           gint i;
2481
2482           msg.msg_iov = g_newa (struct iovec, num_vectors);
2483           for (i = 0; i < num_vectors; i++)
2484             {
2485               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2486               msg.msg_iov[i].iov_len = vectors[i].size;
2487             }
2488           msg.msg_iovlen = num_vectors;
2489         }
2490     }
2491
2492     /* control */
2493     {
2494       struct cmsghdr *cmsg;
2495       gint i;
2496
2497       msg.msg_controllen = 0;
2498       for (i = 0; i < num_messages; i++)
2499         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2500
2501       msg.msg_control = g_alloca (msg.msg_controllen);
2502
2503       cmsg = CMSG_FIRSTHDR (&msg);
2504       for (i = 0; i < num_messages; i++)
2505         {
2506           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2507           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2508           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2509           g_socket_control_message_serialize (messages[i],
2510                                               CMSG_DATA (cmsg));
2511           cmsg = CMSG_NXTHDR (&msg, cmsg);
2512         }
2513       g_assert (cmsg == NULL);
2514     }
2515
2516     while (1)
2517       {
2518         if (socket->priv->blocking &&
2519             !g_socket_condition_wait (socket,
2520                                       G_IO_OUT, NULL, error))
2521           return -1;
2522
2523         result = sendmsg (socket->priv->fd, &msg, flags);
2524         if (result < 0)
2525           {
2526             int errsv = get_socket_errno ();
2527
2528             if (errsv == EINTR)
2529               continue;
2530
2531             if (socket->priv->blocking &&
2532                 (errsv == EWOULDBLOCK ||
2533                  errsv == EAGAIN))
2534               continue;
2535
2536             g_set_error (error, G_IO_ERROR,
2537                          socket_io_error_from_errno (errsv),
2538                          _("Error sending message: %s"), socket_strerror (errsv));
2539
2540             return -1;
2541           }
2542         break;
2543       }
2544
2545     return result;
2546   }
2547 #else
2548   {
2549     struct sockaddr_storage addr;
2550     guint addrlen;
2551     DWORD bytes_sent;
2552     int result;
2553     WSABUF *bufs;
2554     gint i;
2555
2556     /* Win32 doesn't support control messages.
2557        Actually this is possible for raw and datagram sockets
2558        via WSASendMessage on Vista or later, but that doesn't
2559        seem very useful */
2560     if (num_messages != 0)
2561       {
2562         g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2563                      _("GSocketControlMessage not supported on windows"));
2564         return -1;
2565       }
2566
2567     /* iov */
2568     bufs = g_newa (WSABUF, num_vectors);
2569     for (i = 0; i < num_vectors; i++)
2570       {
2571         bufs[i].buf = (char *)vectors[i].buffer;
2572         bufs[i].len = (gulong)vectors[i].size;
2573       }
2574
2575     /* name */
2576     if (address)
2577       {
2578         addrlen = g_socket_address_get_native_size (address);
2579         g_socket_address_to_native (address, &addr, sizeof addr);
2580       }
2581
2582     while (1)
2583       {
2584         if (socket->priv->blocking &&
2585             !g_socket_condition_wait (socket,
2586                                       G_IO_OUT, NULL, error))
2587           return -1;
2588
2589         if (address)
2590           result = WSASendTo (socket->priv->fd,
2591                               bufs, num_vectors,
2592                               &bytes_sent, flags,
2593                               (const struct sockaddr *)&addr, addrlen,
2594                               NULL, NULL);
2595         else
2596           result = WSASend (socket->priv->fd,
2597                             bufs, num_vectors,
2598                             &bytes_sent, flags,
2599                             NULL, NULL);
2600
2601         if (result != 0)
2602           {
2603             int errsv = get_socket_errno ();
2604
2605             if (errsv == WSAEINTR)
2606               continue;
2607
2608             if (errsv == WSAEWOULDBLOCK)
2609               win32_unset_event_mask (socket, FD_WRITE);
2610
2611             if (socket->priv->blocking &&
2612                 errsv == WSAEWOULDBLOCK)
2613               continue;
2614
2615             g_set_error (error, G_IO_ERROR,
2616                          socket_io_error_from_errno (errsv),
2617                          _("Error sending message: %s"), socket_strerror (errsv));
2618
2619             return -1;
2620           }
2621         break;
2622       }
2623
2624     return bytes_sent;
2625   }
2626 #endif
2627 }
2628
2629 /**
2630  * g_socket_receive_message:
2631  * @socket: a #GSocket
2632  * @address: a pointer to a #GSocketAddress pointer, or %NULL
2633  * @vectors: an array of #GInputVector structs
2634  * @num_vectors: the number of elements in @vectors, or -1
2635  * @messages: a pointer which will be filled with an array of
2636  *     #GSocketControlMessages, or %NULL
2637  * @num_messages: a pointer which will be filled with the number of
2638  *    elements in @messages, or %NULL
2639  * @flags: a pointer to an int containing #GSocketMsgFlags flags
2640  * @error: a #GError pointer, or %NULL
2641  *
2642  * Receive data from a socket.  This is the most complicated and
2643  * fully-featured version of this call. For easier use, see
2644  * g_socket_receive() and g_socket_receive_from().
2645  *
2646  * If @address is non-%NULL then @address will be set equal to the
2647  * source address of the received packet.
2648  * @address is owned by the caller.
2649  *
2650  * @vector must point to an array of #GInputVector structs and
2651  * @num_vectors must be the length of this array.  These structs
2652  * describe the buffers that received data will be scattered into.
2653  * If @num_vector is -1, then @vector is assumed to be terminated
2654  * by a #GInputVector with a %NULL buffer pointer.
2655  *
2656  * As a special case, if the size of the array is zero (in which case,
2657  * @vectors may of course be %NULL), then a single byte is received
2658  * and discarded.  This is to facilitate the common practice of
2659  * sending a single '\0' byte for the purposes of transferring
2660  * ancillary data.
2661  *
2662  * @messages, if non-%NULL, is taken to point to a pointer that will
2663  * be set to point to a newly-allocated array of
2664  * #GSocketControlMessage instances.  These correspond to the control
2665  * messages received from the kernel, one #GSocketControlMessage per
2666  * message from the kernel.  This array is %NULL-terminated and must be
2667  * freed by the caller using g_free().
2668  *
2669  * @num_messages, if non-%NULL, will be set to the number of control
2670  * messages received.
2671  *
2672  * If both @messages and @num_messages are non-%NULL, then
2673  * @num_messages gives the number of #GSocketControlMessage instances
2674  * in @messages (ie: not including the %NULL terminator).
2675  *
2676  * @flags is an in/out parameter. The commonly available arguments
2677  * for this is available in the #GSocketMsgFlags enum, but the
2678  * values there are the same as the system values, and the flags
2679  * are passed in as-is, so you can pass in system specific flags too.
2680  *
2681  * If the socket is in blocking mode the call will block until there is
2682  * some data to receive or there is an error. If there is no data available
2683  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2684  * will be returned. To be notified of available data, wait for the %G_IO_IN
2685  * condition.
2686  *
2687  * On error -1 is returned and @error is set accordingly.
2688  *
2689  * Returns: Number of bytes read, or -1 on error
2690  *
2691  * Since: 2.22
2692  **/
2693 gssize
2694 g_socket_receive_message (GSocket                 *socket,
2695                           GSocketAddress         **address,
2696                           GInputVector            *vectors,
2697                           gint                     num_vectors,
2698                           GSocketControlMessage ***messages,
2699                           gint                    *num_messages,
2700                           gint                    *flags,
2701                           GError                 **error)
2702 {
2703   GInputVector one_vector;
2704   char one_byte;
2705
2706   if (!check_socket (socket, error))
2707     return -1;
2708
2709   if (num_vectors == -1)
2710     {
2711       for (num_vectors = 0;
2712            vectors[num_vectors].buffer != NULL;
2713            num_vectors++)
2714         ;
2715     }
2716
2717   if (num_vectors == 0)
2718     {
2719       one_vector.buffer = &one_byte;
2720       one_vector.size = 1;
2721       num_vectors = 1;
2722       vectors = &one_vector;
2723     }
2724
2725 #ifndef G_OS_WIN32
2726   {
2727     struct msghdr msg;
2728     gssize result;
2729     struct sockaddr_storage one_sockaddr;
2730
2731     /* name */
2732     if (address)
2733       {
2734         msg.msg_name = &one_sockaddr;
2735         msg.msg_namelen = sizeof (struct sockaddr_storage);
2736       }
2737     else
2738       {
2739         msg.msg_name = NULL;
2740         msg.msg_namelen = 0;
2741       }
2742
2743     /* iov */
2744     /* this entire expression will be evaluated at compile time */
2745     if (sizeof *msg.msg_iov == sizeof *vectors &&
2746         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2747         G_STRUCT_OFFSET (struct iovec, iov_base) ==
2748         G_STRUCT_OFFSET (GInputVector, buffer) &&
2749         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2750         G_STRUCT_OFFSET (struct iovec, iov_len) ==
2751         G_STRUCT_OFFSET (GInputVector, size))
2752       /* ABI is compatible */
2753       {
2754         msg.msg_iov = (struct iovec *) vectors;
2755         msg.msg_iovlen = num_vectors;
2756       }
2757     else
2758       /* ABI is incompatible */
2759       {
2760         gint i;
2761
2762         msg.msg_iov = g_newa (struct iovec, num_vectors);
2763         for (i = 0; i < num_vectors; i++)
2764           {
2765             msg.msg_iov[i].iov_base = vectors[i].buffer;
2766             msg.msg_iov[i].iov_len = vectors[i].size;
2767           }
2768         msg.msg_iovlen = num_vectors;
2769       }
2770
2771     /* control */
2772     msg.msg_control = g_alloca (2048);
2773     msg.msg_controllen = 2048;
2774
2775     /* flags */
2776     if (flags != NULL)
2777       msg.msg_flags = *flags;
2778     else
2779       msg.msg_flags = 0;
2780
2781     /* do it */
2782     while (1)
2783       {
2784         if (socket->priv->blocking &&
2785             !g_socket_condition_wait (socket,
2786                                       G_IO_IN, NULL, error))
2787           return -1;
2788
2789         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
2790
2791         if (result < 0)
2792           {
2793             int errsv = get_socket_errno ();
2794
2795             if (errsv == EINTR)
2796               continue;
2797
2798             if (socket->priv->blocking &&
2799                 (errsv == EWOULDBLOCK ||
2800                  errsv == EAGAIN))
2801               continue;
2802
2803             g_set_error (error, G_IO_ERROR,
2804                          socket_io_error_from_errno (errsv),
2805                          _("Error receiving message: %s"), socket_strerror (errsv));
2806
2807             return -1;
2808           }
2809         break;
2810       }
2811
2812     /* decode address */
2813     if (address != NULL)
2814       {
2815         if (msg.msg_namelen > 0)
2816           *address = g_socket_address_new_from_native (msg.msg_name,
2817                                                        msg.msg_namelen);
2818         else
2819           *address = NULL;
2820       }
2821
2822     /* decode control messages */
2823     {
2824       GSocketControlMessage **my_messages = NULL;
2825       gint allocated = 0, index = 0;
2826       const gchar *scm_pointer;
2827       struct cmsghdr *cmsg;
2828       gsize scm_size;
2829
2830       scm_pointer = (const gchar *) msg.msg_control;
2831       scm_size = msg.msg_controllen;
2832
2833       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
2834         {
2835           GSocketControlMessage *message;
2836
2837           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
2838                                                           cmsg->cmsg_type,
2839                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
2840                                                           CMSG_DATA (cmsg));
2841           if (message == NULL)
2842             /* We've already spewed about the problem in the
2843                deserialization code, so just continue */
2844             continue;
2845
2846           if (index == allocated)
2847             {
2848               /* estimated 99% case: exactly 1 control message */
2849               allocated = MIN (allocated * 2, 1);
2850               my_messages = g_new (GSocketControlMessage *, (allocated + 1));
2851               allocated = 1;
2852             }
2853
2854           my_messages[index++] = message;
2855         }
2856
2857       if (num_messages)
2858         *num_messages = index;
2859
2860       if (messages)
2861         {
2862           my_messages[index++] = NULL;
2863           *messages = my_messages;
2864         }
2865       else
2866         {
2867           gint i;
2868
2869           /* free all those messages we just constructed.
2870            * we have to do it this way if the user ignores the
2871            * messages so that we will close any received fds.
2872            */
2873           for (i = 0; i < index; i++)
2874             g_object_unref (my_messages[i]);
2875           g_free (my_messages);
2876         }
2877     }
2878
2879     /* capture the flags */
2880     if (flags != NULL)
2881       *flags = msg.msg_flags;
2882
2883     return result;
2884   }
2885 #else
2886   {
2887     struct sockaddr_storage addr;
2888     int addrlen;
2889     DWORD bytes_received;
2890     DWORD win_flags;
2891     int result;
2892     WSABUF *bufs;
2893     gint i;
2894
2895     /* iov */
2896     bufs = g_newa (WSABUF, num_vectors);
2897     for (i = 0; i < num_vectors; i++)
2898       {
2899         bufs[i].buf = (char *)vectors[i].buffer;
2900         bufs[i].len = (gulong)vectors[i].size;
2901       }
2902
2903     /* flags */
2904     if (flags != NULL)
2905       win_flags = *flags;
2906     else
2907       win_flags = 0;
2908
2909     /* do it */
2910     while (1)
2911       {
2912         if (socket->priv->blocking &&
2913             !g_socket_condition_wait (socket,
2914                                       G_IO_IN, NULL, error))
2915           return -1;
2916
2917         addrlen = sizeof addr;
2918         if (address)
2919           result = WSARecvFrom (socket->priv->fd,
2920                                 bufs, num_vectors,
2921                                 &bytes_received, &win_flags,
2922                                 (struct sockaddr *)&addr, &addrlen,
2923                                 NULL, NULL);
2924         else
2925           result = WSARecv (socket->priv->fd,
2926                             bufs, num_vectors,
2927                             &bytes_received, &win_flags,
2928                             NULL, NULL);
2929         if (result != 0)
2930           {
2931             int errsv = get_socket_errno ();
2932
2933             if (errsv == WSAEINTR)
2934               continue;
2935
2936             win32_unset_event_mask (socket, FD_READ);
2937
2938             if (socket->priv->blocking &&
2939                 errsv == WSAEWOULDBLOCK)
2940               continue;
2941
2942             g_set_error (error, G_IO_ERROR,
2943                          socket_io_error_from_errno (errsv),
2944                          _("Error receiving message: %s"), socket_strerror (errsv));
2945
2946             return -1;
2947           }
2948         win32_unset_event_mask (socket, FD_READ);
2949         break;
2950       }
2951
2952     /* decode address */
2953     if (address != NULL)
2954       {
2955         if (addrlen > 0)
2956           *address = g_socket_address_new_from_native (&addr, addrlen);
2957         else
2958           *address = NULL;
2959       }
2960
2961     /* capture the flags */
2962     if (flags != NULL)
2963       *flags = win_flags;
2964
2965     return bytes_received;
2966   }
2967 #endif
2968 }
2969
2970 #define __G_SOCKET_C__
2971 #include "gioaliasdef.c"