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