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