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