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