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