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