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