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