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