GSocket: Add multicast-related functions
[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       join_group,
1692                                     GError       **error)
1693 {
1694   const guint8 *native_addr;
1695   gint optname, result;
1696
1697   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1698   g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
1699   g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
1700   g_return_val_if_fail (g_inet_address_get_family (group) == socket->priv->family, FALSE);
1701
1702   if (!check_socket (socket, error))
1703     return FALSE;
1704
1705   native_addr = g_inet_address_to_bytes (group);
1706   if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1707     {
1708       struct ip_mreq mc_req;
1709
1710       memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1711       mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1712
1713       optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1714       result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1715                            &mc_req, sizeof (mc_req));
1716     }
1717   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1718     {
1719       struct ipv6_mreq mc_req_ipv6;
1720
1721       memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1722       mc_req_ipv6.ipv6mr_interface = 0;
1723
1724       optname = join_group ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP;
1725       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
1726                            &mc_req_ipv6, sizeof (mc_req_ipv6));
1727     }
1728   else
1729     g_return_val_if_reached (FALSE);
1730
1731   if (result < 0)
1732     {
1733       int errsv = get_socket_errno ();
1734
1735       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1736                    join_group ?
1737                    _("Error joining multicast group: %s") :
1738                    _("Error leaving multicast group: %s"),
1739                    socket_strerror (errsv));
1740       return FALSE;
1741     }
1742
1743   return TRUE;
1744 }
1745
1746 /**
1747  * g_socket_join_multicast_group:
1748  * @socket: a #GSocket.
1749  * @group: a #GInetAddress specifying the group address to join.
1750  * @error: #GError for error reporting, or %NULL to ignore.
1751  *
1752  * Registers @socket to receive multicast messages sent to @group.
1753  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
1754  * been bound to an appropriate interface and port with
1755  * g_socket_bind().
1756  *
1757  * Returns: %TRUE on success, %FALSE on error.
1758  *
1759  * Since: 2.32
1760  */
1761 gboolean
1762 g_socket_join_multicast_group (GSocket       *socket,
1763                                GInetAddress  *group,
1764                                GError       **error)
1765 {
1766   return g_socket_multicast_group_operation (socket, group, TRUE, error);
1767 }
1768
1769 /**
1770  * g_socket_leave_multicast_group:
1771  * @socket: a #GSocket.
1772  * @group: a #GInetAddress specifying the group address to leave.
1773  * @error: #GError for error reporting, or %NULL to ignore.
1774  *
1775  * Removes @socket from the multicast group @group (while still
1776  * allowing it to receive unicast messages).
1777  *
1778  * Returns: %TRUE on success, %FALSE on error.
1779  *
1780  * Since: 2.32
1781  */
1782 gboolean
1783 g_socket_leave_multicast_group (GSocket       *socket,
1784                                 GInetAddress  *group,
1785                                 GError       **error)
1786 {
1787   return g_socket_multicast_group_operation (socket, group, FALSE, error);
1788 }
1789
1790 /**
1791  * g_socket_speaks_ipv4:
1792  * @socket: a #GSocket
1793  *
1794  * Checks if a socket is capable of speaking IPv4.
1795  *
1796  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
1797  * and under some combinations of circumstances IPv6 sockets are also
1798  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
1799  * information.
1800  *
1801  * No other types of sockets are currently considered as being capable
1802  * of speaking IPv4.
1803  *
1804  * Returns: %TRUE if this socket can be used with IPv4.
1805  *
1806  * Since: 2.22
1807  **/
1808 gboolean
1809 g_socket_speaks_ipv4 (GSocket *socket)
1810 {
1811   switch (socket->priv->family)
1812     {
1813     case G_SOCKET_FAMILY_IPV4:
1814       return TRUE;
1815
1816     case G_SOCKET_FAMILY_IPV6:
1817 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1818       {
1819         guint sizeof_int = sizeof (int);
1820         gint v6_only;
1821
1822         if (getsockopt (socket->priv->fd,
1823                         IPPROTO_IPV6, IPV6_V6ONLY,
1824                         &v6_only, &sizeof_int) != 0)
1825           return FALSE;
1826
1827         return !v6_only;
1828       }
1829 #else
1830       return FALSE;
1831 #endif
1832
1833     default:
1834       return FALSE;
1835     }
1836 }
1837
1838 /**
1839  * g_socket_accept:
1840  * @socket: a #GSocket.
1841  * @cancellable: (allow-none): a %GCancellable or %NULL
1842  * @error: #GError for error reporting, or %NULL to ignore.
1843  *
1844  * Accept incoming connections on a connection-based socket. This removes
1845  * the first outstanding connection request from the listening socket and
1846  * creates a #GSocket object for it.
1847  *
1848  * The @socket must be bound to a local address with g_socket_bind() and
1849  * must be listening for incoming connections (g_socket_listen()).
1850  *
1851  * If there are no outstanding connections then the operation will block
1852  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1853  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1854  *
1855  * Returns: (transfer full): a new #GSocket, or %NULL on error.
1856  *     Free the returned object with g_object_unref().
1857  *
1858  * Since: 2.22
1859  */
1860 GSocket *
1861 g_socket_accept (GSocket       *socket,
1862                  GCancellable  *cancellable,
1863                  GError       **error)
1864 {
1865   GSocket *new_socket;
1866   gint ret;
1867
1868   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1869
1870   if (!check_socket (socket, error))
1871     return NULL;
1872
1873   while (TRUE)
1874     {
1875       if (socket->priv->blocking &&
1876           !g_socket_condition_wait (socket,
1877                                     G_IO_IN, cancellable, error))
1878         return NULL;
1879
1880       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1881         {
1882           int errsv = get_socket_errno ();
1883
1884           win32_unset_event_mask (socket, FD_ACCEPT);
1885
1886           if (errsv == EINTR)
1887             continue;
1888
1889           if (socket->priv->blocking)
1890             {
1891 #ifdef WSAEWOULDBLOCK
1892               if (errsv == WSAEWOULDBLOCK)
1893                 continue;
1894 #else
1895               if (errsv == EWOULDBLOCK ||
1896                   errsv == EAGAIN)
1897                 continue;
1898 #endif
1899             }
1900
1901           g_set_error (error, G_IO_ERROR,
1902                        socket_io_error_from_errno (errsv),
1903                        _("Error accepting connection: %s"), socket_strerror (errsv));
1904           return NULL;
1905         }
1906       break;
1907     }
1908
1909   win32_unset_event_mask (socket, FD_ACCEPT);
1910
1911 #ifdef G_OS_WIN32
1912   {
1913     /* The socket inherits the accepting sockets event mask and even object,
1914        we need to remove that */
1915     WSAEventSelect (ret, NULL, 0);
1916   }
1917 #else
1918   {
1919     int flags;
1920
1921     /* We always want to set close-on-exec to protect users. If you
1922        need to so some weird inheritance to exec you can re-enable this
1923        using lower level hacks with g_socket_get_fd(). */
1924     flags = fcntl (ret, F_GETFD, 0);
1925     if (flags != -1 &&
1926         (flags & FD_CLOEXEC) == 0)
1927       {
1928         flags |= FD_CLOEXEC;
1929         fcntl (ret, F_SETFD, flags);
1930       }
1931   }
1932 #endif
1933
1934   new_socket = g_socket_new_from_fd (ret, error);
1935   if (new_socket == NULL)
1936     {
1937 #ifdef G_OS_WIN32
1938       closesocket (ret);
1939 #else
1940       close (ret);
1941 #endif
1942     }
1943   else
1944     new_socket->priv->protocol = socket->priv->protocol;
1945
1946   return new_socket;
1947 }
1948
1949 /**
1950  * g_socket_connect:
1951  * @socket: a #GSocket.
1952  * @address: a #GSocketAddress specifying the remote address.
1953  * @cancellable: (allow-none): a %GCancellable or %NULL
1954  * @error: #GError for error reporting, or %NULL to ignore.
1955  *
1956  * Connect the socket to the specified remote address.
1957  *
1958  * For connection oriented socket this generally means we attempt to make
1959  * a connection to the @address. For a connection-less socket it sets
1960  * the default address for g_socket_send() and discards all incoming datagrams
1961  * from other sources.
1962  *
1963  * Generally connection oriented sockets can only connect once, but
1964  * connection-less sockets can connect multiple times to change the
1965  * default address.
1966  *
1967  * If the connect call needs to do network I/O it will block, unless
1968  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1969  * and the user can be notified of the connection finishing by waiting
1970  * for the G_IO_OUT condition. The result of the connection must then be
1971  * checked with g_socket_check_connect_result().
1972  *
1973  * Returns: %TRUE if connected, %FALSE on error.
1974  *
1975  * Since: 2.22
1976  */
1977 gboolean
1978 g_socket_connect (GSocket         *socket,
1979                   GSocketAddress  *address,
1980                   GCancellable    *cancellable,
1981                   GError         **error)
1982 {
1983   struct sockaddr_storage buffer;
1984
1985   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1986
1987   if (!check_socket (socket, error))
1988     return FALSE;
1989
1990   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1991     return FALSE;
1992
1993   if (socket->priv->remote_address)
1994     g_object_unref (socket->priv->remote_address);
1995   socket->priv->remote_address = g_object_ref (address);
1996
1997   while (1)
1998     {
1999       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2000                    g_socket_address_get_native_size (address)) < 0)
2001         {
2002           int errsv = get_socket_errno ();
2003
2004           if (errsv == EINTR)
2005             continue;
2006
2007 #ifndef G_OS_WIN32
2008           if (errsv == EINPROGRESS)
2009 #else
2010           if (errsv == WSAEWOULDBLOCK)
2011 #endif
2012             {
2013               if (socket->priv->blocking)
2014                 {
2015                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2016                     {
2017                       if (g_socket_check_connect_result (socket, error))
2018                         break;
2019                     }
2020                 }
2021               else
2022                 {
2023                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2024                                        _("Connection in progress"));
2025                   socket->priv->connect_pending = TRUE;
2026                 }
2027             }
2028           else
2029             g_set_error_literal (error, G_IO_ERROR,
2030                                  socket_io_error_from_errno (errsv),
2031                                  socket_strerror (errsv));
2032
2033           return FALSE;
2034         }
2035       break;
2036     }
2037
2038   win32_unset_event_mask (socket, FD_CONNECT);
2039
2040   socket->priv->connected = TRUE;
2041
2042   return TRUE;
2043 }
2044
2045 /**
2046  * g_socket_check_connect_result:
2047  * @socket: a #GSocket
2048  * @error: #GError for error reporting, or %NULL to ignore.
2049  *
2050  * Checks and resets the pending connect error for the socket.
2051  * This is used to check for errors when g_socket_connect() is
2052  * used in non-blocking mode.
2053  *
2054  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2055  *
2056  * Since: 2.22
2057  */
2058 gboolean
2059 g_socket_check_connect_result (GSocket  *socket,
2060                                GError  **error)
2061 {
2062   guint optlen;
2063   int value;
2064
2065   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2066
2067   if (!check_socket (socket, error))
2068     return FALSE;
2069
2070   optlen = sizeof (value);
2071   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2072     {
2073       int errsv = get_socket_errno ();
2074
2075       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2076                    _("Unable to get pending error: %s"), socket_strerror (errsv));
2077       return FALSE;
2078     }
2079
2080   if (value != 0)
2081     {
2082       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2083                            socket_strerror (value));
2084       if (socket->priv->remote_address)
2085         {
2086           g_object_unref (socket->priv->remote_address);
2087           socket->priv->remote_address = NULL;
2088         }
2089       return FALSE;
2090     }
2091
2092   socket->priv->connected = TRUE;
2093   return TRUE;
2094 }
2095
2096 /**
2097  * g_socket_receive:
2098  * @socket: a #GSocket
2099  * @buffer: a buffer to read data into (which should be at least @size
2100  *     bytes long).
2101  * @size: the number of bytes you want to read from the socket
2102  * @cancellable: (allow-none): a %GCancellable or %NULL
2103  * @error: #GError for error reporting, or %NULL to ignore.
2104  *
2105  * Receive data (up to @size bytes) from a socket. This is mainly used by
2106  * connection-oriented sockets; it is identical to g_socket_receive_from()
2107  * with @address set to %NULL.
2108  *
2109  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2110  * g_socket_receive() will always read either 0 or 1 complete messages from
2111  * the socket. If the received message is too large to fit in @buffer, then
2112  * the data beyond @size bytes will be discarded, without any explicit
2113  * indication that this has occurred.
2114  *
2115  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2116  * number of bytes, up to @size. If more than @size bytes have been
2117  * received, the additional data will be returned in future calls to
2118  * g_socket_receive().
2119  *
2120  * If the socket is in blocking mode the call will block until there
2121  * is some data to receive, the connection is closed, or there is an
2122  * error. If there is no data available and the socket is in
2123  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2124  * returned. To be notified when data is available, wait for the
2125  * %G_IO_IN condition.
2126  *
2127  * On error -1 is returned and @error is set accordingly.
2128  *
2129  * Returns: Number of bytes read, or 0 if the connection was closed by
2130  * the peer, or -1 on error
2131  *
2132  * Since: 2.22
2133  */
2134 gssize
2135 g_socket_receive (GSocket       *socket,
2136                   gchar         *buffer,
2137                   gsize          size,
2138                   GCancellable  *cancellable,
2139                   GError       **error)
2140 {
2141   return g_socket_receive_with_blocking (socket, buffer, size,
2142                                          socket->priv->blocking,
2143                                          cancellable, error);
2144 }
2145
2146 /**
2147  * g_socket_receive_with_blocking:
2148  * @socket: a #GSocket
2149  * @buffer: a buffer to read data into (which should be at least @size
2150  *     bytes long).
2151  * @size: the number of bytes you want to read from the socket
2152  * @blocking: whether to do blocking or non-blocking I/O
2153  * @cancellable: (allow-none): a %GCancellable or %NULL
2154  * @error: #GError for error reporting, or %NULL to ignore.
2155  *
2156  * This behaves exactly the same as g_socket_receive(), except that
2157  * the choice of blocking or non-blocking behavior is determined by
2158  * the @blocking argument rather than by @socket's properties.
2159  *
2160  * Returns: Number of bytes read, or 0 if the connection was closed by
2161  * the peer, or -1 on error
2162  *
2163  * Since: 2.26
2164  */
2165 gssize
2166 g_socket_receive_with_blocking (GSocket       *socket,
2167                                 gchar         *buffer,
2168                                 gsize          size,
2169                                 gboolean       blocking,
2170                                 GCancellable  *cancellable,
2171                                 GError       **error)
2172 {
2173   gssize ret;
2174
2175   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2176
2177   if (!check_socket (socket, error))
2178     return -1;
2179
2180   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2181     return -1;
2182
2183   while (1)
2184     {
2185       if (blocking &&
2186           !g_socket_condition_wait (socket,
2187                                     G_IO_IN, cancellable, error))
2188         return -1;
2189
2190       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2191         {
2192           int errsv = get_socket_errno ();
2193
2194           if (errsv == EINTR)
2195             continue;
2196
2197           if (blocking)
2198             {
2199 #ifdef WSAEWOULDBLOCK
2200               if (errsv == WSAEWOULDBLOCK)
2201                 continue;
2202 #else
2203               if (errsv == EWOULDBLOCK ||
2204                   errsv == EAGAIN)
2205                 continue;
2206 #endif
2207             }
2208
2209           win32_unset_event_mask (socket, FD_READ);
2210
2211           g_set_error (error, G_IO_ERROR,
2212                        socket_io_error_from_errno (errsv),
2213                        _("Error receiving data: %s"), socket_strerror (errsv));
2214           return -1;
2215         }
2216
2217       win32_unset_event_mask (socket, FD_READ);
2218
2219       break;
2220     }
2221
2222   return ret;
2223 }
2224
2225 /**
2226  * g_socket_receive_from:
2227  * @socket: a #GSocket
2228  * @address: (out) (allow-none): a pointer to a #GSocketAddress
2229  *     pointer, or %NULL
2230  * @buffer: (array length=size) (element-type guint8): a buffer to
2231  *     read data into (which should be at least @size bytes long).
2232  * @size: the number of bytes you want to read from the socket
2233  * @cancellable: (allow-none): a %GCancellable or %NULL
2234  * @error: #GError for error reporting, or %NULL to ignore.
2235  *
2236  * Receive data (up to @size bytes) from a socket.
2237  *
2238  * If @address is non-%NULL then @address will be set equal to the
2239  * source address of the received packet.
2240  * @address is owned by the caller.
2241  *
2242  * See g_socket_receive() for additional information.
2243  *
2244  * Returns: Number of bytes read, or 0 if the connection was closed by
2245  * the peer, or -1 on error
2246  *
2247  * Since: 2.22
2248  */
2249 gssize
2250 g_socket_receive_from (GSocket         *socket,
2251                        GSocketAddress **address,
2252                        gchar           *buffer,
2253                        gsize            size,
2254                        GCancellable    *cancellable,
2255                        GError         **error)
2256 {
2257   GInputVector v;
2258
2259   v.buffer = buffer;
2260   v.size = size;
2261
2262   return g_socket_receive_message (socket,
2263                                    address,
2264                                    &v, 1,
2265                                    NULL, 0, NULL,
2266                                    cancellable,
2267                                    error);
2268 }
2269
2270 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2271  * one, which can be confusing and annoying. So if possible, we want
2272  * to suppress the signal entirely.
2273  */
2274 #ifdef MSG_NOSIGNAL
2275 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2276 #else
2277 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2278 #endif
2279
2280 /**
2281  * g_socket_send:
2282  * @socket: a #GSocket
2283  * @buffer: (array length=size) (element-type guint8): the buffer
2284  *     containing the data to send.
2285  * @size: the number of bytes to send
2286  * @cancellable: (allow-none): a %GCancellable or %NULL
2287  * @error: #GError for error reporting, or %NULL to ignore.
2288  *
2289  * Tries to send @size bytes from @buffer on the socket. This is
2290  * mainly used by connection-oriented sockets; it is identical to
2291  * g_socket_send_to() with @address set to %NULL.
2292  *
2293  * If the socket is in blocking mode the call will block until there is
2294  * space for the data in the socket queue. If there is no space available
2295  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2296  * will be returned. To be notified when space is available, wait for the
2297  * %G_IO_OUT condition. Note though that you may still receive
2298  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2299  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2300  * very common due to the way the underlying APIs work.)
2301  *
2302  * On error -1 is returned and @error is set accordingly.
2303  *
2304  * Returns: Number of bytes written (which may be less than @size), or -1
2305  * on error
2306  *
2307  * Since: 2.22
2308  */
2309 gssize
2310 g_socket_send (GSocket       *socket,
2311                const gchar   *buffer,
2312                gsize          size,
2313                GCancellable  *cancellable,
2314                GError       **error)
2315 {
2316   return g_socket_send_with_blocking (socket, buffer, size,
2317                                       socket->priv->blocking,
2318                                       cancellable, error);
2319 }
2320
2321 /**
2322  * g_socket_send_with_blocking:
2323  * @socket: a #GSocket
2324  * @buffer: (array length=size) (element-type guint8): the buffer
2325  *     containing the data to send.
2326  * @size: the number of bytes to send
2327  * @blocking: whether to do blocking or non-blocking I/O
2328  * @cancellable: (allow-none): a %GCancellable or %NULL
2329  * @error: #GError for error reporting, or %NULL to ignore.
2330  *
2331  * This behaves exactly the same as g_socket_send(), except that
2332  * the choice of blocking or non-blocking behavior is determined by
2333  * the @blocking argument rather than by @socket's properties.
2334  *
2335  * Returns: Number of bytes written (which may be less than @size), or -1
2336  * on error
2337  *
2338  * Since: 2.26
2339  */
2340 gssize
2341 g_socket_send_with_blocking (GSocket       *socket,
2342                              const gchar   *buffer,
2343                              gsize          size,
2344                              gboolean       blocking,
2345                              GCancellable  *cancellable,
2346                              GError       **error)
2347 {
2348   gssize ret;
2349
2350   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2351
2352   if (!check_socket (socket, error))
2353     return -1;
2354
2355   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2356     return -1;
2357
2358   while (1)
2359     {
2360       if (blocking &&
2361           !g_socket_condition_wait (socket,
2362                                     G_IO_OUT, cancellable, error))
2363         return -1;
2364
2365       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2366         {
2367           int errsv = get_socket_errno ();
2368
2369           if (errsv == EINTR)
2370             continue;
2371
2372 #ifdef WSAEWOULDBLOCK
2373           if (errsv == WSAEWOULDBLOCK)
2374             win32_unset_event_mask (socket, FD_WRITE);
2375 #endif
2376
2377           if (blocking)
2378             {
2379 #ifdef WSAEWOULDBLOCK
2380               if (errsv == WSAEWOULDBLOCK)
2381                 continue;
2382 #else
2383               if (errsv == EWOULDBLOCK ||
2384                   errsv == EAGAIN)
2385                 continue;
2386 #endif
2387             }
2388
2389           g_set_error (error, G_IO_ERROR,
2390                        socket_io_error_from_errno (errsv),
2391                        _("Error sending data: %s"), socket_strerror (errsv));
2392           return -1;
2393         }
2394       break;
2395     }
2396
2397   return ret;
2398 }
2399
2400 /**
2401  * g_socket_send_to:
2402  * @socket: a #GSocket
2403  * @address: a #GSocketAddress, or %NULL
2404  * @buffer: (array length=size) (element-type guint8): the buffer
2405  *     containing the data to send.
2406  * @size: the number of bytes to send
2407  * @cancellable: (allow-none): a %GCancellable or %NULL
2408  * @error: #GError for error reporting, or %NULL to ignore.
2409  *
2410  * Tries to send @size bytes from @buffer to @address. If @address is
2411  * %NULL then the message is sent to the default receiver (set by
2412  * g_socket_connect()).
2413  *
2414  * See g_socket_send() for additional information.
2415  *
2416  * Returns: Number of bytes written (which may be less than @size), or -1
2417  * on error
2418  *
2419  * Since: 2.22
2420  */
2421 gssize
2422 g_socket_send_to (GSocket         *socket,
2423                   GSocketAddress  *address,
2424                   const gchar     *buffer,
2425                   gsize            size,
2426                   GCancellable    *cancellable,
2427                   GError         **error)
2428 {
2429   GOutputVector v;
2430
2431   v.buffer = buffer;
2432   v.size = size;
2433
2434   return g_socket_send_message (socket,
2435                                 address,
2436                                 &v, 1,
2437                                 NULL, 0,
2438                                 0,
2439                                 cancellable,
2440                                 error);
2441 }
2442
2443 /**
2444  * g_socket_shutdown:
2445  * @socket: a #GSocket
2446  * @shutdown_read: whether to shut down the read side
2447  * @shutdown_write: whether to shut down the write side
2448  * @error: #GError for error reporting, or %NULL to ignore.
2449  *
2450  * Shut down part of a full-duplex connection.
2451  *
2452  * If @shutdown_read is %TRUE then the receiving side of the connection
2453  * is shut down, and further reading is disallowed.
2454  *
2455  * If @shutdown_write is %TRUE then the sending side of the connection
2456  * is shut down, and further writing is disallowed.
2457  *
2458  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2459  *
2460  * One example where this is used is graceful disconnect for TCP connections
2461  * where you close the sending side, then wait for the other side to close
2462  * the connection, thus ensuring that the other side saw all sent data.
2463  *
2464  * Returns: %TRUE on success, %FALSE on error
2465  *
2466  * Since: 2.22
2467  */
2468 gboolean
2469 g_socket_shutdown (GSocket   *socket,
2470                    gboolean   shutdown_read,
2471                    gboolean   shutdown_write,
2472                    GError   **error)
2473 {
2474   int how;
2475
2476   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2477
2478   if (!check_socket (socket, error))
2479     return FALSE;
2480
2481   /* Do nothing? */
2482   if (!shutdown_read && !shutdown_write)
2483     return TRUE;
2484
2485 #ifndef G_OS_WIN32
2486   if (shutdown_read && shutdown_write)
2487     how = SHUT_RDWR;
2488   else if (shutdown_read)
2489     how = SHUT_RD;
2490   else
2491     how = SHUT_WR;
2492 #else
2493   if (shutdown_read && shutdown_write)
2494     how = SD_BOTH;
2495   else if (shutdown_read)
2496     how = SD_RECEIVE;
2497   else
2498     how = SD_SEND;
2499 #endif
2500
2501   if (shutdown (socket->priv->fd, how) != 0)
2502     {
2503       int errsv = get_socket_errno ();
2504       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2505                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2506       return FALSE;
2507     }
2508
2509   if (shutdown_read && shutdown_write)
2510     socket->priv->connected = FALSE;
2511
2512   return TRUE;
2513 }
2514
2515 /**
2516  * g_socket_close:
2517  * @socket: a #GSocket
2518  * @error: #GError for error reporting, or %NULL to ignore.
2519  *
2520  * Closes the socket, shutting down any active connection.
2521  *
2522  * Closing a socket does not wait for all outstanding I/O operations
2523  * to finish, so the caller should not rely on them to be guaranteed
2524  * to complete even if the close returns with no error.
2525  *
2526  * Once the socket is closed, all other operations will return
2527  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2528  * return an error.
2529  *
2530  * Sockets will be automatically closed when the last reference
2531  * is dropped, but you might want to call this function to make sure
2532  * resources are released as early as possible.
2533  *
2534  * Beware that due to the way that TCP works, it is possible for
2535  * recently-sent data to be lost if either you close a socket while the
2536  * %G_IO_IN condition is set, or else if the remote connection tries to
2537  * send something to you after you close the socket but before it has
2538  * finished reading all of the data you sent. There is no easy generic
2539  * way to avoid this problem; the easiest fix is to design the network
2540  * protocol such that the client will never send data "out of turn".
2541  * Another solution is for the server to half-close the connection by
2542  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2543  * and then wait for the client to notice this and close its side of the
2544  * connection, after which the server can safely call g_socket_close().
2545  * (This is what #GTcpConnection does if you call
2546  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2547  * only works if the client will close its connection after the server
2548  * does.)
2549  *
2550  * Returns: %TRUE on success, %FALSE on error
2551  *
2552  * Since: 2.22
2553  */
2554 gboolean
2555 g_socket_close (GSocket  *socket,
2556                 GError  **error)
2557 {
2558   int res;
2559
2560   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2561
2562   if (socket->priv->closed)
2563     return TRUE; /* Multiple close not an error */
2564
2565   if (!check_socket (socket, error))
2566     return FALSE;
2567
2568   while (1)
2569     {
2570 #ifdef G_OS_WIN32
2571       res = closesocket (socket->priv->fd);
2572 #else
2573       res = close (socket->priv->fd);
2574 #endif
2575       if (res == -1)
2576         {
2577           int errsv = get_socket_errno ();
2578
2579           if (errsv == EINTR)
2580             continue;
2581
2582           g_set_error (error, G_IO_ERROR,
2583                        socket_io_error_from_errno (errsv),
2584                        _("Error closing socket: %s"),
2585                        socket_strerror (errsv));
2586           return FALSE;
2587         }
2588       break;
2589     }
2590
2591   socket->priv->connected = FALSE;
2592   socket->priv->closed = TRUE;
2593   if (socket->priv->remote_address)
2594     {
2595       g_object_unref (socket->priv->remote_address);
2596       socket->priv->remote_address = NULL;
2597     }
2598
2599   return TRUE;
2600 }
2601
2602 /**
2603  * g_socket_is_closed:
2604  * @socket: a #GSocket
2605  *
2606  * Checks whether a socket is closed.
2607  *
2608  * Returns: %TRUE if socket is closed, %FALSE otherwise
2609  *
2610  * Since: 2.22
2611  */
2612 gboolean
2613 g_socket_is_closed (GSocket *socket)
2614 {
2615   return socket->priv->closed;
2616 }
2617
2618 #ifdef G_OS_WIN32
2619 /* Broken source, used on errors */
2620 static gboolean
2621 broken_prepare  (GSource *source,
2622                  gint    *timeout)
2623 {
2624   return FALSE;
2625 }
2626
2627 static gboolean
2628 broken_check (GSource *source)
2629 {
2630   return FALSE;
2631 }
2632
2633 static gboolean
2634 broken_dispatch (GSource     *source,
2635                  GSourceFunc  callback,
2636                  gpointer     user_data)
2637 {
2638   return TRUE;
2639 }
2640
2641 static GSourceFuncs broken_funcs =
2642 {
2643   broken_prepare,
2644   broken_check,
2645   broken_dispatch,
2646   NULL
2647 };
2648
2649 static gint
2650 network_events_for_condition (GIOCondition condition)
2651 {
2652   int event_mask = 0;
2653
2654   if (condition & G_IO_IN)
2655     event_mask |= (FD_READ | FD_ACCEPT);
2656   if (condition & G_IO_OUT)
2657     event_mask |= (FD_WRITE | FD_CONNECT);
2658   event_mask |= FD_CLOSE;
2659
2660   return event_mask;
2661 }
2662
2663 static void
2664 ensure_event (GSocket *socket)
2665 {
2666   if (socket->priv->event == WSA_INVALID_EVENT)
2667     socket->priv->event = WSACreateEvent();
2668 }
2669
2670 static void
2671 update_select_events (GSocket *socket)
2672 {
2673   int event_mask;
2674   GIOCondition *ptr;
2675   GList *l;
2676   WSAEVENT event;
2677
2678   ensure_event (socket);
2679
2680   event_mask = 0;
2681   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2682     {
2683       ptr = l->data;
2684       event_mask |= network_events_for_condition (*ptr);
2685     }
2686
2687   if (event_mask != socket->priv->selected_events)
2688     {
2689       /* If no events selected, disable event so we can unset
2690          nonblocking mode */
2691
2692       if (event_mask == 0)
2693         event = NULL;
2694       else
2695         event = socket->priv->event;
2696
2697       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2698         socket->priv->selected_events = event_mask;
2699     }
2700 }
2701
2702 static void
2703 add_condition_watch (GSocket      *socket,
2704                      GIOCondition *condition)
2705 {
2706   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2707
2708   socket->priv->requested_conditions =
2709     g_list_prepend (socket->priv->requested_conditions, condition);
2710
2711   update_select_events (socket);
2712 }
2713
2714 static void
2715 remove_condition_watch (GSocket      *socket,
2716                         GIOCondition *condition)
2717 {
2718   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2719
2720   socket->priv->requested_conditions =
2721     g_list_remove (socket->priv->requested_conditions, condition);
2722
2723   update_select_events (socket);
2724 }
2725
2726 static GIOCondition
2727 update_condition (GSocket *socket)
2728 {
2729   WSANETWORKEVENTS events;
2730   GIOCondition condition;
2731
2732   if (WSAEnumNetworkEvents (socket->priv->fd,
2733                             socket->priv->event,
2734                             &events) == 0)
2735     {
2736       socket->priv->current_events |= events.lNetworkEvents;
2737       if (events.lNetworkEvents & FD_WRITE &&
2738           events.iErrorCode[FD_WRITE_BIT] != 0)
2739         socket->priv->current_errors |= FD_WRITE;
2740       if (events.lNetworkEvents & FD_CONNECT &&
2741           events.iErrorCode[FD_CONNECT_BIT] != 0)
2742         socket->priv->current_errors |= FD_CONNECT;
2743     }
2744
2745   condition = 0;
2746   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2747     condition |= G_IO_IN;
2748
2749   if (socket->priv->current_events & FD_CLOSE ||
2750       socket->priv->closed)
2751     condition |= G_IO_HUP;
2752
2753   /* Never report both G_IO_OUT and HUP, these are
2754      mutually exclusive (can't write to a closed socket) */
2755   if ((condition & G_IO_HUP) == 0 &&
2756       socket->priv->current_events & FD_WRITE)
2757     {
2758       if (socket->priv->current_errors & FD_WRITE)
2759         condition |= G_IO_ERR;
2760       else
2761         condition |= G_IO_OUT;
2762     }
2763   else
2764     {
2765       if (socket->priv->current_events & FD_CONNECT)
2766         {
2767           if (socket->priv->current_errors & FD_CONNECT)
2768             condition |= (G_IO_HUP | G_IO_ERR);
2769           else
2770             condition |= G_IO_OUT;
2771         }
2772     }
2773
2774   return condition;
2775 }
2776 #endif
2777
2778 typedef struct {
2779   GSource       source;
2780   GPollFD       pollfd;
2781   GSocket      *socket;
2782   GIOCondition  condition;
2783   GCancellable *cancellable;
2784   GPollFD       cancel_pollfd;
2785   gint64        timeout_time;
2786 } GSocketSource;
2787
2788 static gboolean
2789 socket_source_prepare (GSource *source,
2790                        gint    *timeout)
2791 {
2792   GSocketSource *socket_source = (GSocketSource *)source;
2793
2794   if (g_cancellable_is_cancelled (socket_source->cancellable))
2795     return TRUE;
2796
2797   if (socket_source->timeout_time)
2798     {
2799       gint64 now;
2800
2801       now = g_source_get_time (source);
2802       /* Round up to ensure that we don't try again too early */
2803       *timeout = (socket_source->timeout_time - now + 999) / 1000;
2804       if (*timeout < 0)
2805         {
2806           socket_source->socket->priv->timed_out = TRUE;
2807           *timeout = 0;
2808           return TRUE;
2809         }
2810     }
2811   else
2812     *timeout = -1;
2813
2814 #ifdef G_OS_WIN32
2815   socket_source->pollfd.revents = update_condition (socket_source->socket);
2816 #endif
2817
2818   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2819     return TRUE;
2820
2821   return FALSE;
2822 }
2823
2824 static gboolean
2825 socket_source_check (GSource *source)
2826 {
2827   int timeout;
2828
2829   return socket_source_prepare (source, &timeout);
2830 }
2831
2832 static gboolean
2833 socket_source_dispatch (GSource     *source,
2834                         GSourceFunc  callback,
2835                         gpointer     user_data)
2836 {
2837   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2838   GSocketSource *socket_source = (GSocketSource *)source;
2839
2840 #ifdef G_OS_WIN32
2841   socket_source->pollfd.revents = update_condition (socket_source->socket);
2842 #endif
2843   if (socket_source->socket->priv->timed_out)
2844     socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
2845
2846   return (*func) (socket_source->socket,
2847                   socket_source->pollfd.revents & socket_source->condition,
2848                   user_data);
2849 }
2850
2851 static void
2852 socket_source_finalize (GSource *source)
2853 {
2854   GSocketSource *socket_source = (GSocketSource *)source;
2855   GSocket *socket;
2856
2857   socket = socket_source->socket;
2858
2859 #ifdef G_OS_WIN32
2860   remove_condition_watch (socket, &socket_source->condition);
2861 #endif
2862
2863   g_object_unref (socket);
2864
2865   if (socket_source->cancellable)
2866     {
2867       g_cancellable_release_fd (socket_source->cancellable);
2868       g_object_unref (socket_source->cancellable);
2869     }
2870 }
2871
2872 static gboolean
2873 socket_source_closure_callback (GSocket      *socket,
2874                                 GIOCondition  condition,
2875                                 gpointer      data)
2876 {
2877   GClosure *closure = data;
2878
2879   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
2880   GValue result_value = G_VALUE_INIT;
2881   gboolean result;
2882
2883   g_value_init (&result_value, G_TYPE_BOOLEAN);
2884
2885   g_value_init (&params[0], G_TYPE_SOCKET);
2886   g_value_set_object (&params[0], socket);
2887   g_value_init (&params[1], G_TYPE_IO_CONDITION);
2888   g_value_set_flags (&params[1], condition);
2889
2890   g_closure_invoke (closure, &result_value, 2, params, NULL);
2891
2892   result = g_value_get_boolean (&result_value);
2893   g_value_unset (&result_value);
2894   g_value_unset (&params[0]);
2895   g_value_unset (&params[1]);
2896
2897   return result;
2898 }
2899
2900 static GSourceFuncs socket_source_funcs =
2901 {
2902   socket_source_prepare,
2903   socket_source_check,
2904   socket_source_dispatch,
2905   socket_source_finalize,
2906   (GSourceFunc)socket_source_closure_callback,
2907   (GSourceDummyMarshal)g_cclosure_marshal_generic,
2908 };
2909
2910 static GSource *
2911 socket_source_new (GSocket      *socket,
2912                    GIOCondition  condition,
2913                    GCancellable *cancellable)
2914 {
2915   GSource *source;
2916   GSocketSource *socket_source;
2917
2918 #ifdef G_OS_WIN32
2919   ensure_event (socket);
2920
2921   if (socket->priv->event == WSA_INVALID_EVENT)
2922     {
2923       g_warning ("Failed to create WSAEvent");
2924       return g_source_new (&broken_funcs, sizeof (GSource));
2925     }
2926 #endif
2927
2928   condition |= G_IO_HUP | G_IO_ERR;
2929
2930   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2931   g_source_set_name (source, "GSocket");
2932   socket_source = (GSocketSource *)source;
2933
2934   socket_source->socket = g_object_ref (socket);
2935   socket_source->condition = condition;
2936
2937   if (g_cancellable_make_pollfd (cancellable,
2938                                  &socket_source->cancel_pollfd))
2939     {
2940       socket_source->cancellable = g_object_ref (cancellable);
2941       g_source_add_poll (source, &socket_source->cancel_pollfd);
2942     }
2943
2944 #ifdef G_OS_WIN32
2945   add_condition_watch (socket, &socket_source->condition);
2946   socket_source->pollfd.fd = (gintptr) socket->priv->event;
2947 #else
2948   socket_source->pollfd.fd = socket->priv->fd;
2949 #endif
2950
2951   socket_source->pollfd.events = condition;
2952   socket_source->pollfd.revents = 0;
2953   g_source_add_poll (source, &socket_source->pollfd);
2954
2955   if (socket->priv->timeout)
2956     socket_source->timeout_time = g_get_monotonic_time () +
2957                                   socket->priv->timeout * 1000000;
2958
2959   else
2960     socket_source->timeout_time = 0;
2961
2962   return source;
2963 }
2964
2965 /**
2966  * g_socket_create_source: (skip)
2967  * @socket: a #GSocket
2968  * @condition: a #GIOCondition mask to monitor
2969  * @cancellable: (allow-none): a %GCancellable or %NULL
2970  *
2971  * Creates a %GSource that can be attached to a %GMainContext to monitor
2972  * for the availibility of the specified @condition on the socket.
2973  *
2974  * The callback on the source is of the #GSocketSourceFunc type.
2975  *
2976  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2977  * these conditions will always be reported output if they are true.
2978  *
2979  * @cancellable if not %NULL can be used to cancel the source, which will
2980  * cause the source to trigger, reporting the current condition (which
2981  * is likely 0 unless cancellation happened at the same time as a
2982  * condition change). You can check for this in the callback using
2983  * g_cancellable_is_cancelled().
2984  *
2985  * If @socket has a timeout set, and it is reached before @condition
2986  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2987  * %G_IO_OUT depending on @condition. However, @socket will have been
2988  * marked as having had a timeout, and so the next #GSocket I/O method
2989  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2990  *
2991  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2992  *
2993  * Since: 2.22
2994  */
2995 GSource *
2996 g_socket_create_source (GSocket      *socket,
2997                         GIOCondition  condition,
2998                         GCancellable *cancellable)
2999 {
3000   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3001
3002   return socket_source_new (socket, condition, cancellable);
3003 }
3004
3005 /**
3006  * g_socket_condition_check:
3007  * @socket: a #GSocket
3008  * @condition: a #GIOCondition mask to check
3009  *
3010  * Checks on the readiness of @socket to perform operations.
3011  * The operations specified in @condition are checked for and masked
3012  * against the currently-satisfied conditions on @socket. The result
3013  * is returned.
3014  *
3015  * Note that on Windows, it is possible for an operation to return
3016  * %G_IO_ERROR_WOULD_BLOCK even immediately after
3017  * g_socket_condition_check() has claimed that the socket is ready for
3018  * writing. Rather than calling g_socket_condition_check() and then
3019  * writing to the socket if it succeeds, it is generally better to
3020  * simply try writing to the socket right away, and try again later if
3021  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3022  *
3023  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3024  * these conditions will always be set in the output if they are true.
3025  *
3026  * This call never blocks.
3027  *
3028  * Returns: the @GIOCondition mask of the current state
3029  *
3030  * Since: 2.22
3031  */
3032 GIOCondition
3033 g_socket_condition_check (GSocket      *socket,
3034                           GIOCondition  condition)
3035 {
3036   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3037
3038   if (!check_socket (socket, NULL))
3039     return 0;
3040
3041 #ifdef G_OS_WIN32
3042   {
3043     GIOCondition current_condition;
3044
3045     condition |= G_IO_ERR | G_IO_HUP;
3046
3047     add_condition_watch (socket, &condition);
3048     current_condition = update_condition (socket);
3049     remove_condition_watch (socket, &condition);
3050     return condition & current_condition;
3051   }
3052 #else
3053   {
3054     GPollFD poll_fd;
3055     gint result;
3056     poll_fd.fd = socket->priv->fd;
3057     poll_fd.events = condition;
3058
3059     do
3060       result = g_poll (&poll_fd, 1, 0);
3061     while (result == -1 && get_socket_errno () == EINTR);
3062
3063     return poll_fd.revents;
3064   }
3065 #endif
3066 }
3067
3068 /**
3069  * g_socket_condition_wait:
3070  * @socket: a #GSocket
3071  * @condition: a #GIOCondition mask to wait for
3072  * @cancellable: (allow-none): a #GCancellable, or %NULL
3073  * @error: a #GError pointer, or %NULL
3074  *
3075  * Waits for @condition to become true on @socket. When the condition
3076  * is met, %TRUE is returned.
3077  *
3078  * If @cancellable is cancelled before the condition is met, or if the
3079  * socket has a timeout set and it is reached before the condition is
3080  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3081  * the appropriate value (%G_IO_ERROR_CANCELLED or
3082  * %G_IO_ERROR_TIMED_OUT).
3083  *
3084  * Returns: %TRUE if the condition was met, %FALSE otherwise
3085  *
3086  * Since: 2.22
3087  */
3088 gboolean
3089 g_socket_condition_wait (GSocket       *socket,
3090                          GIOCondition   condition,
3091                          GCancellable  *cancellable,
3092                          GError       **error)
3093 {
3094   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3095
3096   if (!check_socket (socket, error))
3097     return FALSE;
3098
3099   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3100     return FALSE;
3101
3102 #ifdef G_OS_WIN32
3103   {
3104     GIOCondition current_condition;
3105     WSAEVENT events[2];
3106     DWORD res, timeout;
3107     GPollFD cancel_fd;
3108     int num_events;
3109
3110     /* Always check these */
3111     condition |=  G_IO_ERR | G_IO_HUP;
3112
3113     add_condition_watch (socket, &condition);
3114
3115     num_events = 0;
3116     events[num_events++] = socket->priv->event;
3117
3118     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3119       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3120
3121     if (socket->priv->timeout)
3122       timeout = socket->priv->timeout * 1000;
3123     else
3124       timeout = WSA_INFINITE;
3125
3126     current_condition = update_condition (socket);
3127     while ((condition & current_condition) == 0)
3128       {
3129         res = WSAWaitForMultipleEvents(num_events, events,
3130                                        FALSE, timeout, FALSE);
3131         if (res == WSA_WAIT_FAILED)
3132           {
3133             int errsv = get_socket_errno ();
3134
3135             g_set_error (error, G_IO_ERROR,
3136                          socket_io_error_from_errno (errsv),
3137                          _("Waiting for socket condition: %s"),
3138                          socket_strerror (errsv));
3139             break;
3140           }
3141         else if (res == WSA_WAIT_TIMEOUT)
3142           {
3143             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3144                                  _("Socket I/O timed out"));
3145             break;
3146           }
3147
3148         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3149           break;
3150
3151         current_condition = update_condition (socket);
3152       }
3153     remove_condition_watch (socket, &condition);
3154     if (num_events > 1)
3155       g_cancellable_release_fd (cancellable);
3156
3157     return (condition & current_condition) != 0;
3158   }
3159 #else
3160   {
3161     GPollFD poll_fd[2];
3162     gint result;
3163     gint num;
3164     gint timeout;
3165
3166     poll_fd[0].fd = socket->priv->fd;
3167     poll_fd[0].events = condition;
3168     num = 1;
3169
3170     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3171       num++;
3172
3173     if (socket->priv->timeout)
3174       timeout = socket->priv->timeout * 1000;
3175     else
3176       timeout = -1;
3177
3178     do
3179       result = g_poll (poll_fd, num, timeout);
3180     while (result == -1 && get_socket_errno () == EINTR);
3181     
3182     if (num > 1)
3183       g_cancellable_release_fd (cancellable);
3184
3185     if (result == 0)
3186       {
3187         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3188                              _("Socket I/O timed out"));
3189         return FALSE;
3190       }
3191
3192     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3193   }
3194   #endif
3195 }
3196
3197 /**
3198  * g_socket_send_message:
3199  * @socket: a #GSocket
3200  * @address: a #GSocketAddress, or %NULL
3201  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3202  * @num_vectors: the number of elements in @vectors, or -1
3203  * @messages: (array length=num_messages) (allow-none): a pointer to an
3204  *   array of #GSocketControlMessages, or %NULL.
3205  * @num_messages: number of elements in @messages, or -1.
3206  * @flags: an int containing #GSocketMsgFlags flags
3207  * @cancellable: (allow-none): a %GCancellable or %NULL
3208  * @error: #GError for error reporting, or %NULL to ignore.
3209  *
3210  * Send data to @address on @socket.  This is the most complicated and
3211  * fully-featured version of this call. For easier use, see
3212  * g_socket_send() and g_socket_send_to().
3213  *
3214  * If @address is %NULL then the message is sent to the default receiver
3215  * (set by g_socket_connect()).
3216  *
3217  * @vectors must point to an array of #GOutputVector structs and
3218  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3219  * then @vectors is assumed to be terminated by a #GOutputVector with a
3220  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3221  * that the sent data will be gathered from. Using multiple
3222  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3223  * data from multiple sources into a single buffer, and more
3224  * network-efficient than making multiple calls to g_socket_send().
3225  *
3226  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3227  * #GSocketControlMessage instances. These correspond to the control
3228  * messages to be sent on the socket.
3229  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3230  * array.
3231  *
3232  * @flags modify how the message is sent. The commonly available arguments
3233  * for this are available in the #GSocketMsgFlags enum, but the
3234  * values there are the same as the system values, and the flags
3235  * are passed in as-is, so you can pass in system-specific flags too.
3236  *
3237  * If the socket is in blocking mode the call will block until there is
3238  * space for the data in the socket queue. If there is no space available
3239  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3240  * will be returned. To be notified when space is available, wait for the
3241  * %G_IO_OUT condition. Note though that you may still receive
3242  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3243  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3244  * very common due to the way the underlying APIs work.)
3245  *
3246  * On error -1 is returned and @error is set accordingly.
3247  *
3248  * Returns: Number of bytes written (which may be less than @size), or -1
3249  * on error
3250  *
3251  * Since: 2.22
3252  */
3253 gssize
3254 g_socket_send_message (GSocket                *socket,
3255                        GSocketAddress         *address,
3256                        GOutputVector          *vectors,
3257                        gint                    num_vectors,
3258                        GSocketControlMessage **messages,
3259                        gint                    num_messages,
3260                        gint                    flags,
3261                        GCancellable           *cancellable,
3262                        GError                **error)
3263 {
3264   GOutputVector one_vector;
3265   char zero;
3266
3267   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3268
3269   if (!check_socket (socket, error))
3270     return -1;
3271
3272   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3273     return -1;
3274
3275   if (num_vectors == -1)
3276     {
3277       for (num_vectors = 0;
3278            vectors[num_vectors].buffer != NULL;
3279            num_vectors++)
3280         ;
3281     }
3282
3283   if (num_messages == -1)
3284     {
3285       for (num_messages = 0;
3286            messages != NULL && messages[num_messages] != NULL;
3287            num_messages++)
3288         ;
3289     }
3290
3291   if (num_vectors == 0)
3292     {
3293       zero = '\0';
3294
3295       one_vector.buffer = &zero;
3296       one_vector.size = 1;
3297       num_vectors = 1;
3298       vectors = &one_vector;
3299     }
3300
3301 #ifndef G_OS_WIN32
3302   {
3303     struct msghdr msg;
3304     gssize result;
3305
3306    msg.msg_flags = 0;
3307
3308     /* name */
3309     if (address)
3310       {
3311         msg.msg_namelen = g_socket_address_get_native_size (address);
3312         msg.msg_name = g_alloca (msg.msg_namelen);
3313         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3314           return -1;
3315       }
3316     else
3317       {
3318         msg.msg_name = NULL;
3319         msg.msg_namelen = 0;
3320       }
3321
3322     /* iov */
3323     {
3324       /* this entire expression will be evaluated at compile time */
3325       if (sizeof *msg.msg_iov == sizeof *vectors &&
3326           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3327           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3328           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3329           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3330           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3331           G_STRUCT_OFFSET (GOutputVector, size))
3332         /* ABI is compatible */
3333         {
3334           msg.msg_iov = (struct iovec *) vectors;
3335           msg.msg_iovlen = num_vectors;
3336         }
3337       else
3338         /* ABI is incompatible */
3339         {
3340           gint i;
3341
3342           msg.msg_iov = g_newa (struct iovec, num_vectors);
3343           for (i = 0; i < num_vectors; i++)
3344             {
3345               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3346               msg.msg_iov[i].iov_len = vectors[i].size;
3347             }
3348           msg.msg_iovlen = num_vectors;
3349         }
3350     }
3351
3352     /* control */
3353     {
3354       struct cmsghdr *cmsg;
3355       gint i;
3356
3357       msg.msg_controllen = 0;
3358       for (i = 0; i < num_messages; i++)
3359         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3360
3361       if (msg.msg_controllen == 0)
3362         msg.msg_control = NULL;
3363       else
3364         {
3365           msg.msg_control = g_alloca (msg.msg_controllen);
3366           memset (msg.msg_control, '\0', msg.msg_controllen);
3367         }
3368
3369       cmsg = CMSG_FIRSTHDR (&msg);
3370       for (i = 0; i < num_messages; i++)
3371         {
3372           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3373           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3374           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3375           g_socket_control_message_serialize (messages[i],
3376                                               CMSG_DATA (cmsg));
3377           cmsg = CMSG_NXTHDR (&msg, cmsg);
3378         }
3379       g_assert (cmsg == NULL);
3380     }
3381
3382     while (1)
3383       {
3384         if (socket->priv->blocking &&
3385             !g_socket_condition_wait (socket,
3386                                       G_IO_OUT, cancellable, error))
3387           return -1;
3388
3389         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3390         if (result < 0)
3391           {
3392             int errsv = get_socket_errno ();
3393
3394             if (errsv == EINTR)
3395               continue;
3396
3397             if (socket->priv->blocking &&
3398                 (errsv == EWOULDBLOCK ||
3399                  errsv == EAGAIN))
3400               continue;
3401
3402             g_set_error (error, G_IO_ERROR,
3403                          socket_io_error_from_errno (errsv),
3404                          _("Error sending message: %s"), socket_strerror (errsv));
3405
3406             return -1;
3407           }
3408         break;
3409       }
3410
3411     return result;
3412   }
3413 #else
3414   {
3415     struct sockaddr_storage addr;
3416     guint addrlen;
3417     DWORD bytes_sent;
3418     int result;
3419     WSABUF *bufs;
3420     gint i;
3421
3422     /* Win32 doesn't support control messages.
3423        Actually this is possible for raw and datagram sockets
3424        via WSASendMessage on Vista or later, but that doesn't
3425        seem very useful */
3426     if (num_messages != 0)
3427       {
3428         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3429                              _("GSocketControlMessage not supported on windows"));
3430         return -1;
3431       }
3432
3433     /* iov */
3434     bufs = g_newa (WSABUF, num_vectors);
3435     for (i = 0; i < num_vectors; i++)
3436       {
3437         bufs[i].buf = (char *)vectors[i].buffer;
3438         bufs[i].len = (gulong)vectors[i].size;
3439       }
3440
3441     /* name */
3442     addrlen = 0; /* Avoid warning */
3443     if (address)
3444       {
3445         addrlen = g_socket_address_get_native_size (address);
3446         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3447           return -1;
3448       }
3449
3450     while (1)
3451       {
3452         if (socket->priv->blocking &&
3453             !g_socket_condition_wait (socket,
3454                                       G_IO_OUT, cancellable, error))
3455           return -1;
3456
3457         if (address)
3458           result = WSASendTo (socket->priv->fd,
3459                               bufs, num_vectors,
3460                               &bytes_sent, flags,
3461                               (const struct sockaddr *)&addr, addrlen,
3462                               NULL, NULL);
3463         else
3464           result = WSASend (socket->priv->fd,
3465                             bufs, num_vectors,
3466                             &bytes_sent, flags,
3467                             NULL, NULL);
3468
3469         if (result != 0)
3470           {
3471             int errsv = get_socket_errno ();
3472
3473             if (errsv == WSAEINTR)
3474               continue;
3475
3476             if (errsv == WSAEWOULDBLOCK)
3477               win32_unset_event_mask (socket, FD_WRITE);
3478
3479             if (socket->priv->blocking &&
3480                 errsv == WSAEWOULDBLOCK)
3481               continue;
3482
3483             g_set_error (error, G_IO_ERROR,
3484                          socket_io_error_from_errno (errsv),
3485                          _("Error sending message: %s"), socket_strerror (errsv));
3486
3487             return -1;
3488           }
3489         break;
3490       }
3491
3492     return bytes_sent;
3493   }
3494 #endif
3495 }
3496
3497 /**
3498  * g_socket_receive_message:
3499  * @socket: a #GSocket
3500  * @address: (out) (allow-none): a pointer to a #GSocketAddress
3501  *     pointer, or %NULL
3502  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3503  * @num_vectors: the number of elements in @vectors, or -1
3504  * @messages: (array length=num_messages) (allow-none): a pointer which
3505  *    may be filled with an array of #GSocketControlMessages, or %NULL
3506  * @num_messages: a pointer which will be filled with the number of
3507  *    elements in @messages, or %NULL
3508  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3509  * @cancellable: (allow-none): a %GCancellable or %NULL
3510  * @error: a #GError pointer, or %NULL
3511  *
3512  * Receive data from a socket.  This is the most complicated and
3513  * fully-featured version of this call. For easier use, see
3514  * g_socket_receive() and g_socket_receive_from().
3515  *
3516  * If @address is non-%NULL then @address will be set equal to the
3517  * source address of the received packet.
3518  * @address is owned by the caller.
3519  *
3520  * @vector must point to an array of #GInputVector structs and
3521  * @num_vectors must be the length of this array.  These structs
3522  * describe the buffers that received data will be scattered into.
3523  * If @num_vectors is -1, then @vectors is assumed to be terminated
3524  * by a #GInputVector with a %NULL buffer pointer.
3525  *
3526  * As a special case, if @num_vectors is 0 (in which case, @vectors
3527  * may of course be %NULL), then a single byte is received and
3528  * discarded. This is to facilitate the common practice of sending a
3529  * single '\0' byte for the purposes of transferring ancillary data.
3530  *
3531  * @messages, if non-%NULL, will be set to point to a newly-allocated
3532  * array of #GSocketControlMessage instances or %NULL if no such
3533  * messages was received. These correspond to the control messages
3534  * received from the kernel, one #GSocketControlMessage per message
3535  * from the kernel. This array is %NULL-terminated and must be freed
3536  * by the caller using g_free() after calling g_object_unref() on each
3537  * element. If @messages is %NULL, any control messages received will
3538  * be discarded.
3539  *
3540  * @num_messages, if non-%NULL, will be set to the number of control
3541  * messages received.
3542  *
3543  * If both @messages and @num_messages are non-%NULL, then
3544  * @num_messages gives the number of #GSocketControlMessage instances
3545  * in @messages (ie: not including the %NULL terminator).
3546  *
3547  * @flags is an in/out parameter. The commonly available arguments
3548  * for this are available in the #GSocketMsgFlags enum, but the
3549  * values there are the same as the system values, and the flags
3550  * are passed in as-is, so you can pass in system-specific flags too
3551  * (and g_socket_receive_message() may pass system-specific flags out).
3552  *
3553  * As with g_socket_receive(), data may be discarded if @socket is
3554  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3555  * provide enough buffer space to read a complete message. You can pass
3556  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3557  * removing it from the receive queue, but there is no portable way to find
3558  * out the length of the message other than by reading it into a
3559  * sufficiently-large buffer.
3560  *
3561  * If the socket is in blocking mode the call will block until there
3562  * is some data to receive, the connection is closed, or there is an
3563  * error. If there is no data available and the socket is in
3564  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3565  * returned. To be notified when data is available, wait for the
3566  * %G_IO_IN condition.
3567  *
3568  * On error -1 is returned and @error is set accordingly.
3569  *
3570  * Returns: Number of bytes read, or 0 if the connection was closed by
3571  * the peer, or -1 on error
3572  *
3573  * Since: 2.22
3574  */
3575 gssize
3576 g_socket_receive_message (GSocket                 *socket,
3577                           GSocketAddress         **address,
3578                           GInputVector            *vectors,
3579                           gint                     num_vectors,
3580                           GSocketControlMessage ***messages,
3581                           gint                    *num_messages,
3582                           gint                    *flags,
3583                           GCancellable            *cancellable,
3584                           GError                 **error)
3585 {
3586   GInputVector one_vector;
3587   char one_byte;
3588
3589   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3590
3591   if (!check_socket (socket, error))
3592     return -1;
3593
3594   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3595     return -1;
3596
3597   if (num_vectors == -1)
3598     {
3599       for (num_vectors = 0;
3600            vectors[num_vectors].buffer != NULL;
3601            num_vectors++)
3602         ;
3603     }
3604
3605   if (num_vectors == 0)
3606     {
3607       one_vector.buffer = &one_byte;
3608       one_vector.size = 1;
3609       num_vectors = 1;
3610       vectors = &one_vector;
3611     }
3612
3613 #ifndef G_OS_WIN32
3614   {
3615     struct msghdr msg;
3616     gssize result;
3617     struct sockaddr_storage one_sockaddr;
3618
3619     /* name */
3620     if (address)
3621       {
3622         msg.msg_name = &one_sockaddr;
3623         msg.msg_namelen = sizeof (struct sockaddr_storage);
3624       }
3625     else
3626       {
3627         msg.msg_name = NULL;
3628         msg.msg_namelen = 0;
3629       }
3630
3631     /* iov */
3632     /* this entire expression will be evaluated at compile time */
3633     if (sizeof *msg.msg_iov == sizeof *vectors &&
3634         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3635         G_STRUCT_OFFSET (struct iovec, iov_base) ==
3636         G_STRUCT_OFFSET (GInputVector, buffer) &&
3637         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3638         G_STRUCT_OFFSET (struct iovec, iov_len) ==
3639         G_STRUCT_OFFSET (GInputVector, size))
3640       /* ABI is compatible */
3641       {
3642         msg.msg_iov = (struct iovec *) vectors;
3643         msg.msg_iovlen = num_vectors;
3644       }
3645     else
3646       /* ABI is incompatible */
3647       {
3648         gint i;
3649
3650         msg.msg_iov = g_newa (struct iovec, num_vectors);
3651         for (i = 0; i < num_vectors; i++)
3652           {
3653             msg.msg_iov[i].iov_base = vectors[i].buffer;
3654             msg.msg_iov[i].iov_len = vectors[i].size;
3655           }
3656         msg.msg_iovlen = num_vectors;
3657       }
3658
3659     /* control */
3660     msg.msg_control = g_alloca (2048);
3661     msg.msg_controllen = 2048;
3662
3663     /* flags */
3664     if (flags != NULL)
3665       msg.msg_flags = *flags;
3666     else
3667       msg.msg_flags = 0;
3668
3669     /* We always set the close-on-exec flag so we don't leak file
3670      * descriptors into child processes.  Note that gunixfdmessage.c
3671      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
3672      */
3673 #ifdef MSG_CMSG_CLOEXEC
3674     msg.msg_flags |= MSG_CMSG_CLOEXEC;
3675 #endif
3676
3677     /* do it */
3678     while (1)
3679       {
3680         if (socket->priv->blocking &&
3681             !g_socket_condition_wait (socket,
3682                                       G_IO_IN, cancellable, error))
3683           return -1;
3684
3685         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3686 #ifdef MSG_CMSG_CLOEXEC 
3687         if (result < 0 && get_socket_errno () == EINVAL)
3688           {
3689             /* We must be running on an old kernel.  Call without the flag. */
3690             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
3691             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3692           }
3693 #endif
3694
3695         if (result < 0)
3696           {
3697             int errsv = get_socket_errno ();
3698
3699             if (errsv == EINTR)
3700               continue;
3701
3702             if (socket->priv->blocking &&
3703                 (errsv == EWOULDBLOCK ||
3704                  errsv == EAGAIN))
3705               continue;
3706
3707             g_set_error (error, G_IO_ERROR,
3708                          socket_io_error_from_errno (errsv),
3709                          _("Error receiving message: %s"), socket_strerror (errsv));
3710
3711             return -1;
3712           }
3713         break;
3714       }
3715
3716     /* decode address */
3717     if (address != NULL)
3718       {
3719         if (msg.msg_namelen > 0)
3720           *address = g_socket_address_new_from_native (msg.msg_name,
3721                                                        msg.msg_namelen);
3722         else
3723           *address = NULL;
3724       }
3725
3726     /* decode control messages */
3727     {
3728       GPtrArray *my_messages = NULL;
3729       struct cmsghdr *cmsg;
3730
3731       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3732         {
3733           GSocketControlMessage *message;
3734
3735           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3736                                                           cmsg->cmsg_type,
3737                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3738                                                           CMSG_DATA (cmsg));
3739           if (message == NULL)
3740             /* We've already spewed about the problem in the
3741                deserialization code, so just continue */
3742             continue;
3743
3744           if (messages == NULL)
3745             {
3746               /* we have to do it this way if the user ignores the
3747                * messages so that we will close any received fds.
3748                */
3749               g_object_unref (message);
3750             }
3751           else
3752             {
3753               if (my_messages == NULL)
3754                 my_messages = g_ptr_array_new ();
3755               g_ptr_array_add (my_messages, message);
3756             }
3757         }
3758
3759       if (num_messages)
3760         *num_messages = my_messages != NULL ? my_messages->len : 0;
3761
3762       if (messages)
3763         {
3764           if (my_messages == NULL)
3765             {
3766               *messages = NULL;
3767             }
3768           else
3769             {
3770               g_ptr_array_add (my_messages, NULL);
3771               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3772             }
3773         }
3774       else
3775         {
3776           g_assert (my_messages == NULL);
3777         }
3778     }
3779
3780     /* capture the flags */
3781     if (flags != NULL)
3782       *flags = msg.msg_flags;
3783
3784     return result;
3785   }
3786 #else
3787   {
3788     struct sockaddr_storage addr;
3789     int addrlen;
3790     DWORD bytes_received;
3791     DWORD win_flags;
3792     int result;
3793     WSABUF *bufs;
3794     gint i;
3795
3796     /* iov */
3797     bufs = g_newa (WSABUF, num_vectors);
3798     for (i = 0; i < num_vectors; i++)
3799       {
3800         bufs[i].buf = (char *)vectors[i].buffer;
3801         bufs[i].len = (gulong)vectors[i].size;
3802       }
3803
3804     /* flags */
3805     if (flags != NULL)
3806       win_flags = *flags;
3807     else
3808       win_flags = 0;
3809
3810     /* do it */
3811     while (1)
3812       {
3813         if (socket->priv->blocking &&
3814             !g_socket_condition_wait (socket,
3815                                       G_IO_IN, cancellable, error))
3816           return -1;
3817
3818         addrlen = sizeof addr;
3819         if (address)
3820           result = WSARecvFrom (socket->priv->fd,
3821                                 bufs, num_vectors,
3822                                 &bytes_received, &win_flags,
3823                                 (struct sockaddr *)&addr, &addrlen,
3824                                 NULL, NULL);
3825         else
3826           result = WSARecv (socket->priv->fd,
3827                             bufs, num_vectors,
3828                             &bytes_received, &win_flags,
3829                             NULL, NULL);
3830         if (result != 0)
3831           {
3832             int errsv = get_socket_errno ();
3833
3834             if (errsv == WSAEINTR)
3835               continue;
3836
3837             win32_unset_event_mask (socket, FD_READ);
3838
3839             if (socket->priv->blocking &&
3840                 errsv == WSAEWOULDBLOCK)
3841               continue;
3842
3843             g_set_error (error, G_IO_ERROR,
3844                          socket_io_error_from_errno (errsv),
3845                          _("Error receiving message: %s"), socket_strerror (errsv));
3846
3847             return -1;
3848           }
3849         win32_unset_event_mask (socket, FD_READ);
3850         break;
3851       }
3852
3853     /* decode address */
3854     if (address != NULL)
3855       {
3856         if (addrlen > 0)
3857           *address = g_socket_address_new_from_native (&addr, addrlen);
3858         else
3859           *address = NULL;
3860       }
3861
3862     /* capture the flags */
3863     if (flags != NULL)
3864       *flags = win_flags;
3865
3866     if (messages != NULL)
3867       *messages = NULL;
3868     if (num_messages != NULL)
3869       *num_messages = 0;
3870
3871     return bytes_received;
3872   }
3873 #endif
3874 }
3875
3876 /**
3877  * g_socket_get_credentials:
3878  * @socket: a #GSocket.
3879  * @error: #GError for error reporting, or %NULL to ignore.
3880  *
3881  * Returns the credentials of the foreign process connected to this
3882  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3883  * sockets).
3884  *
3885  * If this operation isn't supported on the OS, the method fails with
3886  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3887  * by reading the %SO_PEERCRED option on the underlying socket.
3888  *
3889  * Other ways to obtain credentials from a foreign peer includes the
3890  * #GUnixCredentialsMessage type and
3891  * g_unix_connection_send_credentials() /
3892  * g_unix_connection_receive_credentials() functions.
3893  *
3894  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3895  * that must be freed with g_object_unref().
3896  *
3897  * Since: 2.26
3898  */
3899 GCredentials *
3900 g_socket_get_credentials (GSocket   *socket,
3901                           GError   **error)
3902 {
3903   GCredentials *ret;
3904
3905   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3906   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3907
3908   ret = NULL;
3909
3910 #if defined(__linux__) || defined(__OpenBSD__)
3911   {
3912     socklen_t optlen;
3913 #if defined(__linux__)
3914     struct ucred native_creds;
3915     optlen = sizeof (struct ucred);
3916 #elif defined(__OpenBSD__)
3917     struct sockpeercred native_creds;
3918     optlen = sizeof (struct sockpeercred);
3919 #endif
3920     if (getsockopt (socket->priv->fd,
3921                     SOL_SOCKET,
3922                     SO_PEERCRED,
3923                     (void *)&native_creds,
3924                     &optlen) != 0)
3925       {
3926         int errsv = get_socket_errno ();
3927         g_set_error (error,
3928                      G_IO_ERROR,
3929                      socket_io_error_from_errno (errsv),
3930                      _("Unable to get pending error: %s"),
3931                      socket_strerror (errsv));
3932       }
3933     else
3934       {
3935         ret = g_credentials_new ();
3936         g_credentials_set_native (ret,
3937 #if defined(__linux__)
3938                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
3939 #elif defined(__OpenBSD__)
3940                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
3941 #endif
3942                                   &native_creds);
3943       }
3944   }
3945 #else
3946   g_set_error_literal (error,
3947                        G_IO_ERROR,
3948                        G_IO_ERROR_NOT_SUPPORTED,
3949                        _("g_socket_get_credentials not implemented for this OS"));
3950 #endif
3951
3952   return ret;
3953 }