gsocket: fix joining/leaving multicast groups
[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       memset (&mc_req, 0, sizeof (mc_req));
1956       memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
1957
1958 #ifdef HAVE_IP_MREQN
1959       if (iface)
1960         mc_req.imr_ifindex = if_nametoindex (iface);
1961       else
1962         mc_req.imr_ifindex = 0;  /* Pick any.  */
1963 #else
1964       mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
1965 #endif
1966
1967       if (source_specific)
1968         {
1969 #ifdef IP_ADD_SOURCE_MEMBERSHIP
1970           optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
1971 #else
1972           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1973                        join_group ?
1974                        _("Error joining multicast group: %s") :
1975                        _("Error leaving multicast group: %s"),
1976                        _("No support for source-specific multicast"));
1977           return FALSE;
1978 #endif
1979         }
1980       else
1981         optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
1982       result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
1983                            &mc_req, sizeof (mc_req));
1984     }
1985   else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1986     {
1987       struct ipv6_mreq mc_req_ipv6;
1988
1989       memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
1990       memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
1991 #ifdef HAVE_IF_NAMETOINDEX
1992       if (iface)
1993         mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
1994       else
1995 #endif
1996         mc_req_ipv6.ipv6mr_interface = 0;
1997
1998       optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
1999       result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2000                            &mc_req_ipv6, sizeof (mc_req_ipv6));
2001     }
2002   else
2003     g_return_val_if_reached (FALSE);
2004
2005   if (result < 0)
2006     {
2007       int errsv = get_socket_errno ();
2008
2009       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2010                    join_group ?
2011                    _("Error joining multicast group: %s") :
2012                    _("Error leaving multicast group: %s"),
2013                    socket_strerror (errsv));
2014       return FALSE;
2015     }
2016
2017   return TRUE;
2018 }
2019
2020 /**
2021  * g_socket_join_multicast_group:
2022  * @socket: a #GSocket.
2023  * @group: a #GInetAddress specifying the group address to join.
2024  * @iface: (allow-none): Name of the interface to use, or %NULL
2025  * @source_specific: %TRUE if source-specific multicast should be used
2026  * @error: #GError for error reporting, or %NULL to ignore.
2027  *
2028  * Registers @socket to receive multicast messages sent to @group.
2029  * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2030  * been bound to an appropriate interface and port with
2031  * g_socket_bind().
2032  *
2033  * If @iface is %NULL, the system will automatically pick an interface
2034  * to bind to based on @group.
2035  *
2036  * If @source_specific is %TRUE, source-specific multicast as defined
2037  * in RFC 4604 is used. Note that on older platforms this may fail
2038  * with a %G_IO_ERROR_NOT_SUPPORTED error.
2039  *
2040  * Returns: %TRUE on success, %FALSE on error.
2041  *
2042  * Since: 2.32
2043  */
2044 gboolean
2045 g_socket_join_multicast_group (GSocket       *socket,
2046                                GInetAddress  *group,
2047                                gboolean       source_specific,
2048                                const gchar   *iface,
2049                                GError       **error)
2050 {
2051   return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2052 }
2053
2054 /**
2055  * g_socket_leave_multicast_group:
2056  * @socket: a #GSocket.
2057  * @group: a #GInetAddress specifying the group address to leave.
2058  * @iface: (allow-none): Interface used
2059  * @source_specific: %TRUE if source-specific multicast was used
2060  * @error: #GError for error reporting, or %NULL to ignore.
2061  *
2062  * Removes @socket from the multicast group defined by @group, @iface,
2063  * and @source_specific (which must all have the same values they had
2064  * when you joined the group).
2065  *
2066  * @socket remains bound to its address and port, and can still receive
2067  * unicast messages after calling this.
2068  *
2069  * Returns: %TRUE on success, %FALSE on error.
2070  *
2071  * Since: 2.32
2072  */
2073 gboolean
2074 g_socket_leave_multicast_group (GSocket       *socket,
2075                                 GInetAddress  *group,
2076                                 gboolean       source_specific,
2077                                 const gchar   *iface,
2078                                 GError       **error)
2079 {
2080   return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2081 }
2082
2083 /**
2084  * g_socket_speaks_ipv4:
2085  * @socket: a #GSocket
2086  *
2087  * Checks if a socket is capable of speaking IPv4.
2088  *
2089  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2090  * and under some combinations of circumstances IPv6 sockets are also
2091  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2092  * information.
2093  *
2094  * No other types of sockets are currently considered as being capable
2095  * of speaking IPv4.
2096  *
2097  * Returns: %TRUE if this socket can be used with IPv4.
2098  *
2099  * Since: 2.22
2100  **/
2101 gboolean
2102 g_socket_speaks_ipv4 (GSocket *socket)
2103 {
2104   switch (socket->priv->family)
2105     {
2106     case G_SOCKET_FAMILY_IPV4:
2107       return TRUE;
2108
2109     case G_SOCKET_FAMILY_IPV6:
2110 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2111       {
2112         guint sizeof_int = sizeof (int);
2113         gint v6_only;
2114
2115         if (getsockopt (socket->priv->fd,
2116                         IPPROTO_IPV6, IPV6_V6ONLY,
2117                         &v6_only, &sizeof_int) != 0)
2118           return FALSE;
2119
2120         return !v6_only;
2121       }
2122 #else
2123       return FALSE;
2124 #endif
2125
2126     default:
2127       return FALSE;
2128     }
2129 }
2130
2131 /**
2132  * g_socket_accept:
2133  * @socket: a #GSocket.
2134  * @cancellable: (allow-none): a %GCancellable or %NULL
2135  * @error: #GError for error reporting, or %NULL to ignore.
2136  *
2137  * Accept incoming connections on a connection-based socket. This removes
2138  * the first outstanding connection request from the listening socket and
2139  * creates a #GSocket object for it.
2140  *
2141  * The @socket must be bound to a local address with g_socket_bind() and
2142  * must be listening for incoming connections (g_socket_listen()).
2143  *
2144  * If there are no outstanding connections then the operation will block
2145  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2146  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2147  *
2148  * Returns: (transfer full): a new #GSocket, or %NULL on error.
2149  *     Free the returned object with g_object_unref().
2150  *
2151  * Since: 2.22
2152  */
2153 GSocket *
2154 g_socket_accept (GSocket       *socket,
2155                  GCancellable  *cancellable,
2156                  GError       **error)
2157 {
2158   GSocket *new_socket;
2159   gint ret;
2160
2161   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2162
2163   if (!check_socket (socket, error))
2164     return NULL;
2165
2166   while (TRUE)
2167     {
2168       if (socket->priv->blocking &&
2169           !g_socket_condition_wait (socket,
2170                                     G_IO_IN, cancellable, error))
2171         return NULL;
2172
2173       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2174         {
2175           int errsv = get_socket_errno ();
2176
2177           win32_unset_event_mask (socket, FD_ACCEPT);
2178
2179           if (errsv == EINTR)
2180             continue;
2181
2182           if (socket->priv->blocking)
2183             {
2184 #ifdef WSAEWOULDBLOCK
2185               if (errsv == WSAEWOULDBLOCK)
2186                 continue;
2187 #else
2188               if (errsv == EWOULDBLOCK ||
2189                   errsv == EAGAIN)
2190                 continue;
2191 #endif
2192             }
2193
2194           g_set_error (error, G_IO_ERROR,
2195                        socket_io_error_from_errno (errsv),
2196                        _("Error accepting connection: %s"), socket_strerror (errsv));
2197           return NULL;
2198         }
2199       break;
2200     }
2201
2202   win32_unset_event_mask (socket, FD_ACCEPT);
2203
2204 #ifdef G_OS_WIN32
2205   {
2206     /* The socket inherits the accepting sockets event mask and even object,
2207        we need to remove that */
2208     WSAEventSelect (ret, NULL, 0);
2209   }
2210 #else
2211   {
2212     int flags;
2213
2214     /* We always want to set close-on-exec to protect users. If you
2215        need to so some weird inheritance to exec you can re-enable this
2216        using lower level hacks with g_socket_get_fd(). */
2217     flags = fcntl (ret, F_GETFD, 0);
2218     if (flags != -1 &&
2219         (flags & FD_CLOEXEC) == 0)
2220       {
2221         flags |= FD_CLOEXEC;
2222         fcntl (ret, F_SETFD, flags);
2223       }
2224   }
2225 #endif
2226
2227   new_socket = g_socket_new_from_fd (ret, error);
2228   if (new_socket == NULL)
2229     {
2230 #ifdef G_OS_WIN32
2231       closesocket (ret);
2232 #else
2233       close (ret);
2234 #endif
2235     }
2236   else
2237     new_socket->priv->protocol = socket->priv->protocol;
2238
2239   return new_socket;
2240 }
2241
2242 /**
2243  * g_socket_connect:
2244  * @socket: a #GSocket.
2245  * @address: a #GSocketAddress specifying the remote address.
2246  * @cancellable: (allow-none): a %GCancellable or %NULL
2247  * @error: #GError for error reporting, or %NULL to ignore.
2248  *
2249  * Connect the socket to the specified remote address.
2250  *
2251  * For connection oriented socket this generally means we attempt to make
2252  * a connection to the @address. For a connection-less socket it sets
2253  * the default address for g_socket_send() and discards all incoming datagrams
2254  * from other sources.
2255  *
2256  * Generally connection oriented sockets can only connect once, but
2257  * connection-less sockets can connect multiple times to change the
2258  * default address.
2259  *
2260  * If the connect call needs to do network I/O it will block, unless
2261  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2262  * and the user can be notified of the connection finishing by waiting
2263  * for the G_IO_OUT condition. The result of the connection must then be
2264  * checked with g_socket_check_connect_result().
2265  *
2266  * Returns: %TRUE if connected, %FALSE on error.
2267  *
2268  * Since: 2.22
2269  */
2270 gboolean
2271 g_socket_connect (GSocket         *socket,
2272                   GSocketAddress  *address,
2273                   GCancellable    *cancellable,
2274                   GError         **error)
2275 {
2276   struct sockaddr_storage buffer;
2277
2278   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2279
2280   if (!check_socket (socket, error))
2281     return FALSE;
2282
2283   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
2284     return FALSE;
2285
2286   if (socket->priv->remote_address)
2287     g_object_unref (socket->priv->remote_address);
2288   socket->priv->remote_address = g_object_ref (address);
2289
2290   while (1)
2291     {
2292       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
2293                    g_socket_address_get_native_size (address)) < 0)
2294         {
2295           int errsv = get_socket_errno ();
2296
2297           if (errsv == EINTR)
2298             continue;
2299
2300 #ifndef G_OS_WIN32
2301           if (errsv == EINPROGRESS)
2302 #else
2303           if (errsv == WSAEWOULDBLOCK)
2304 #endif
2305             {
2306               if (socket->priv->blocking)
2307                 {
2308                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
2309                     {
2310                       if (g_socket_check_connect_result (socket, error))
2311                         break;
2312                     }
2313                 }
2314               else
2315                 {
2316                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
2317                                        _("Connection in progress"));
2318                   socket->priv->connect_pending = TRUE;
2319                 }
2320             }
2321           else
2322             g_set_error_literal (error, G_IO_ERROR,
2323                                  socket_io_error_from_errno (errsv),
2324                                  socket_strerror (errsv));
2325
2326           return FALSE;
2327         }
2328       break;
2329     }
2330
2331   win32_unset_event_mask (socket, FD_CONNECT);
2332
2333   socket->priv->connected = TRUE;
2334
2335   return TRUE;
2336 }
2337
2338 /**
2339  * g_socket_check_connect_result:
2340  * @socket: a #GSocket
2341  * @error: #GError for error reporting, or %NULL to ignore.
2342  *
2343  * Checks and resets the pending connect error for the socket.
2344  * This is used to check for errors when g_socket_connect() is
2345  * used in non-blocking mode.
2346  *
2347  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
2348  *
2349  * Since: 2.22
2350  */
2351 gboolean
2352 g_socket_check_connect_result (GSocket  *socket,
2353                                GError  **error)
2354 {
2355   guint optlen;
2356   int value;
2357
2358   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2359
2360   if (!check_socket (socket, error))
2361     return FALSE;
2362
2363   optlen = sizeof (value);
2364   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
2365     {
2366       int errsv = get_socket_errno ();
2367
2368       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2369                    _("Unable to get pending error: %s"), socket_strerror (errsv));
2370       return FALSE;
2371     }
2372
2373   if (value != 0)
2374     {
2375       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
2376                            socket_strerror (value));
2377       if (socket->priv->remote_address)
2378         {
2379           g_object_unref (socket->priv->remote_address);
2380           socket->priv->remote_address = NULL;
2381         }
2382       return FALSE;
2383     }
2384
2385   socket->priv->connected = TRUE;
2386   return TRUE;
2387 }
2388
2389 /**
2390  * g_socket_get_available_bytes:
2391  * @socket: a #GSocket
2392  *
2393  * Get the amount of data pending in the OS input buffer.
2394  *
2395  * Returns: the number of bytes that can be read from the socket
2396  * without blocking or -1 on error.
2397  *
2398  * Since: 2.32
2399  */
2400 gssize
2401 g_socket_get_available_bytes (GSocket *socket)
2402 {
2403 #ifndef G_OS_WIN32
2404   gulong avail = 0;
2405 #else
2406   gint avail = 0;
2407 #endif
2408
2409   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
2410
2411 #ifndef G_OS_WIN32
2412   if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
2413     return -1;
2414 #else
2415   if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) == SOCKET_ERROR)
2416     return -1;
2417 #endif
2418
2419   return avail;
2420 }
2421
2422 /**
2423  * g_socket_receive:
2424  * @socket: a #GSocket
2425  * @buffer: a buffer to read data into (which should be at least @size
2426  *     bytes long).
2427  * @size: the number of bytes you want to read from the socket
2428  * @cancellable: (allow-none): a %GCancellable or %NULL
2429  * @error: #GError for error reporting, or %NULL to ignore.
2430  *
2431  * Receive data (up to @size bytes) from a socket. This is mainly used by
2432  * connection-oriented sockets; it is identical to g_socket_receive_from()
2433  * with @address set to %NULL.
2434  *
2435  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
2436  * g_socket_receive() will always read either 0 or 1 complete messages from
2437  * the socket. If the received message is too large to fit in @buffer, then
2438  * the data beyond @size bytes will be discarded, without any explicit
2439  * indication that this has occurred.
2440  *
2441  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
2442  * number of bytes, up to @size. If more than @size bytes have been
2443  * received, the additional data will be returned in future calls to
2444  * g_socket_receive().
2445  *
2446  * If the socket is in blocking mode the call will block until there
2447  * is some data to receive, the connection is closed, or there is an
2448  * error. If there is no data available and the socket is in
2449  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
2450  * returned. To be notified when data is available, wait for the
2451  * %G_IO_IN condition.
2452  *
2453  * On error -1 is returned and @error is set accordingly.
2454  *
2455  * Returns: Number of bytes read, or 0 if the connection was closed by
2456  * the peer, or -1 on error
2457  *
2458  * Since: 2.22
2459  */
2460 gssize
2461 g_socket_receive (GSocket       *socket,
2462                   gchar         *buffer,
2463                   gsize          size,
2464                   GCancellable  *cancellable,
2465                   GError       **error)
2466 {
2467   return g_socket_receive_with_blocking (socket, buffer, size,
2468                                          socket->priv->blocking,
2469                                          cancellable, error);
2470 }
2471
2472 /**
2473  * g_socket_receive_with_blocking:
2474  * @socket: a #GSocket
2475  * @buffer: a buffer to read data into (which should be at least @size
2476  *     bytes long).
2477  * @size: the number of bytes you want to read from the socket
2478  * @blocking: whether to do blocking or non-blocking I/O
2479  * @cancellable: (allow-none): a %GCancellable or %NULL
2480  * @error: #GError for error reporting, or %NULL to ignore.
2481  *
2482  * This behaves exactly the same as g_socket_receive(), except that
2483  * the choice of blocking or non-blocking behavior is determined by
2484  * the @blocking argument rather than by @socket's properties.
2485  *
2486  * Returns: Number of bytes read, or 0 if the connection was closed by
2487  * the peer, or -1 on error
2488  *
2489  * Since: 2.26
2490  */
2491 gssize
2492 g_socket_receive_with_blocking (GSocket       *socket,
2493                                 gchar         *buffer,
2494                                 gsize          size,
2495                                 gboolean       blocking,
2496                                 GCancellable  *cancellable,
2497                                 GError       **error)
2498 {
2499   gssize ret;
2500
2501   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2502
2503   if (!check_socket (socket, error))
2504     return -1;
2505
2506   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2507     return -1;
2508
2509   while (1)
2510     {
2511       if (blocking &&
2512           !g_socket_condition_wait (socket,
2513                                     G_IO_IN, cancellable, error))
2514         return -1;
2515
2516       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
2517         {
2518           int errsv = get_socket_errno ();
2519
2520           if (errsv == EINTR)
2521             continue;
2522
2523           if (blocking)
2524             {
2525 #ifdef WSAEWOULDBLOCK
2526               if (errsv == WSAEWOULDBLOCK)
2527                 continue;
2528 #else
2529               if (errsv == EWOULDBLOCK ||
2530                   errsv == EAGAIN)
2531                 continue;
2532 #endif
2533             }
2534
2535           win32_unset_event_mask (socket, FD_READ);
2536
2537           g_set_error (error, G_IO_ERROR,
2538                        socket_io_error_from_errno (errsv),
2539                        _("Error receiving data: %s"), socket_strerror (errsv));
2540           return -1;
2541         }
2542
2543       win32_unset_event_mask (socket, FD_READ);
2544
2545       break;
2546     }
2547
2548   return ret;
2549 }
2550
2551 /**
2552  * g_socket_receive_from:
2553  * @socket: a #GSocket
2554  * @address: (out) (allow-none): a pointer to a #GSocketAddress
2555  *     pointer, or %NULL
2556  * @buffer: (array length=size) (element-type guint8): a buffer to
2557  *     read data into (which should be at least @size bytes long).
2558  * @size: the number of bytes you want to read from the socket
2559  * @cancellable: (allow-none): a %GCancellable or %NULL
2560  * @error: #GError for error reporting, or %NULL to ignore.
2561  *
2562  * Receive data (up to @size bytes) from a socket.
2563  *
2564  * If @address is non-%NULL then @address will be set equal to the
2565  * source address of the received packet.
2566  * @address is owned by the caller.
2567  *
2568  * See g_socket_receive() for additional information.
2569  *
2570  * Returns: Number of bytes read, or 0 if the connection was closed by
2571  * the peer, or -1 on error
2572  *
2573  * Since: 2.22
2574  */
2575 gssize
2576 g_socket_receive_from (GSocket         *socket,
2577                        GSocketAddress **address,
2578                        gchar           *buffer,
2579                        gsize            size,
2580                        GCancellable    *cancellable,
2581                        GError         **error)
2582 {
2583   GInputVector v;
2584
2585   v.buffer = buffer;
2586   v.size = size;
2587
2588   return g_socket_receive_message (socket,
2589                                    address,
2590                                    &v, 1,
2591                                    NULL, 0, NULL,
2592                                    cancellable,
2593                                    error);
2594 }
2595
2596 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
2597  * one, which can be confusing and annoying. So if possible, we want
2598  * to suppress the signal entirely.
2599  */
2600 #ifdef MSG_NOSIGNAL
2601 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
2602 #else
2603 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
2604 #endif
2605
2606 /**
2607  * g_socket_send:
2608  * @socket: a #GSocket
2609  * @buffer: (array length=size) (element-type guint8): the buffer
2610  *     containing the data to send.
2611  * @size: the number of bytes to send
2612  * @cancellable: (allow-none): a %GCancellable or %NULL
2613  * @error: #GError for error reporting, or %NULL to ignore.
2614  *
2615  * Tries to send @size bytes from @buffer on the socket. This is
2616  * mainly used by connection-oriented sockets; it is identical to
2617  * g_socket_send_to() with @address set to %NULL.
2618  *
2619  * If the socket is in blocking mode the call will block until there is
2620  * space for the data in the socket queue. If there is no space available
2621  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2622  * will be returned. To be notified when space is available, wait for the
2623  * %G_IO_OUT condition. Note though that you may still receive
2624  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2625  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2626  * very common due to the way the underlying APIs work.)
2627  *
2628  * On error -1 is returned and @error is set accordingly.
2629  *
2630  * Returns: Number of bytes written (which may be less than @size), or -1
2631  * on error
2632  *
2633  * Since: 2.22
2634  */
2635 gssize
2636 g_socket_send (GSocket       *socket,
2637                const gchar   *buffer,
2638                gsize          size,
2639                GCancellable  *cancellable,
2640                GError       **error)
2641 {
2642   return g_socket_send_with_blocking (socket, buffer, size,
2643                                       socket->priv->blocking,
2644                                       cancellable, error);
2645 }
2646
2647 /**
2648  * g_socket_send_with_blocking:
2649  * @socket: a #GSocket
2650  * @buffer: (array length=size) (element-type guint8): the buffer
2651  *     containing the data to send.
2652  * @size: the number of bytes to send
2653  * @blocking: whether to do blocking or non-blocking I/O
2654  * @cancellable: (allow-none): a %GCancellable or %NULL
2655  * @error: #GError for error reporting, or %NULL to ignore.
2656  *
2657  * This behaves exactly the same as g_socket_send(), except that
2658  * the choice of blocking or non-blocking behavior is determined by
2659  * the @blocking argument rather than by @socket's properties.
2660  *
2661  * Returns: Number of bytes written (which may be less than @size), or -1
2662  * on error
2663  *
2664  * Since: 2.26
2665  */
2666 gssize
2667 g_socket_send_with_blocking (GSocket       *socket,
2668                              const gchar   *buffer,
2669                              gsize          size,
2670                              gboolean       blocking,
2671                              GCancellable  *cancellable,
2672                              GError       **error)
2673 {
2674   gssize ret;
2675
2676   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
2677
2678   if (!check_socket (socket, error))
2679     return -1;
2680
2681   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2682     return -1;
2683
2684   while (1)
2685     {
2686       if (blocking &&
2687           !g_socket_condition_wait (socket,
2688                                     G_IO_OUT, cancellable, error))
2689         return -1;
2690
2691       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
2692         {
2693           int errsv = get_socket_errno ();
2694
2695           if (errsv == EINTR)
2696             continue;
2697
2698 #ifdef WSAEWOULDBLOCK
2699           if (errsv == WSAEWOULDBLOCK)
2700             win32_unset_event_mask (socket, FD_WRITE);
2701 #endif
2702
2703           if (blocking)
2704             {
2705 #ifdef WSAEWOULDBLOCK
2706               if (errsv == WSAEWOULDBLOCK)
2707                 continue;
2708 #else
2709               if (errsv == EWOULDBLOCK ||
2710                   errsv == EAGAIN)
2711                 continue;
2712 #endif
2713             }
2714
2715           g_set_error (error, G_IO_ERROR,
2716                        socket_io_error_from_errno (errsv),
2717                        _("Error sending data: %s"), socket_strerror (errsv));
2718           return -1;
2719         }
2720       break;
2721     }
2722
2723   return ret;
2724 }
2725
2726 /**
2727  * g_socket_send_to:
2728  * @socket: a #GSocket
2729  * @address: (allow-none): a #GSocketAddress, or %NULL
2730  * @buffer: (array length=size) (element-type guint8): the buffer
2731  *     containing the data to send.
2732  * @size: the number of bytes to send
2733  * @cancellable: (allow-none): a %GCancellable or %NULL
2734  * @error: #GError for error reporting, or %NULL to ignore.
2735  *
2736  * Tries to send @size bytes from @buffer to @address. If @address is
2737  * %NULL then the message is sent to the default receiver (set by
2738  * g_socket_connect()).
2739  *
2740  * See g_socket_send() for additional information.
2741  *
2742  * Returns: Number of bytes written (which may be less than @size), or -1
2743  * on error
2744  *
2745  * Since: 2.22
2746  */
2747 gssize
2748 g_socket_send_to (GSocket         *socket,
2749                   GSocketAddress  *address,
2750                   const gchar     *buffer,
2751                   gsize            size,
2752                   GCancellable    *cancellable,
2753                   GError         **error)
2754 {
2755   GOutputVector v;
2756
2757   v.buffer = buffer;
2758   v.size = size;
2759
2760   return g_socket_send_message (socket,
2761                                 address,
2762                                 &v, 1,
2763                                 NULL, 0,
2764                                 0,
2765                                 cancellable,
2766                                 error);
2767 }
2768
2769 /**
2770  * g_socket_shutdown:
2771  * @socket: a #GSocket
2772  * @shutdown_read: whether to shut down the read side
2773  * @shutdown_write: whether to shut down the write side
2774  * @error: #GError for error reporting, or %NULL to ignore.
2775  *
2776  * Shut down part of a full-duplex connection.
2777  *
2778  * If @shutdown_read is %TRUE then the receiving side of the connection
2779  * is shut down, and further reading is disallowed.
2780  *
2781  * If @shutdown_write is %TRUE then the sending side of the connection
2782  * is shut down, and further writing is disallowed.
2783  *
2784  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2785  *
2786  * One example where this is used is graceful disconnect for TCP connections
2787  * where you close the sending side, then wait for the other side to close
2788  * the connection, thus ensuring that the other side saw all sent data.
2789  *
2790  * Returns: %TRUE on success, %FALSE on error
2791  *
2792  * Since: 2.22
2793  */
2794 gboolean
2795 g_socket_shutdown (GSocket   *socket,
2796                    gboolean   shutdown_read,
2797                    gboolean   shutdown_write,
2798                    GError   **error)
2799 {
2800   int how;
2801
2802   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2803
2804   if (!check_socket (socket, error))
2805     return FALSE;
2806
2807   /* Do nothing? */
2808   if (!shutdown_read && !shutdown_write)
2809     return TRUE;
2810
2811 #ifndef G_OS_WIN32
2812   if (shutdown_read && shutdown_write)
2813     how = SHUT_RDWR;
2814   else if (shutdown_read)
2815     how = SHUT_RD;
2816   else
2817     how = SHUT_WR;
2818 #else
2819   if (shutdown_read && shutdown_write)
2820     how = SD_BOTH;
2821   else if (shutdown_read)
2822     how = SD_RECEIVE;
2823   else
2824     how = SD_SEND;
2825 #endif
2826
2827   if (shutdown (socket->priv->fd, how) != 0)
2828     {
2829       int errsv = get_socket_errno ();
2830       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2831                    _("Unable to shutdown socket: %s"), socket_strerror (errsv));
2832       return FALSE;
2833     }
2834
2835   if (shutdown_read && shutdown_write)
2836     socket->priv->connected = FALSE;
2837
2838   return TRUE;
2839 }
2840
2841 /**
2842  * g_socket_close:
2843  * @socket: a #GSocket
2844  * @error: #GError for error reporting, or %NULL to ignore.
2845  *
2846  * Closes the socket, shutting down any active connection.
2847  *
2848  * Closing a socket does not wait for all outstanding I/O operations
2849  * to finish, so the caller should not rely on them to be guaranteed
2850  * to complete even if the close returns with no error.
2851  *
2852  * Once the socket is closed, all other operations will return
2853  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2854  * return an error.
2855  *
2856  * Sockets will be automatically closed when the last reference
2857  * is dropped, but you might want to call this function to make sure
2858  * resources are released as early as possible.
2859  *
2860  * Beware that due to the way that TCP works, it is possible for
2861  * recently-sent data to be lost if either you close a socket while the
2862  * %G_IO_IN condition is set, or else if the remote connection tries to
2863  * send something to you after you close the socket but before it has
2864  * finished reading all of the data you sent. There is no easy generic
2865  * way to avoid this problem; the easiest fix is to design the network
2866  * protocol such that the client will never send data "out of turn".
2867  * Another solution is for the server to half-close the connection by
2868  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2869  * and then wait for the client to notice this and close its side of the
2870  * connection, after which the server can safely call g_socket_close().
2871  * (This is what #GTcpConnection does if you call
2872  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2873  * only works if the client will close its connection after the server
2874  * does.)
2875  *
2876  * Returns: %TRUE on success, %FALSE on error
2877  *
2878  * Since: 2.22
2879  */
2880 gboolean
2881 g_socket_close (GSocket  *socket,
2882                 GError  **error)
2883 {
2884   int res;
2885
2886   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2887
2888   if (socket->priv->closed)
2889     return TRUE; /* Multiple close not an error */
2890
2891   if (!check_socket (socket, error))
2892     return FALSE;
2893
2894   while (1)
2895     {
2896 #ifdef G_OS_WIN32
2897       res = closesocket (socket->priv->fd);
2898 #else
2899       res = close (socket->priv->fd);
2900 #endif
2901       if (res == -1)
2902         {
2903           int errsv = get_socket_errno ();
2904
2905           if (errsv == EINTR)
2906             continue;
2907
2908           g_set_error (error, G_IO_ERROR,
2909                        socket_io_error_from_errno (errsv),
2910                        _("Error closing socket: %s"),
2911                        socket_strerror (errsv));
2912           return FALSE;
2913         }
2914       break;
2915     }
2916
2917   socket->priv->connected = FALSE;
2918   socket->priv->closed = TRUE;
2919   if (socket->priv->remote_address)
2920     {
2921       g_object_unref (socket->priv->remote_address);
2922       socket->priv->remote_address = NULL;
2923     }
2924
2925   return TRUE;
2926 }
2927
2928 /**
2929  * g_socket_is_closed:
2930  * @socket: a #GSocket
2931  *
2932  * Checks whether a socket is closed.
2933  *
2934  * Returns: %TRUE if socket is closed, %FALSE otherwise
2935  *
2936  * Since: 2.22
2937  */
2938 gboolean
2939 g_socket_is_closed (GSocket *socket)
2940 {
2941   return socket->priv->closed;
2942 }
2943
2944 #ifdef G_OS_WIN32
2945 /* Broken source, used on errors */
2946 static gboolean
2947 broken_prepare  (GSource *source,
2948                  gint    *timeout)
2949 {
2950   return FALSE;
2951 }
2952
2953 static gboolean
2954 broken_check (GSource *source)
2955 {
2956   return FALSE;
2957 }
2958
2959 static gboolean
2960 broken_dispatch (GSource     *source,
2961                  GSourceFunc  callback,
2962                  gpointer     user_data)
2963 {
2964   return TRUE;
2965 }
2966
2967 static GSourceFuncs broken_funcs =
2968 {
2969   broken_prepare,
2970   broken_check,
2971   broken_dispatch,
2972   NULL
2973 };
2974
2975 static gint
2976 network_events_for_condition (GIOCondition condition)
2977 {
2978   int event_mask = 0;
2979
2980   if (condition & G_IO_IN)
2981     event_mask |= (FD_READ | FD_ACCEPT);
2982   if (condition & G_IO_OUT)
2983     event_mask |= (FD_WRITE | FD_CONNECT);
2984   event_mask |= FD_CLOSE;
2985
2986   return event_mask;
2987 }
2988
2989 static void
2990 ensure_event (GSocket *socket)
2991 {
2992   if (socket->priv->event == WSA_INVALID_EVENT)
2993     socket->priv->event = WSACreateEvent();
2994 }
2995
2996 static void
2997 update_select_events (GSocket *socket)
2998 {
2999   int event_mask;
3000   GIOCondition *ptr;
3001   GList *l;
3002   WSAEVENT event;
3003
3004   ensure_event (socket);
3005
3006   event_mask = 0;
3007   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3008     {
3009       ptr = l->data;
3010       event_mask |= network_events_for_condition (*ptr);
3011     }
3012
3013   if (event_mask != socket->priv->selected_events)
3014     {
3015       /* If no events selected, disable event so we can unset
3016          nonblocking mode */
3017
3018       if (event_mask == 0)
3019         event = NULL;
3020       else
3021         event = socket->priv->event;
3022
3023       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3024         socket->priv->selected_events = event_mask;
3025     }
3026 }
3027
3028 static void
3029 add_condition_watch (GSocket      *socket,
3030                      GIOCondition *condition)
3031 {
3032   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3033
3034   socket->priv->requested_conditions =
3035     g_list_prepend (socket->priv->requested_conditions, condition);
3036
3037   update_select_events (socket);
3038 }
3039
3040 static void
3041 remove_condition_watch (GSocket      *socket,
3042                         GIOCondition *condition)
3043 {
3044   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3045
3046   socket->priv->requested_conditions =
3047     g_list_remove (socket->priv->requested_conditions, condition);
3048
3049   update_select_events (socket);
3050 }
3051
3052 static GIOCondition
3053 update_condition (GSocket *socket)
3054 {
3055   WSANETWORKEVENTS events;
3056   GIOCondition condition;
3057
3058   if (WSAEnumNetworkEvents (socket->priv->fd,
3059                             socket->priv->event,
3060                             &events) == 0)
3061     {
3062       socket->priv->current_events |= events.lNetworkEvents;
3063       if (events.lNetworkEvents & FD_WRITE &&
3064           events.iErrorCode[FD_WRITE_BIT] != 0)
3065         socket->priv->current_errors |= FD_WRITE;
3066       if (events.lNetworkEvents & FD_CONNECT &&
3067           events.iErrorCode[FD_CONNECT_BIT] != 0)
3068         socket->priv->current_errors |= FD_CONNECT;
3069     }
3070
3071   condition = 0;
3072   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3073     condition |= G_IO_IN;
3074
3075   if (socket->priv->current_events & FD_CLOSE)
3076     {
3077       int r, errsv, buffer;
3078
3079       r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3080       if (r < 0)
3081           errsv = get_socket_errno ();
3082
3083       if (r > 0 ||
3084           (r < 0 && errsv == WSAENOTCONN))
3085         condition |= G_IO_IN;
3086       else if (r == 0 ||
3087                (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3088                           errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3089         condition |= G_IO_HUP;
3090       else
3091         condition |= G_IO_ERR;
3092     }
3093
3094   if (socket->priv->closed)
3095     condition |= G_IO_HUP;
3096
3097   /* Never report both G_IO_OUT and HUP, these are
3098      mutually exclusive (can't write to a closed socket) */
3099   if ((condition & G_IO_HUP) == 0 &&
3100       socket->priv->current_events & FD_WRITE)
3101     {
3102       if (socket->priv->current_errors & FD_WRITE)
3103         condition |= G_IO_ERR;
3104       else
3105         condition |= G_IO_OUT;
3106     }
3107   else
3108     {
3109       if (socket->priv->current_events & FD_CONNECT)
3110         {
3111           if (socket->priv->current_errors & FD_CONNECT)
3112             condition |= (G_IO_HUP | G_IO_ERR);
3113           else
3114             condition |= G_IO_OUT;
3115         }
3116     }
3117
3118   return condition;
3119 }
3120 #endif
3121
3122 typedef struct {
3123   GSource       source;
3124   GPollFD       pollfd;
3125   GSocket      *socket;
3126   GIOCondition  condition;
3127   GCancellable *cancellable;
3128   GPollFD       cancel_pollfd;
3129   gint64        timeout_time;
3130 } GSocketSource;
3131
3132 static gboolean
3133 socket_source_prepare (GSource *source,
3134                        gint    *timeout)
3135 {
3136   GSocketSource *socket_source = (GSocketSource *)source;
3137
3138   if (g_cancellable_is_cancelled (socket_source->cancellable))
3139     return TRUE;
3140
3141   if (socket_source->timeout_time)
3142     {
3143       gint64 now;
3144
3145       now = g_source_get_time (source);
3146       /* Round up to ensure that we don't try again too early */
3147       *timeout = (socket_source->timeout_time - now + 999) / 1000;
3148       if (*timeout < 0)
3149         {
3150           socket_source->socket->priv->timed_out = TRUE;
3151           *timeout = 0;
3152           return TRUE;
3153         }
3154     }
3155   else
3156     *timeout = -1;
3157
3158 #ifdef G_OS_WIN32
3159   socket_source->pollfd.revents = update_condition (socket_source->socket);
3160 #endif
3161
3162   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
3163     return TRUE;
3164
3165   return FALSE;
3166 }
3167
3168 static gboolean
3169 socket_source_check (GSource *source)
3170 {
3171   int timeout;
3172
3173   return socket_source_prepare (source, &timeout);
3174 }
3175
3176 static gboolean
3177 socket_source_dispatch (GSource     *source,
3178                         GSourceFunc  callback,
3179                         gpointer     user_data)
3180 {
3181   GSocketSourceFunc func = (GSocketSourceFunc)callback;
3182   GSocketSource *socket_source = (GSocketSource *)source;
3183   GSocket *socket = socket_source->socket;
3184   gboolean ret;
3185
3186 #ifdef G_OS_WIN32
3187   socket_source->pollfd.revents = update_condition (socket_source->socket);
3188 #endif
3189   if (socket_source->socket->priv->timed_out)
3190     socket_source->pollfd.revents |= socket_source->condition & (G_IO_IN | G_IO_OUT);
3191
3192   ret = (*func) (socket,
3193                  socket_source->pollfd.revents & socket_source->condition,
3194                  user_data);
3195
3196   if (socket->priv->timeout)
3197     socket_source->timeout_time = g_get_monotonic_time () +
3198                                   socket->priv->timeout * 1000000;
3199
3200   else
3201     socket_source->timeout_time = 0;
3202
3203   return ret;
3204 }
3205
3206 static void
3207 socket_source_finalize (GSource *source)
3208 {
3209   GSocketSource *socket_source = (GSocketSource *)source;
3210   GSocket *socket;
3211
3212   socket = socket_source->socket;
3213
3214 #ifdef G_OS_WIN32
3215   remove_condition_watch (socket, &socket_source->condition);
3216 #endif
3217
3218   g_object_unref (socket);
3219
3220   if (socket_source->cancellable)
3221     {
3222       g_cancellable_release_fd (socket_source->cancellable);
3223       g_object_unref (socket_source->cancellable);
3224     }
3225 }
3226
3227 static gboolean
3228 socket_source_closure_callback (GSocket      *socket,
3229                                 GIOCondition  condition,
3230                                 gpointer      data)
3231 {
3232   GClosure *closure = data;
3233
3234   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
3235   GValue result_value = G_VALUE_INIT;
3236   gboolean result;
3237
3238   g_value_init (&result_value, G_TYPE_BOOLEAN);
3239
3240   g_value_init (&params[0], G_TYPE_SOCKET);
3241   g_value_set_object (&params[0], socket);
3242   g_value_init (&params[1], G_TYPE_IO_CONDITION);
3243   g_value_set_flags (&params[1], condition);
3244
3245   g_closure_invoke (closure, &result_value, 2, params, NULL);
3246
3247   result = g_value_get_boolean (&result_value);
3248   g_value_unset (&result_value);
3249   g_value_unset (&params[0]);
3250   g_value_unset (&params[1]);
3251
3252   return result;
3253 }
3254
3255 static GSourceFuncs socket_source_funcs =
3256 {
3257   socket_source_prepare,
3258   socket_source_check,
3259   socket_source_dispatch,
3260   socket_source_finalize,
3261   (GSourceFunc)socket_source_closure_callback,
3262   (GSourceDummyMarshal)g_cclosure_marshal_generic,
3263 };
3264
3265 static GSource *
3266 socket_source_new (GSocket      *socket,
3267                    GIOCondition  condition,
3268                    GCancellable *cancellable)
3269 {
3270   GSource *source;
3271   GSocketSource *socket_source;
3272
3273 #ifdef G_OS_WIN32
3274   ensure_event (socket);
3275
3276   if (socket->priv->event == WSA_INVALID_EVENT)
3277     {
3278       g_warning ("Failed to create WSAEvent");
3279       return g_source_new (&broken_funcs, sizeof (GSource));
3280     }
3281 #endif
3282
3283   condition |= G_IO_HUP | G_IO_ERR;
3284
3285   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
3286   g_source_set_name (source, "GSocket");
3287   socket_source = (GSocketSource *)source;
3288
3289   socket_source->socket = g_object_ref (socket);
3290   socket_source->condition = condition;
3291
3292   if (g_cancellable_make_pollfd (cancellable,
3293                                  &socket_source->cancel_pollfd))
3294     {
3295       socket_source->cancellable = g_object_ref (cancellable);
3296       g_source_add_poll (source, &socket_source->cancel_pollfd);
3297     }
3298
3299 #ifdef G_OS_WIN32
3300   add_condition_watch (socket, &socket_source->condition);
3301   socket_source->pollfd.fd = (gintptr) socket->priv->event;
3302 #else
3303   socket_source->pollfd.fd = socket->priv->fd;
3304 #endif
3305
3306   socket_source->pollfd.events = condition;
3307   socket_source->pollfd.revents = 0;
3308   g_source_add_poll (source, &socket_source->pollfd);
3309
3310   if (socket->priv->timeout)
3311     socket_source->timeout_time = g_get_monotonic_time () +
3312                                   socket->priv->timeout * 1000000;
3313
3314   else
3315     socket_source->timeout_time = 0;
3316
3317   return source;
3318 }
3319
3320 /**
3321  * g_socket_create_source: (skip)
3322  * @socket: a #GSocket
3323  * @condition: a #GIOCondition mask to monitor
3324  * @cancellable: (allow-none): a %GCancellable or %NULL
3325  *
3326  * Creates a %GSource that can be attached to a %GMainContext to monitor
3327  * for the availibility of the specified @condition on the socket.
3328  *
3329  * The callback on the source is of the #GSocketSourceFunc type.
3330  *
3331  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
3332  * these conditions will always be reported output if they are true.
3333  *
3334  * @cancellable if not %NULL can be used to cancel the source, which will
3335  * cause the source to trigger, reporting the current condition (which
3336  * is likely 0 unless cancellation happened at the same time as a
3337  * condition change). You can check for this in the callback using
3338  * g_cancellable_is_cancelled().
3339  *
3340  * If @socket has a timeout set, and it is reached before @condition
3341  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
3342  * %G_IO_OUT depending on @condition. However, @socket will have been
3343  * marked as having had a timeout, and so the next #GSocket I/O method
3344  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
3345  *
3346  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
3347  *
3348  * Since: 2.22
3349  */
3350 GSource *
3351 g_socket_create_source (GSocket      *socket,
3352                         GIOCondition  condition,
3353                         GCancellable *cancellable)
3354 {
3355   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
3356
3357   return socket_source_new (socket, condition, cancellable);
3358 }
3359
3360 /**
3361  * g_socket_condition_check:
3362  * @socket: a #GSocket
3363  * @condition: a #GIOCondition mask to check
3364  *
3365  * Checks on the readiness of @socket to perform operations.
3366  * The operations specified in @condition are checked for and masked
3367  * against the currently-satisfied conditions on @socket. The result
3368  * is returned.
3369  *
3370  * Note that on Windows, it is possible for an operation to return
3371  * %G_IO_ERROR_WOULD_BLOCK even immediately after
3372  * g_socket_condition_check() has claimed that the socket is ready for
3373  * writing. Rather than calling g_socket_condition_check() and then
3374  * writing to the socket if it succeeds, it is generally better to
3375  * simply try writing to the socket right away, and try again later if
3376  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
3377  *
3378  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
3379  * these conditions will always be set in the output if they are true.
3380  *
3381  * This call never blocks.
3382  *
3383  * Returns: the @GIOCondition mask of the current state
3384  *
3385  * Since: 2.22
3386  */
3387 GIOCondition
3388 g_socket_condition_check (GSocket      *socket,
3389                           GIOCondition  condition)
3390 {
3391   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
3392
3393   if (!check_socket (socket, NULL))
3394     return 0;
3395
3396 #ifdef G_OS_WIN32
3397   {
3398     GIOCondition current_condition;
3399
3400     condition |= G_IO_ERR | G_IO_HUP;
3401
3402     add_condition_watch (socket, &condition);
3403     current_condition = update_condition (socket);
3404     remove_condition_watch (socket, &condition);
3405     return condition & current_condition;
3406   }
3407 #else
3408   {
3409     GPollFD poll_fd;
3410     gint result;
3411     poll_fd.fd = socket->priv->fd;
3412     poll_fd.events = condition;
3413     poll_fd.revents = 0;
3414
3415     do
3416       result = g_poll (&poll_fd, 1, 0);
3417     while (result == -1 && get_socket_errno () == EINTR);
3418
3419     return poll_fd.revents;
3420   }
3421 #endif
3422 }
3423
3424 /**
3425  * g_socket_condition_wait:
3426  * @socket: a #GSocket
3427  * @condition: a #GIOCondition mask to wait for
3428  * @cancellable: (allow-none): a #GCancellable, or %NULL
3429  * @error: a #GError pointer, or %NULL
3430  *
3431  * Waits for @condition to become true on @socket. When the condition
3432  * is met, %TRUE is returned.
3433  *
3434  * If @cancellable is cancelled before the condition is met, or if the
3435  * socket has a timeout set and it is reached before the condition is
3436  * met, then %FALSE is returned and @error, if non-%NULL, is set to
3437  * the appropriate value (%G_IO_ERROR_CANCELLED or
3438  * %G_IO_ERROR_TIMED_OUT).
3439  *
3440  * See also g_socket_condition_timed_wait().
3441  *
3442  * Returns: %TRUE if the condition was met, %FALSE otherwise
3443  *
3444  * Since: 2.22
3445  */
3446 gboolean
3447 g_socket_condition_wait (GSocket       *socket,
3448                          GIOCondition   condition,
3449                          GCancellable  *cancellable,
3450                          GError       **error)
3451 {
3452   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3453
3454   return g_socket_condition_timed_wait (socket, condition, -1,
3455                                         cancellable, error);
3456 }
3457
3458 /**
3459  * g_socket_condition_timed_wait:
3460  * @socket: a #GSocket
3461  * @condition: a #GIOCondition mask to wait for
3462  * @timeout: the maximum time (in microseconds) to wait, or -1
3463  * @cancellable: (allow-none): a #GCancellable, or %NULL
3464  * @error: a #GError pointer, or %NULL
3465  *
3466  * Waits for up to @timeout microseconds for @condition to become true
3467  * on @socket. If the condition is met, %TRUE is returned.
3468  *
3469  * If @cancellable is cancelled before the condition is met, or if
3470  * @timeout (or the socket's #GSocket:timeout) is reached before the
3471  * condition is met, then %FALSE is returned and @error, if non-%NULL,
3472  * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
3473  * %G_IO_ERROR_TIMED_OUT).
3474  *
3475  * If you don't want a timeout, use g_socket_condition_wait().
3476  * (Alternatively, you can pass -1 for @timeout.)
3477  *
3478  * Note that although @timeout is in microseconds for consistency with
3479  * other GLib APIs, this function actually only has millisecond
3480  * resolution, and the behavior is undefined if @timeout is not an
3481  * exact number of milliseconds.
3482  *
3483  * Returns: %TRUE if the condition was met, %FALSE otherwise
3484  *
3485  * Since: 2.32
3486  */
3487 gboolean
3488 g_socket_condition_timed_wait (GSocket       *socket,
3489                                GIOCondition   condition,
3490                                gint64         timeout,
3491                                GCancellable  *cancellable,
3492                                GError       **error)
3493 {
3494   gint64 start_time;
3495
3496   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3497
3498   if (!check_socket (socket, error))
3499     return FALSE;
3500
3501   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3502     return FALSE;
3503
3504   if (socket->priv->timeout &&
3505       (timeout < 0 || socket->priv->timeout < timeout / G_USEC_PER_SEC))
3506     timeout = socket->priv->timeout * 1000;
3507   else if (timeout != -1)
3508     timeout = timeout / 1000;
3509
3510   start_time = g_get_monotonic_time ();
3511
3512 #ifdef G_OS_WIN32
3513   {
3514     GIOCondition current_condition;
3515     WSAEVENT events[2];
3516     DWORD res;
3517     GPollFD cancel_fd;
3518     int num_events;
3519
3520     /* Always check these */
3521     condition |=  G_IO_ERR | G_IO_HUP;
3522
3523     add_condition_watch (socket, &condition);
3524
3525     num_events = 0;
3526     events[num_events++] = socket->priv->event;
3527
3528     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
3529       events[num_events++] = (WSAEVENT)cancel_fd.fd;
3530
3531     if (timeout == -1)
3532       timeout = WSA_INFINITE;
3533
3534     current_condition = update_condition (socket);
3535     while ((condition & current_condition) == 0)
3536       {
3537         res = WSAWaitForMultipleEvents (num_events, events,
3538                                         FALSE, timeout, FALSE);
3539         if (res == WSA_WAIT_FAILED)
3540           {
3541             int errsv = get_socket_errno ();
3542
3543             g_set_error (error, G_IO_ERROR,
3544                          socket_io_error_from_errno (errsv),
3545                          _("Waiting for socket condition: %s"),
3546                          socket_strerror (errsv));
3547             break;
3548           }
3549         else if (res == WSA_WAIT_TIMEOUT)
3550           {
3551             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3552                                  _("Socket I/O timed out"));
3553             break;
3554           }
3555
3556         if (g_cancellable_set_error_if_cancelled (cancellable, error))
3557           break;
3558
3559         current_condition = update_condition (socket);
3560
3561         if (timeout != WSA_INFINITE)
3562           {
3563             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3564             if (timeout < 0)
3565               timeout = 0;
3566           }
3567       }
3568     remove_condition_watch (socket, &condition);
3569     if (num_events > 1)
3570       g_cancellable_release_fd (cancellable);
3571
3572     return (condition & current_condition) != 0;
3573   }
3574 #else
3575   {
3576     GPollFD poll_fd[2];
3577     gint result;
3578     gint num;
3579
3580     poll_fd[0].fd = socket->priv->fd;
3581     poll_fd[0].events = condition;
3582     num = 1;
3583
3584     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
3585       num++;
3586
3587     while (TRUE)
3588       {
3589         result = g_poll (poll_fd, num, timeout);
3590         if (result != -1 || errno != EINTR)
3591           break;
3592
3593         if (timeout != -1)
3594           {
3595             timeout -= (g_get_monotonic_time () - start_time) * 1000;
3596             if (timeout < 0)
3597               timeout = 0;
3598           }
3599       }
3600     
3601     if (num > 1)
3602       g_cancellable_release_fd (cancellable);
3603
3604     if (result == 0)
3605       {
3606         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3607                              _("Socket I/O timed out"));
3608         return FALSE;
3609       }
3610
3611     return !g_cancellable_set_error_if_cancelled (cancellable, error);
3612   }
3613   #endif
3614 }
3615
3616 /**
3617  * g_socket_send_message:
3618  * @socket: a #GSocket
3619  * @address: (allow-none): a #GSocketAddress, or %NULL
3620  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
3621  * @num_vectors: the number of elements in @vectors, or -1
3622  * @messages: (array length=num_messages) (allow-none): a pointer to an
3623  *   array of #GSocketControlMessages, or %NULL.
3624  * @num_messages: number of elements in @messages, or -1.
3625  * @flags: an int containing #GSocketMsgFlags flags
3626  * @cancellable: (allow-none): a %GCancellable or %NULL
3627  * @error: #GError for error reporting, or %NULL to ignore.
3628  *
3629  * Send data to @address on @socket.  This is the most complicated and
3630  * fully-featured version of this call. For easier use, see
3631  * g_socket_send() and g_socket_send_to().
3632  *
3633  * If @address is %NULL then the message is sent to the default receiver
3634  * (set by g_socket_connect()).
3635  *
3636  * @vectors must point to an array of #GOutputVector structs and
3637  * @num_vectors must be the length of this array. (If @num_vectors is -1,
3638  * then @vectors is assumed to be terminated by a #GOutputVector with a
3639  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
3640  * that the sent data will be gathered from. Using multiple
3641  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
3642  * data from multiple sources into a single buffer, and more
3643  * network-efficient than making multiple calls to g_socket_send().
3644  *
3645  * @messages, if non-%NULL, is taken to point to an array of @num_messages
3646  * #GSocketControlMessage instances. These correspond to the control
3647  * messages to be sent on the socket.
3648  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
3649  * array.
3650  *
3651  * @flags modify how the message is sent. The commonly available arguments
3652  * for this are available in the #GSocketMsgFlags enum, but the
3653  * values there are the same as the system values, and the flags
3654  * are passed in as-is, so you can pass in system-specific flags too.
3655  *
3656  * If the socket is in blocking mode the call will block until there is
3657  * space for the data in the socket queue. If there is no space available
3658  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3659  * will be returned. To be notified when space is available, wait for the
3660  * %G_IO_OUT condition. Note though that you may still receive
3661  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3662  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3663  * very common due to the way the underlying APIs work.)
3664  *
3665  * On error -1 is returned and @error is set accordingly.
3666  *
3667  * Returns: Number of bytes written (which may be less than @size), or -1
3668  * on error
3669  *
3670  * Since: 2.22
3671  */
3672 gssize
3673 g_socket_send_message (GSocket                *socket,
3674                        GSocketAddress         *address,
3675                        GOutputVector          *vectors,
3676                        gint                    num_vectors,
3677                        GSocketControlMessage **messages,
3678                        gint                    num_messages,
3679                        gint                    flags,
3680                        GCancellable           *cancellable,
3681                        GError                **error)
3682 {
3683   GOutputVector one_vector;
3684   char zero;
3685
3686   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3687
3688   if (!check_socket (socket, error))
3689     return -1;
3690
3691   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3692     return -1;
3693
3694   if (num_vectors == -1)
3695     {
3696       for (num_vectors = 0;
3697            vectors[num_vectors].buffer != NULL;
3698            num_vectors++)
3699         ;
3700     }
3701
3702   if (num_messages == -1)
3703     {
3704       for (num_messages = 0;
3705            messages != NULL && messages[num_messages] != NULL;
3706            num_messages++)
3707         ;
3708     }
3709
3710   if (num_vectors == 0)
3711     {
3712       zero = '\0';
3713
3714       one_vector.buffer = &zero;
3715       one_vector.size = 1;
3716       num_vectors = 1;
3717       vectors = &one_vector;
3718     }
3719
3720 #ifndef G_OS_WIN32
3721   {
3722     struct msghdr msg;
3723     gssize result;
3724
3725    msg.msg_flags = 0;
3726
3727     /* name */
3728     if (address)
3729       {
3730         msg.msg_namelen = g_socket_address_get_native_size (address);
3731         msg.msg_name = g_alloca (msg.msg_namelen);
3732         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
3733           return -1;
3734       }
3735     else
3736       {
3737         msg.msg_name = NULL;
3738         msg.msg_namelen = 0;
3739       }
3740
3741     /* iov */
3742     {
3743       /* this entire expression will be evaluated at compile time */
3744       if (sizeof *msg.msg_iov == sizeof *vectors &&
3745           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3746           G_STRUCT_OFFSET (struct iovec, iov_base) ==
3747           G_STRUCT_OFFSET (GOutputVector, buffer) &&
3748           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3749           G_STRUCT_OFFSET (struct iovec, iov_len) ==
3750           G_STRUCT_OFFSET (GOutputVector, size))
3751         /* ABI is compatible */
3752         {
3753           msg.msg_iov = (struct iovec *) vectors;
3754           msg.msg_iovlen = num_vectors;
3755         }
3756       else
3757         /* ABI is incompatible */
3758         {
3759           gint i;
3760
3761           msg.msg_iov = g_newa (struct iovec, num_vectors);
3762           for (i = 0; i < num_vectors; i++)
3763             {
3764               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
3765               msg.msg_iov[i].iov_len = vectors[i].size;
3766             }
3767           msg.msg_iovlen = num_vectors;
3768         }
3769     }
3770
3771     /* control */
3772     {
3773       struct cmsghdr *cmsg;
3774       gint i;
3775
3776       msg.msg_controllen = 0;
3777       for (i = 0; i < num_messages; i++)
3778         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
3779
3780       if (msg.msg_controllen == 0)
3781         msg.msg_control = NULL;
3782       else
3783         {
3784           msg.msg_control = g_alloca (msg.msg_controllen);
3785           memset (msg.msg_control, '\0', msg.msg_controllen);
3786         }
3787
3788       cmsg = CMSG_FIRSTHDR (&msg);
3789       for (i = 0; i < num_messages; i++)
3790         {
3791           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
3792           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
3793           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
3794           g_socket_control_message_serialize (messages[i],
3795                                               CMSG_DATA (cmsg));
3796           cmsg = CMSG_NXTHDR (&msg, cmsg);
3797         }
3798       g_assert (cmsg == NULL);
3799     }
3800
3801     while (1)
3802       {
3803         if (socket->priv->blocking &&
3804             !g_socket_condition_wait (socket,
3805                                       G_IO_OUT, cancellable, error))
3806           return -1;
3807
3808         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3809         if (result < 0)
3810           {
3811             int errsv = get_socket_errno ();
3812
3813             if (errsv == EINTR)
3814               continue;
3815
3816             if (socket->priv->blocking &&
3817                 (errsv == EWOULDBLOCK ||
3818                  errsv == EAGAIN))
3819               continue;
3820
3821             g_set_error (error, G_IO_ERROR,
3822                          socket_io_error_from_errno (errsv),
3823                          _("Error sending message: %s"), socket_strerror (errsv));
3824
3825             return -1;
3826           }
3827         break;
3828       }
3829
3830     return result;
3831   }
3832 #else
3833   {
3834     struct sockaddr_storage addr;
3835     guint addrlen;
3836     DWORD bytes_sent;
3837     int result;
3838     WSABUF *bufs;
3839     gint i;
3840
3841     /* Win32 doesn't support control messages.
3842        Actually this is possible for raw and datagram sockets
3843        via WSASendMessage on Vista or later, but that doesn't
3844        seem very useful */
3845     if (num_messages != 0)
3846       {
3847         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3848                              _("GSocketControlMessage not supported on Windows"));
3849         return -1;
3850       }
3851
3852     /* iov */
3853     bufs = g_newa (WSABUF, num_vectors);
3854     for (i = 0; i < num_vectors; i++)
3855       {
3856         bufs[i].buf = (char *)vectors[i].buffer;
3857         bufs[i].len = (gulong)vectors[i].size;
3858       }
3859
3860     /* name */
3861     addrlen = 0; /* Avoid warning */
3862     if (address)
3863       {
3864         addrlen = g_socket_address_get_native_size (address);
3865         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3866           return -1;
3867       }
3868
3869     while (1)
3870       {
3871         if (socket->priv->blocking &&
3872             !g_socket_condition_wait (socket,
3873                                       G_IO_OUT, cancellable, error))
3874           return -1;
3875
3876         if (address)
3877           result = WSASendTo (socket->priv->fd,
3878                               bufs, num_vectors,
3879                               &bytes_sent, flags,
3880                               (const struct sockaddr *)&addr, addrlen,
3881                               NULL, NULL);
3882         else
3883           result = WSASend (socket->priv->fd,
3884                             bufs, num_vectors,
3885                             &bytes_sent, flags,
3886                             NULL, NULL);
3887
3888         if (result != 0)
3889           {
3890             int errsv = get_socket_errno ();
3891
3892             if (errsv == WSAEINTR)
3893               continue;
3894
3895             if (errsv == WSAEWOULDBLOCK)
3896               win32_unset_event_mask (socket, FD_WRITE);
3897
3898             if (socket->priv->blocking &&
3899                 errsv == WSAEWOULDBLOCK)
3900               continue;
3901
3902             g_set_error (error, G_IO_ERROR,
3903                          socket_io_error_from_errno (errsv),
3904                          _("Error sending message: %s"), socket_strerror (errsv));
3905
3906             return -1;
3907           }
3908         break;
3909       }
3910
3911     return bytes_sent;
3912   }
3913 #endif
3914 }
3915
3916 static GSocketAddress *
3917 cache_recv_address (GSocket *socket, struct sockaddr *native, int native_len)
3918 {
3919   GSocketAddress *saddr;
3920   gint i;
3921   guint64 oldest_time = G_MAXUINT64;
3922   gint oldest_index = 0;
3923
3924   if (native_len <= 0)
3925     return NULL;
3926
3927   saddr = NULL;
3928   for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
3929     {
3930       GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
3931       gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
3932       gint tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
3933
3934       if (!tmp)
3935         continue;
3936
3937       if (tmp_native_len != native_len)
3938         continue;
3939
3940       if (memcmp (tmp_native, native, native_len) == 0)
3941         {
3942           saddr = g_object_ref (tmp);
3943           socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
3944           return saddr;
3945         }
3946
3947       if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
3948         {
3949           oldest_time = socket->priv->recv_addr_cache[i].last_used;
3950           oldest_index = i;
3951         }
3952     }
3953
3954   saddr = g_socket_address_new_from_native (native, native_len);
3955
3956   if (socket->priv->recv_addr_cache[oldest_index].addr)
3957     {
3958       g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
3959       g_free (socket->priv->recv_addr_cache[oldest_index].native);
3960     }
3961
3962   socket->priv->recv_addr_cache[oldest_index].native = g_memdup (native, native_len);
3963   socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
3964   socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
3965   socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
3966
3967   return saddr;
3968 }
3969
3970 /**
3971  * g_socket_receive_message:
3972  * @socket: a #GSocket
3973  * @address: (out) (allow-none): a pointer to a #GSocketAddress
3974  *     pointer, or %NULL
3975  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3976  * @num_vectors: the number of elements in @vectors, or -1
3977  * @messages: (array length=num_messages) (allow-none): a pointer which
3978  *    may be filled with an array of #GSocketControlMessages, or %NULL
3979  * @num_messages: a pointer which will be filled with the number of
3980  *    elements in @messages, or %NULL
3981  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3982  * @cancellable: (allow-none): a %GCancellable or %NULL
3983  * @error: a #GError pointer, or %NULL
3984  *
3985  * Receive data from a socket.  This is the most complicated and
3986  * fully-featured version of this call. For easier use, see
3987  * g_socket_receive() and g_socket_receive_from().
3988  *
3989  * If @address is non-%NULL then @address will be set equal to the
3990  * source address of the received packet.
3991  * @address is owned by the caller.
3992  *
3993  * @vector must point to an array of #GInputVector structs and
3994  * @num_vectors must be the length of this array.  These structs
3995  * describe the buffers that received data will be scattered into.
3996  * If @num_vectors is -1, then @vectors is assumed to be terminated
3997  * by a #GInputVector with a %NULL buffer pointer.
3998  *
3999  * As a special case, if @num_vectors is 0 (in which case, @vectors
4000  * may of course be %NULL), then a single byte is received and
4001  * discarded. This is to facilitate the common practice of sending a
4002  * single '\0' byte for the purposes of transferring ancillary data.
4003  *
4004  * @messages, if non-%NULL, will be set to point to a newly-allocated
4005  * array of #GSocketControlMessage instances or %NULL if no such
4006  * messages was received. These correspond to the control messages
4007  * received from the kernel, one #GSocketControlMessage per message
4008  * from the kernel. This array is %NULL-terminated and must be freed
4009  * by the caller using g_free() after calling g_object_unref() on each
4010  * element. If @messages is %NULL, any control messages received will
4011  * be discarded.
4012  *
4013  * @num_messages, if non-%NULL, will be set to the number of control
4014  * messages received.
4015  *
4016  * If both @messages and @num_messages are non-%NULL, then
4017  * @num_messages gives the number of #GSocketControlMessage instances
4018  * in @messages (ie: not including the %NULL terminator).
4019  *
4020  * @flags is an in/out parameter. The commonly available arguments
4021  * for this are available in the #GSocketMsgFlags enum, but the
4022  * values there are the same as the system values, and the flags
4023  * are passed in as-is, so you can pass in system-specific flags too
4024  * (and g_socket_receive_message() may pass system-specific flags out).
4025  *
4026  * As with g_socket_receive(), data may be discarded if @socket is
4027  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
4028  * provide enough buffer space to read a complete message. You can pass
4029  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
4030  * removing it from the receive queue, but there is no portable way to find
4031  * out the length of the message other than by reading it into a
4032  * sufficiently-large buffer.
4033  *
4034  * If the socket is in blocking mode the call will block until there
4035  * is some data to receive, the connection is closed, or there is an
4036  * error. If there is no data available and the socket is in
4037  * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
4038  * returned. To be notified when data is available, wait for the
4039  * %G_IO_IN condition.
4040  *
4041  * On error -1 is returned and @error is set accordingly.
4042  *
4043  * Returns: Number of bytes read, or 0 if the connection was closed by
4044  * the peer, or -1 on error
4045  *
4046  * Since: 2.22
4047  */
4048 gssize
4049 g_socket_receive_message (GSocket                 *socket,
4050                           GSocketAddress         **address,
4051                           GInputVector            *vectors,
4052                           gint                     num_vectors,
4053                           GSocketControlMessage ***messages,
4054                           gint                    *num_messages,
4055                           gint                    *flags,
4056                           GCancellable            *cancellable,
4057                           GError                 **error)
4058 {
4059   GInputVector one_vector;
4060   char one_byte;
4061
4062   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
4063
4064   if (!check_socket (socket, error))
4065     return -1;
4066
4067   if (g_cancellable_set_error_if_cancelled (cancellable, error))
4068     return -1;
4069
4070   if (num_vectors == -1)
4071     {
4072       for (num_vectors = 0;
4073            vectors[num_vectors].buffer != NULL;
4074            num_vectors++)
4075         ;
4076     }
4077
4078   if (num_vectors == 0)
4079     {
4080       one_vector.buffer = &one_byte;
4081       one_vector.size = 1;
4082       num_vectors = 1;
4083       vectors = &one_vector;
4084     }
4085
4086 #ifndef G_OS_WIN32
4087   {
4088     struct msghdr msg;
4089     gssize result;
4090     struct sockaddr_storage one_sockaddr;
4091
4092     /* name */
4093     if (address)
4094       {
4095         msg.msg_name = &one_sockaddr;
4096         msg.msg_namelen = sizeof (struct sockaddr_storage);
4097       }
4098     else
4099       {
4100         msg.msg_name = NULL;
4101         msg.msg_namelen = 0;
4102       }
4103
4104     /* iov */
4105     /* this entire expression will be evaluated at compile time */
4106     if (sizeof *msg.msg_iov == sizeof *vectors &&
4107         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
4108         G_STRUCT_OFFSET (struct iovec, iov_base) ==
4109         G_STRUCT_OFFSET (GInputVector, buffer) &&
4110         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
4111         G_STRUCT_OFFSET (struct iovec, iov_len) ==
4112         G_STRUCT_OFFSET (GInputVector, size))
4113       /* ABI is compatible */
4114       {
4115         msg.msg_iov = (struct iovec *) vectors;
4116         msg.msg_iovlen = num_vectors;
4117       }
4118     else
4119       /* ABI is incompatible */
4120       {
4121         gint i;
4122
4123         msg.msg_iov = g_newa (struct iovec, num_vectors);
4124         for (i = 0; i < num_vectors; i++)
4125           {
4126             msg.msg_iov[i].iov_base = vectors[i].buffer;
4127             msg.msg_iov[i].iov_len = vectors[i].size;
4128           }
4129         msg.msg_iovlen = num_vectors;
4130       }
4131
4132     /* control */
4133     msg.msg_control = g_alloca (2048);
4134     msg.msg_controllen = 2048;
4135
4136     /* flags */
4137     if (flags != NULL)
4138       msg.msg_flags = *flags;
4139     else
4140       msg.msg_flags = 0;
4141
4142     /* We always set the close-on-exec flag so we don't leak file
4143      * descriptors into child processes.  Note that gunixfdmessage.c
4144      * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
4145      */
4146 #ifdef MSG_CMSG_CLOEXEC
4147     msg.msg_flags |= MSG_CMSG_CLOEXEC;
4148 #endif
4149
4150     /* do it */
4151     while (1)
4152       {
4153         if (socket->priv->blocking &&
4154             !g_socket_condition_wait (socket,
4155                                       G_IO_IN, cancellable, error))
4156           return -1;
4157
4158         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4159 #ifdef MSG_CMSG_CLOEXEC 
4160         if (result < 0 && get_socket_errno () == EINVAL)
4161           {
4162             /* We must be running on an old kernel.  Call without the flag. */
4163             msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
4164             result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
4165           }
4166 #endif
4167
4168         if (result < 0)
4169           {
4170             int errsv = get_socket_errno ();
4171
4172             if (errsv == EINTR)
4173               continue;
4174
4175             if (socket->priv->blocking &&
4176                 (errsv == EWOULDBLOCK ||
4177                  errsv == EAGAIN))
4178               continue;
4179
4180             g_set_error (error, G_IO_ERROR,
4181                          socket_io_error_from_errno (errsv),
4182                          _("Error receiving message: %s"), socket_strerror (errsv));
4183
4184             return -1;
4185           }
4186         break;
4187       }
4188
4189     /* decode address */
4190     if (address != NULL)
4191       {
4192         *address = cache_recv_address (socket, msg.msg_name, msg.msg_namelen);
4193       }
4194
4195     /* decode control messages */
4196     {
4197       GPtrArray *my_messages = NULL;
4198       struct cmsghdr *cmsg;
4199
4200       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
4201         {
4202           GSocketControlMessage *message;
4203
4204           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4205                                                           cmsg->cmsg_type,
4206                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4207                                                           CMSG_DATA (cmsg));
4208           if (message == NULL)
4209             /* We've already spewed about the problem in the
4210                deserialization code, so just continue */
4211             continue;
4212
4213           if (messages == NULL)
4214             {
4215               /* we have to do it this way if the user ignores the
4216                * messages so that we will close any received fds.
4217                */
4218               g_object_unref (message);
4219             }
4220           else
4221             {
4222               if (my_messages == NULL)
4223                 my_messages = g_ptr_array_new ();
4224               g_ptr_array_add (my_messages, message);
4225             }
4226         }
4227
4228       if (num_messages)
4229         *num_messages = my_messages != NULL ? my_messages->len : 0;
4230
4231       if (messages)
4232         {
4233           if (my_messages == NULL)
4234             {
4235               *messages = NULL;
4236             }
4237           else
4238             {
4239               g_ptr_array_add (my_messages, NULL);
4240               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4241             }
4242         }
4243       else
4244         {
4245           g_assert (my_messages == NULL);
4246         }
4247     }
4248
4249     /* capture the flags */
4250     if (flags != NULL)
4251       *flags = msg.msg_flags;
4252
4253     return result;
4254   }
4255 #else
4256   {
4257     struct sockaddr_storage addr;
4258     int addrlen;
4259     DWORD bytes_received;
4260     DWORD win_flags;
4261     int result;
4262     WSABUF *bufs;
4263     gint i;
4264
4265     /* iov */
4266     bufs = g_newa (WSABUF, num_vectors);
4267     for (i = 0; i < num_vectors; i++)
4268       {
4269         bufs[i].buf = (char *)vectors[i].buffer;
4270         bufs[i].len = (gulong)vectors[i].size;
4271       }
4272
4273     /* flags */
4274     if (flags != NULL)
4275       win_flags = *flags;
4276     else
4277       win_flags = 0;
4278
4279     /* do it */
4280     while (1)
4281       {
4282         if (socket->priv->blocking &&
4283             !g_socket_condition_wait (socket,
4284                                       G_IO_IN, cancellable, error))
4285           return -1;
4286
4287         addrlen = sizeof addr;
4288         if (address)
4289           result = WSARecvFrom (socket->priv->fd,
4290                                 bufs, num_vectors,
4291                                 &bytes_received, &win_flags,
4292                                 (struct sockaddr *)&addr, &addrlen,
4293                                 NULL, NULL);
4294         else
4295           result = WSARecv (socket->priv->fd,
4296                             bufs, num_vectors,
4297                             &bytes_received, &win_flags,
4298                             NULL, NULL);
4299         if (result != 0)
4300           {
4301             int errsv = get_socket_errno ();
4302
4303             if (errsv == WSAEINTR)
4304               continue;
4305
4306             win32_unset_event_mask (socket, FD_READ);
4307
4308             if (socket->priv->blocking &&
4309                 errsv == WSAEWOULDBLOCK)
4310               continue;
4311
4312             g_set_error (error, G_IO_ERROR,
4313                          socket_io_error_from_errno (errsv),
4314                          _("Error receiving message: %s"), socket_strerror (errsv));
4315
4316             return -1;
4317           }
4318         win32_unset_event_mask (socket, FD_READ);
4319         break;
4320       }
4321
4322     /* decode address */
4323     if (address != NULL)
4324       {
4325         *address = cache_recv_address (socket, &addr, addrlen);
4326       }
4327
4328     /* capture the flags */
4329     if (flags != NULL)
4330       *flags = win_flags;
4331
4332     if (messages != NULL)
4333       *messages = NULL;
4334     if (num_messages != NULL)
4335       *num_messages = 0;
4336
4337     return bytes_received;
4338   }
4339 #endif
4340 }
4341
4342 /**
4343  * g_socket_get_credentials:
4344  * @socket: a #GSocket.
4345  * @error: #GError for error reporting, or %NULL to ignore.
4346  *
4347  * Returns the credentials of the foreign process connected to this
4348  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
4349  * sockets).
4350  *
4351  * If this operation isn't supported on the OS, the method fails with
4352  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
4353  * by reading the %SO_PEERCRED option on the underlying socket.
4354  *
4355  * Other ways to obtain credentials from a foreign peer includes the
4356  * #GUnixCredentialsMessage type and
4357  * g_unix_connection_send_credentials() /
4358  * g_unix_connection_receive_credentials() functions.
4359  *
4360  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
4361  * that must be freed with g_object_unref().
4362  *
4363  * Since: 2.26
4364  */
4365 GCredentials *
4366 g_socket_get_credentials (GSocket   *socket,
4367                           GError   **error)
4368 {
4369   GCredentials *ret;
4370
4371   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
4372   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4373
4374   ret = NULL;
4375
4376 #if defined(__linux__) || defined(__OpenBSD__)
4377   {
4378     socklen_t optlen;
4379 #if defined(__linux__)
4380     struct ucred native_creds;
4381     optlen = sizeof (struct ucred);
4382 #elif defined(__OpenBSD__)
4383     struct sockpeercred native_creds;
4384     optlen = sizeof (struct sockpeercred);
4385 #endif
4386     if (getsockopt (socket->priv->fd,
4387                     SOL_SOCKET,
4388                     SO_PEERCRED,
4389                     (void *)&native_creds,
4390                     &optlen) != 0)
4391       {
4392         int errsv = get_socket_errno ();
4393         g_set_error (error,
4394                      G_IO_ERROR,
4395                      socket_io_error_from_errno (errsv),
4396                      _("Unable to get pending error: %s"),
4397                      socket_strerror (errsv));
4398       }
4399     else
4400       {
4401         ret = g_credentials_new ();
4402         g_credentials_set_native (ret,
4403 #if defined(__linux__)
4404                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
4405 #elif defined(__OpenBSD__)
4406                                   G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED,
4407 #endif
4408                                   &native_creds);
4409       }
4410   }
4411 #else
4412   g_set_error_literal (error,
4413                        G_IO_ERROR,
4414                        G_IO_ERROR_NOT_SUPPORTED,
4415                        _("g_socket_get_credentials not implemented for this OS"));
4416 #endif
4417
4418   return ret;
4419 }