Silence a bunch of -Wunused-but-set-variable warnings
[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 #include <errno.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <stdlib.h>
36
37 #ifndef G_OS_WIN32
38 # include <fcntl.h>
39 # include <unistd.h>
40 #endif
41
42 #ifdef HAVE_SYS_UIO_H
43 #include <sys/uio.h>
44 #endif
45
46 #include "gcancellable.h"
47 #include "gioenumtypes.h"
48 #include "ginetaddress.h"
49 #include "ginitable.h"
50 #include "gioerror.h"
51 #include "gioenums.h"
52 #include "gioerror.h"
53 #include "gio-marshal.h"
54 #include "gnetworkingprivate.h"
55 #include "gsocketaddress.h"
56 #include "gsocketcontrolmessage.h"
57 #include "gcredentials.h"
58 #include "glibintl.h"
59
60 /**
61  * SECTION:gsocket
62  * @short_description: Low-level socket object
63  * @include: gio/gio.h
64  * @see_also: #GInitable
65  *
66  * A #GSocket is a low-level networking primitive. It is a more or less
67  * direct mapping of the BSD socket API in a portable GObject based API.
68  * It supports both the UNIX socket implementations and winsock2 on Windows.
69  *
70  * #GSocket is the platform independent base upon which the higher level
71  * network primitives are based. Applications are not typically meant to
72  * use it directly, but rather through classes like #GSocketClient,
73  * #GSocketService and #GSocketConnection. However there may be cases where
74  * direct use of #GSocket is useful.
75  *
76  * #GSocket implements the #GInitable interface, so if it is manually constructed
77  * by e.g. g_object_new() you must call g_initable_init() and check the
78  * results before using the object. This is done automatically in
79  * g_socket_new() and g_socket_new_from_fd(), so these functions can return
80  * %NULL.
81  *
82  * Sockets operate in two general modes, blocking or non-blocking. When
83  * in blocking mode all operations block until the requested operation
84  * is finished or there is an error. In non-blocking mode all calls that
85  * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
86  * To know when a call would successfully run you can call g_socket_condition_check(),
87  * or g_socket_condition_wait(). You can also use g_socket_create_source() and
88  * attach it to a #GMainContext to get callbacks when I/O is possible.
89  * Note that all sockets are always set to non blocking mode in the system, and
90  * blocking mode is emulated in GSocket.
91  *
92  * When working in non-blocking mode applications should always be able to
93  * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
94  * function said that I/O was possible. This can easily happen in case
95  * of a race condition in the application, but it can also happen for other
96  * reasons. For instance, on Windows a socket is always seen as writable
97  * until a write returns %G_IO_ERROR_WOULD_BLOCK.
98  *
99  * #GSocket<!-- -->s can be either connection oriented or datagram based.
100  * For connection oriented types you must first establish a connection by
101  * either connecting to an address or accepting a connection from another
102  * address. For connectionless socket types the target/source address is
103  * specified or received in each I/O operation.
104  *
105  * All socket file descriptors are set to be close-on-exec.
106  *
107  * Note that creating a #GSocket causes the signal %SIGPIPE to be
108  * ignored for the remainder of the program. If you are writing a
109  * command-line utility that uses #GSocket, you may need to take into
110  * account the fact that your program will not automatically be killed
111  * if it tries to write to %stdout after it has been closed.
112  *
113  * Since: 2.22
114  */
115
116 static void     g_socket_initable_iface_init (GInitableIface  *iface);
117 static gboolean g_socket_initable_init       (GInitable       *initable,
118                                               GCancellable    *cancellable,
119                                               GError         **error);
120
121 G_DEFINE_TYPE_WITH_CODE (GSocket, g_socket, G_TYPE_OBJECT,
122                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
123                                                 g_socket_initable_iface_init));
124
125 enum
126 {
127   PROP_0,
128   PROP_FAMILY,
129   PROP_TYPE,
130   PROP_PROTOCOL,
131   PROP_FD,
132   PROP_BLOCKING,
133   PROP_LISTEN_BACKLOG,
134   PROP_KEEPALIVE,
135   PROP_LOCAL_ADDRESS,
136   PROP_REMOTE_ADDRESS,
137   PROP_TIMEOUT
138 };
139
140 struct _GSocketPrivate
141 {
142   GSocketFamily   family;
143   GSocketType     type;
144   GSocketProtocol protocol;
145   gint            fd;
146   gint            listen_backlog;
147   guint           timeout;
148   GError         *construct_error;
149   GSocketAddress *remote_address;
150   guint           inited : 1;
151   guint           blocking : 1;
152   guint           keepalive : 1;
153   guint           closed : 1;
154   guint           connected : 1;
155   guint           listening : 1;
156   guint           timed_out : 1;
157   guint           connect_pending : 1;
158 #ifdef G_OS_WIN32
159   WSAEVENT        event;
160   int             current_events;
161   int             current_errors;
162   int             selected_events;
163   GList          *requested_conditions; /* list of requested GIOCondition * */
164 #endif
165 };
166
167 static int
168 get_socket_errno (void)
169 {
170 #ifndef G_OS_WIN32
171   return errno;
172 #else
173   return WSAGetLastError ();
174 #endif
175 }
176
177 static GIOErrorEnum
178 socket_io_error_from_errno (int err)
179 {
180 #ifndef G_OS_WIN32
181   return g_io_error_from_errno (err);
182 #else
183   switch (err)
184     {
185     case WSAEADDRINUSE:
186       return G_IO_ERROR_ADDRESS_IN_USE;
187     case WSAEWOULDBLOCK:
188       return G_IO_ERROR_WOULD_BLOCK;
189     case WSAEACCES:
190       return G_IO_ERROR_PERMISSION_DENIED;
191     case WSA_INVALID_HANDLE:
192     case WSA_INVALID_PARAMETER:
193     case WSAEBADF:
194     case WSAENOTSOCK:
195       return G_IO_ERROR_INVALID_ARGUMENT;
196     case WSAEPROTONOSUPPORT:
197       return G_IO_ERROR_NOT_SUPPORTED;
198     case WSAECANCELLED:
199       return G_IO_ERROR_CANCELLED;
200     case WSAESOCKTNOSUPPORT:
201     case WSAEOPNOTSUPP:
202     case WSAEPFNOSUPPORT:
203     case WSAEAFNOSUPPORT:
204       return G_IO_ERROR_NOT_SUPPORTED;
205     default:
206       return G_IO_ERROR_FAILED;
207     }
208 #endif
209 }
210
211 static const char *
212 socket_strerror (int err)
213 {
214 #ifndef G_OS_WIN32
215   return g_strerror (err);
216 #else
217   static GStaticPrivate last_msg = G_STATIC_PRIVATE_INIT;
218   char *msg;
219
220   msg = g_win32_error_message (err);
221   g_static_private_set (&last_msg, msg, g_free);
222
223   return msg;
224 #endif
225 }
226
227 #ifdef G_OS_WIN32
228 #define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
229 static void
230 _win32_unset_event_mask (GSocket *socket, int mask)
231 {
232   socket->priv->current_events &= ~mask;
233   socket->priv->current_errors &= ~mask;
234 }
235 #else
236 #define win32_unset_event_mask(_socket, _mask)
237 #endif
238
239 static void
240 set_fd_nonblocking (int fd)
241 {
242 #ifndef G_OS_WIN32
243   glong arg;
244 #else
245   gulong arg;
246 #endif
247
248 #ifndef G_OS_WIN32
249   if ((arg = fcntl (fd, F_GETFL, NULL)) < 0)
250     {
251       g_warning ("Error getting socket status flags: %s", socket_strerror (errno));
252       arg = 0;
253     }
254
255   arg = arg | O_NONBLOCK;
256
257   if (fcntl (fd, F_SETFL, arg) < 0)
258       g_warning ("Error setting socket status flags: %s", socket_strerror (errno));
259 #else
260   arg = TRUE;
261
262   if (ioctlsocket (fd, FIONBIO, &arg) == SOCKET_ERROR)
263     {
264       int errsv = get_socket_errno ();
265       g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
266     }
267 #endif
268 }
269
270 static gboolean
271 check_socket (GSocket *socket,
272               GError **error)
273 {
274   if (!socket->priv->inited)
275     {
276       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
277                            _("Invalid socket, not initialized"));
278       return FALSE;
279     }
280
281   if (socket->priv->construct_error)
282     {
283       g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
284                    _("Invalid socket, initialization failed due to: %s"),
285                    socket->priv->construct_error->message);
286       return FALSE;
287     }
288
289   if (socket->priv->closed)
290     {
291       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
292                            _("Socket is already closed"));
293       return FALSE;
294     }
295
296   if (socket->priv->timed_out)
297     {
298       socket->priv->timed_out = FALSE;
299       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
300                            _("Socket I/O timed out"));
301       return FALSE;
302     }
303
304   return TRUE;
305 }
306
307 static void
308 g_socket_details_from_fd (GSocket *socket)
309 {
310   struct sockaddr_storage address;
311   gint fd;
312   guint addrlen;
313   guint optlen;
314   int value;
315   int errsv;
316 #ifdef G_OS_WIN32
317   /* See bug #611756 */
318   BOOL bool_val = FALSE;
319 #else
320   int bool_val;
321 #endif
322
323   fd = socket->priv->fd;
324   optlen = sizeof value;
325   if (getsockopt (fd, SOL_SOCKET, SO_TYPE, (void *)&value, &optlen) != 0)
326     {
327       errsv = get_socket_errno ();
328
329       switch (errsv)
330         {
331 #ifdef ENOTSOCK
332          case ENOTSOCK:
333 #endif
334 #ifdef WSAENOTSOCK
335          case WSAENOTSOCK:
336 #endif
337          case EBADF:
338           /* programmer error */
339           g_error ("creating GSocket from fd %d: %s\n",
340                    fd, socket_strerror (errsv));
341          default:
342            break;
343         }
344
345       goto err;
346     }
347
348   g_assert (optlen == sizeof value);
349   switch (value)
350     {
351      case SOCK_STREAM:
352       socket->priv->type = G_SOCKET_TYPE_STREAM;
353       break;
354
355      case SOCK_DGRAM:
356       socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
357       break;
358
359      case SOCK_SEQPACKET:
360       socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
361       break;
362
363      default:
364       socket->priv->type = G_SOCKET_TYPE_INVALID;
365       break;
366     }
367
368   addrlen = sizeof address;
369   if (getsockname (fd, (struct sockaddr *) &address, &addrlen) != 0)
370     {
371       errsv = get_socket_errno ();
372       goto err;
373     }
374
375   g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
376             sizeof address.ss_family <= addrlen);
377   switch (address.ss_family)
378     {
379      case G_SOCKET_FAMILY_IPV4:
380      case G_SOCKET_FAMILY_IPV6:
381        socket->priv->family = address.ss_family;
382        switch (socket->priv->type)
383          {
384          case G_SOCKET_TYPE_STREAM:
385            socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
386            break;
387
388          case G_SOCKET_TYPE_DATAGRAM:
389            socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
390            break;
391
392          case G_SOCKET_TYPE_SEQPACKET:
393            socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
394            break;
395
396          default:
397            break;
398          }
399        break;
400
401      case G_SOCKET_FAMILY_UNIX:
402        socket->priv->family = G_SOCKET_FAMILY_UNIX;
403        socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
404        break;
405
406      default:
407        socket->priv->family = G_SOCKET_FAMILY_INVALID;
408        break;
409     }
410
411   if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
412     {
413       addrlen = sizeof address;
414       if (getpeername (fd, (struct sockaddr *) &address, &addrlen) >= 0)
415         socket->priv->connected = TRUE;
416     }
417
418   optlen = sizeof bool_val;
419   if (getsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
420                   (void *)&bool_val, &optlen) == 0)
421     {
422 #ifndef G_OS_WIN32
423       /* Experimentation indicates that the SO_KEEPALIVE value is
424        * actually a char on Windows, even if documentation claims it
425        * to be a BOOL which is a typedef for int. So this g_assert()
426        * fails. See bug #611756.
427        */
428       g_assert (optlen == sizeof bool_val);
429 #endif
430       socket->priv->keepalive = !!bool_val;
431     }
432   else
433     {
434       /* Can't read, maybe not supported, assume FALSE */
435       socket->priv->keepalive = FALSE;
436     }
437
438   return;
439
440  err:
441   g_set_error (&socket->priv->construct_error, G_IO_ERROR,
442                socket_io_error_from_errno (errsv),
443                _("creating GSocket from fd: %s"),
444                socket_strerror (errsv));
445 }
446
447 static gint
448 g_socket_create_socket (GSocketFamily   family,
449                         GSocketType     type,
450                         int             protocol,
451                         GError        **error)
452 {
453   gint native_type;
454   gint fd;
455
456   switch (type)
457     {
458      case G_SOCKET_TYPE_STREAM:
459       native_type = SOCK_STREAM;
460       break;
461
462      case G_SOCKET_TYPE_DATAGRAM:
463       native_type = SOCK_DGRAM;
464       break;
465
466      case G_SOCKET_TYPE_SEQPACKET:
467       native_type = SOCK_SEQPACKET;
468       break;
469
470      default:
471       g_assert_not_reached ();
472     }
473
474   if (protocol == -1)
475     {
476       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
477                    _("Unable to create socket: %s"), _("Unknown protocol was specified"));
478       return -1;
479     }
480
481 #ifdef SOCK_CLOEXEC
482   fd = socket (family, native_type | SOCK_CLOEXEC, protocol);
483   /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
484   if (fd < 0 && errno == EINVAL)
485 #endif
486     fd = socket (family, native_type, protocol);
487
488   if (fd < 0)
489     {
490       int errsv = get_socket_errno ();
491
492       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
493                    _("Unable to create socket: %s"), socket_strerror (errsv));
494     }
495
496 #ifndef G_OS_WIN32
497   {
498     int flags;
499
500     /* We always want to set close-on-exec to protect users. If you
501        need to so some weird inheritance to exec you can re-enable this
502        using lower level hacks with g_socket_get_fd(). */
503     flags = fcntl (fd, F_GETFD, 0);
504     if (flags != -1 &&
505         (flags & FD_CLOEXEC) == 0)
506       {
507         flags |= FD_CLOEXEC;
508         fcntl (fd, F_SETFD, flags);
509       }
510   }
511 #endif
512
513   return fd;
514 }
515
516 static void
517 g_socket_constructed (GObject *object)
518 {
519   GSocket *socket = G_SOCKET (object);
520
521   if (socket->priv->fd >= 0)
522     /* create socket->priv info from the fd */
523     g_socket_details_from_fd (socket);
524
525   else
526     /* create the fd from socket->priv info */
527     socket->priv->fd = g_socket_create_socket (socket->priv->family,
528                                                socket->priv->type,
529                                                socket->priv->protocol,
530                                                &socket->priv->construct_error);
531
532   /* Always use native nonblocking sockets, as
533      windows sets sockets to nonblocking automatically
534      in certain operations. This way we make things work
535      the same on all platforms */
536   if (socket->priv->fd != -1)
537     set_fd_nonblocking (socket->priv->fd);
538 }
539
540 static void
541 g_socket_get_property (GObject    *object,
542                        guint       prop_id,
543                        GValue     *value,
544                        GParamSpec *pspec)
545 {
546   GSocket *socket = G_SOCKET (object);
547   GSocketAddress *address;
548
549   switch (prop_id)
550     {
551       case PROP_FAMILY:
552         g_value_set_enum (value, socket->priv->family);
553         break;
554
555       case PROP_TYPE:
556         g_value_set_enum (value, socket->priv->type);
557         break;
558
559       case PROP_PROTOCOL:
560         g_value_set_enum (value, socket->priv->protocol);
561         break;
562
563       case PROP_FD:
564         g_value_set_int (value, socket->priv->fd);
565         break;
566
567       case PROP_BLOCKING:
568         g_value_set_boolean (value, socket->priv->blocking);
569         break;
570
571       case PROP_LISTEN_BACKLOG:
572         g_value_set_int (value, socket->priv->listen_backlog);
573         break;
574
575       case PROP_KEEPALIVE:
576         g_value_set_boolean (value, socket->priv->keepalive);
577         break;
578
579       case PROP_LOCAL_ADDRESS:
580         address = g_socket_get_local_address (socket, NULL);
581         g_value_take_object (value, address);
582         break;
583
584       case PROP_REMOTE_ADDRESS:
585         address = g_socket_get_remote_address (socket, NULL);
586         g_value_take_object (value, address);
587         break;
588
589       case PROP_TIMEOUT:
590         g_value_set_uint (value, socket->priv->timeout);
591         break;
592
593       default:
594         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
595     }
596 }
597
598 static void
599 g_socket_set_property (GObject      *object,
600                        guint         prop_id,
601                        const GValue *value,
602                        GParamSpec   *pspec)
603 {
604   GSocket *socket = G_SOCKET (object);
605
606   switch (prop_id)
607     {
608       case PROP_FAMILY:
609         socket->priv->family = g_value_get_enum (value);
610         break;
611
612       case PROP_TYPE:
613         socket->priv->type = g_value_get_enum (value);
614         break;
615
616       case PROP_PROTOCOL:
617         socket->priv->protocol = g_value_get_enum (value);
618         break;
619
620       case PROP_FD:
621         socket->priv->fd = g_value_get_int (value);
622         break;
623
624       case PROP_BLOCKING:
625         g_socket_set_blocking (socket, g_value_get_boolean (value));
626         break;
627
628       case PROP_LISTEN_BACKLOG:
629         g_socket_set_listen_backlog (socket, g_value_get_int (value));
630         break;
631
632       case PROP_KEEPALIVE:
633         g_socket_set_keepalive (socket, g_value_get_boolean (value));
634         break;
635
636       case PROP_TIMEOUT:
637         g_socket_set_timeout (socket, g_value_get_uint (value));
638         break;
639
640       default:
641         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
642     }
643 }
644
645 static void
646 g_socket_finalize (GObject *object)
647 {
648   GSocket *socket = G_SOCKET (object);
649
650   g_clear_error (&socket->priv->construct_error);
651
652   if (socket->priv->fd != -1 &&
653       !socket->priv->closed)
654     g_socket_close (socket, NULL);
655
656   if (socket->priv->remote_address)
657     g_object_unref (socket->priv->remote_address);
658
659 #ifdef G_OS_WIN32
660   if (socket->priv->event != WSA_INVALID_EVENT)
661     {
662       WSACloseEvent (socket->priv->event);
663       socket->priv->event = WSA_INVALID_EVENT;
664     }
665
666   g_assert (socket->priv->requested_conditions == NULL);
667 #endif
668
669   if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
670     (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
671 }
672
673 static void
674 g_socket_class_init (GSocketClass *klass)
675 {
676   GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
677   volatile GType type;
678
679   /* Make sure winsock has been initialized */
680   type = g_inet_address_get_type ();
681   (type); /* To avoid -Wunused-but-set-variable */
682
683 #ifdef SIGPIPE
684   /* There is no portable, thread-safe way to avoid having the process
685    * be killed by SIGPIPE when calling send() or sendmsg(), so we are
686    * forced to simply ignore the signal process-wide.
687    */
688   signal (SIGPIPE, SIG_IGN);
689 #endif
690
691   g_type_class_add_private (klass, sizeof (GSocketPrivate));
692
693   gobject_class->finalize = g_socket_finalize;
694   gobject_class->constructed = g_socket_constructed;
695   gobject_class->set_property = g_socket_set_property;
696   gobject_class->get_property = g_socket_get_property;
697
698   g_object_class_install_property (gobject_class, PROP_FAMILY,
699                                    g_param_spec_enum ("family",
700                                                       P_("Socket family"),
701                                                       P_("The sockets address family"),
702                                                       G_TYPE_SOCKET_FAMILY,
703                                                       G_SOCKET_FAMILY_INVALID,
704                                                       G_PARAM_CONSTRUCT_ONLY |
705                                                       G_PARAM_READWRITE |
706                                                       G_PARAM_STATIC_STRINGS));
707
708   g_object_class_install_property (gobject_class, PROP_TYPE,
709                                    g_param_spec_enum ("type",
710                                                       P_("Socket type"),
711                                                       P_("The sockets type"),
712                                                       G_TYPE_SOCKET_TYPE,
713                                                       G_SOCKET_TYPE_STREAM,
714                                                       G_PARAM_CONSTRUCT_ONLY |
715                                                       G_PARAM_READWRITE |
716                                                       G_PARAM_STATIC_STRINGS));
717
718   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
719                                    g_param_spec_enum ("protocol",
720                                                       P_("Socket protocol"),
721                                                       P_("The id of the protocol to use, or -1 for unknown"),
722                                                       G_TYPE_SOCKET_PROTOCOL,
723                                                       G_SOCKET_PROTOCOL_UNKNOWN,
724                                                       G_PARAM_CONSTRUCT_ONLY |
725                                                       G_PARAM_READWRITE |
726                                                       G_PARAM_STATIC_STRINGS));
727
728   g_object_class_install_property (gobject_class, PROP_FD,
729                                    g_param_spec_int ("fd",
730                                                      P_("File descriptor"),
731                                                      P_("The sockets file descriptor"),
732                                                      G_MININT,
733                                                      G_MAXINT,
734                                                      -1,
735                                                      G_PARAM_CONSTRUCT_ONLY |
736                                                      G_PARAM_READWRITE |
737                                                      G_PARAM_STATIC_STRINGS));
738
739   g_object_class_install_property (gobject_class, PROP_BLOCKING,
740                                    g_param_spec_boolean ("blocking",
741                                                          P_("blocking"),
742                                                          P_("Whether or not I/O on this socket is blocking"),
743                                                          TRUE,
744                                                          G_PARAM_READWRITE |
745                                                          G_PARAM_STATIC_STRINGS));
746
747   g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
748                                    g_param_spec_int ("listen-backlog",
749                                                      P_("Listen backlog"),
750                                                      P_("Outstanding connections in the listen queue"),
751                                                      0,
752                                                      SOMAXCONN,
753                                                      10,
754                                                      G_PARAM_READWRITE |
755                                                      G_PARAM_STATIC_STRINGS));
756
757   g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
758                                    g_param_spec_boolean ("keepalive",
759                                                          P_("Keep connection alive"),
760                                                          P_("Keep connection alive by sending periodic pings"),
761                                                          FALSE,
762                                                          G_PARAM_READWRITE |
763                                                          G_PARAM_STATIC_STRINGS));
764
765   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
766                                    g_param_spec_object ("local-address",
767                                                         P_("Local address"),
768                                                         P_("The local address the socket is bound to"),
769                                                         G_TYPE_SOCKET_ADDRESS,
770                                                         G_PARAM_READABLE |
771                                                         G_PARAM_STATIC_STRINGS));
772
773   g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
774                                    g_param_spec_object ("remote-address",
775                                                         P_("Remote address"),
776                                                         P_("The remote address the socket is connected to"),
777                                                         G_TYPE_SOCKET_ADDRESS,
778                                                         G_PARAM_READABLE |
779                                                         G_PARAM_STATIC_STRINGS));
780
781   /**
782    * GSocket:timeout:
783    *
784    * The timeout in seconds on socket I/O
785    *
786    * Since: 2.26
787    */
788   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
789                                    g_param_spec_uint ("timeout",
790                                                       P_("Timeout"),
791                                                       P_("The timeout in seconds on socket I/O"),
792                                                       0,
793                                                       G_MAXUINT,
794                                                       0,
795                                                       G_PARAM_READWRITE |
796                                                       G_PARAM_STATIC_STRINGS));
797 }
798
799 static void
800 g_socket_initable_iface_init (GInitableIface *iface)
801 {
802   iface->init = g_socket_initable_init;
803 }
804
805 static void
806 g_socket_init (GSocket *socket)
807 {
808   socket->priv = G_TYPE_INSTANCE_GET_PRIVATE (socket, G_TYPE_SOCKET, GSocketPrivate);
809
810   socket->priv->fd = -1;
811   socket->priv->blocking = TRUE;
812   socket->priv->listen_backlog = 10;
813   socket->priv->construct_error = NULL;
814 #ifdef G_OS_WIN32
815   socket->priv->event = WSA_INVALID_EVENT;
816 #endif
817 }
818
819 static gboolean
820 g_socket_initable_init (GInitable *initable,
821                         GCancellable *cancellable,
822                         GError  **error)
823 {
824   GSocket  *socket;
825
826   g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
827
828   socket = G_SOCKET (initable);
829
830   if (cancellable != NULL)
831     {
832       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
833                            _("Cancellable initialization not supported"));
834       return FALSE;
835     }
836
837   socket->priv->inited = TRUE;
838
839   if (socket->priv->construct_error)
840     {
841       if (error)
842         *error = g_error_copy (socket->priv->construct_error);
843       return FALSE;
844     }
845
846
847   return TRUE;
848 }
849
850 /**
851  * g_socket_new:
852  * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
853  * @type: the socket type to use.
854  * @protocol: the id of the protocol to use, or 0 for default.
855  * @error: #GError for error reporting, or %NULL to ignore.
856  *
857  * Creates a new #GSocket with the defined family, type and protocol.
858  * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
859  * for the family and type is used.
860  *
861  * The @protocol is a family and type specific int that specifies what
862  * kind of protocol to use. #GSocketProtocol lists several common ones.
863  * Many families only support one protocol, and use 0 for this, others
864  * support several and using 0 means to use the default protocol for
865  * the family and type.
866  *
867  * The protocol id is passed directly to the operating
868  * system, so you can use protocols not listed in #GSocketProtocol if you
869  * know the protocol number used for it.
870  *
871  * Returns: a #GSocket or %NULL on error.
872  *     Free the returned object with g_object_unref().
873  *
874  * Since: 2.22
875  */
876 GSocket *
877 g_socket_new (GSocketFamily     family,
878               GSocketType       type,
879               GSocketProtocol   protocol,
880               GError          **error)
881 {
882   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
883                                    NULL, error,
884                                    "family", family,
885                                    "type", type,
886                                    "protocol", protocol,
887                                    NULL));
888 }
889
890 /**
891  * g_socket_new_from_fd:
892  * @fd: a native socket file descriptor.
893  * @error: #GError for error reporting, or %NULL to ignore.
894  *
895  * Creates a new #GSocket from a native file descriptor
896  * or winsock SOCKET handle.
897  *
898  * This reads all the settings from the file descriptor so that
899  * all properties should work. Note that the file descriptor
900  * will be set to non-blocking mode, independent on the blocking
901  * mode of the #GSocket.
902  *
903  * Returns: a #GSocket or %NULL on error.
904  *     Free the returned object with g_object_unref().
905  *
906  * Since: 2.22
907  */
908 GSocket *
909 g_socket_new_from_fd (gint     fd,
910                       GError **error)
911 {
912   return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
913                                    NULL, error,
914                                    "fd", fd,
915                                    NULL));
916 }
917
918 /**
919  * g_socket_set_blocking:
920  * @socket: a #GSocket.
921  * @blocking: Whether to use blocking I/O or not.
922  *
923  * Sets the blocking mode of the socket. In blocking mode
924  * all operations block until they succeed or there is an error. In
925  * non-blocking mode all functions return results immediately or
926  * with a %G_IO_ERROR_WOULD_BLOCK error.
927  *
928  * All sockets are created in blocking mode. However, note that the
929  * platform level socket is always non-blocking, and blocking mode
930  * is a GSocket level feature.
931  *
932  * Since: 2.22
933  */
934 void
935 g_socket_set_blocking (GSocket  *socket,
936                        gboolean  blocking)
937 {
938   g_return_if_fail (G_IS_SOCKET (socket));
939
940   blocking = !!blocking;
941
942   if (socket->priv->blocking == blocking)
943     return;
944
945   socket->priv->blocking = blocking;
946   g_object_notify (G_OBJECT (socket), "blocking");
947 }
948
949 /**
950  * g_socket_get_blocking:
951  * @socket: a #GSocket.
952  *
953  * Gets the blocking mode of the socket. For details on blocking I/O,
954  * see g_socket_set_blocking().
955  *
956  * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
957  *
958  * Since: 2.22
959  */
960 gboolean
961 g_socket_get_blocking (GSocket *socket)
962 {
963   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
964
965   return socket->priv->blocking;
966 }
967
968 /**
969  * g_socket_set_keepalive:
970  * @socket: a #GSocket.
971  * @keepalive: Value for the keepalive flag
972  *
973  * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
974  * this flag is set on a socket, the system will attempt to verify that the
975  * remote socket endpoint is still present if a sufficiently long period of
976  * time passes with no data being exchanged. If the system is unable to
977  * verify the presence of the remote endpoint, it will automatically close
978  * the connection.
979  *
980  * This option is only functional on certain kinds of sockets. (Notably,
981  * %G_SOCKET_PROTOCOL_TCP sockets.)
982  *
983  * The exact time between pings is system- and protocol-dependent, but will
984  * normally be at least two hours. Most commonly, you would set this flag
985  * on a server socket if you want to allow clients to remain idle for long
986  * periods of time, but also want to ensure that connections are eventually
987  * garbage-collected if clients crash or become unreachable.
988  *
989  * Since: 2.22
990  */
991 void
992 g_socket_set_keepalive (GSocket  *socket,
993                         gboolean  keepalive)
994 {
995   int value;
996
997   g_return_if_fail (G_IS_SOCKET (socket));
998
999   keepalive = !!keepalive;
1000   if (socket->priv->keepalive == keepalive)
1001     return;
1002
1003   value = (gint) keepalive;
1004   if (setsockopt (socket->priv->fd, SOL_SOCKET, SO_KEEPALIVE,
1005                   (gpointer) &value, sizeof (value)) < 0)
1006     {
1007       int errsv = get_socket_errno ();
1008       g_warning ("error setting keepalive: %s", socket_strerror (errsv));
1009       return;
1010     }
1011
1012   socket->priv->keepalive = keepalive;
1013   g_object_notify (G_OBJECT (socket), "keepalive");
1014 }
1015
1016 /**
1017  * g_socket_get_keepalive:
1018  * @socket: a #GSocket.
1019  *
1020  * Gets the keepalive mode of the socket. For details on this,
1021  * see g_socket_set_keepalive().
1022  *
1023  * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1024  *
1025  * Since: 2.22
1026  */
1027 gboolean
1028 g_socket_get_keepalive (GSocket *socket)
1029 {
1030   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1031
1032   return socket->priv->keepalive;
1033 }
1034
1035 /**
1036  * g_socket_get_listen_backlog:
1037  * @socket: a #GSocket.
1038  *
1039  * Gets the listen backlog setting of the socket. For details on this,
1040  * see g_socket_set_listen_backlog().
1041  *
1042  * Returns: the maximum number of pending connections.
1043  *
1044  * Since: 2.22
1045  */
1046 gint
1047 g_socket_get_listen_backlog  (GSocket *socket)
1048 {
1049   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1050
1051   return socket->priv->listen_backlog;
1052 }
1053
1054 /**
1055  * g_socket_set_listen_backlog:
1056  * @socket: a #GSocket.
1057  * @backlog: the maximum number of pending connections.
1058  *
1059  * Sets the maximum number of outstanding connections allowed
1060  * when listening on this socket. If more clients than this are
1061  * connecting to the socket and the application is not handling them
1062  * on time then the new connections will be refused.
1063  *
1064  * Note that this must be called before g_socket_listen() and has no
1065  * effect if called after that.
1066  *
1067  * Since: 2.22
1068  */
1069 void
1070 g_socket_set_listen_backlog (GSocket *socket,
1071                              gint     backlog)
1072 {
1073   g_return_if_fail (G_IS_SOCKET (socket));
1074   g_return_if_fail (!socket->priv->listening);
1075
1076   if (backlog != socket->priv->listen_backlog)
1077     {
1078       socket->priv->listen_backlog = backlog;
1079       g_object_notify (G_OBJECT (socket), "listen-backlog");
1080     }
1081 }
1082
1083 /**
1084  * g_socket_get_timeout:
1085  * @socket: a #GSocket.
1086  *
1087  * Gets the timeout setting of the socket. For details on this, see
1088  * g_socket_set_timeout().
1089  *
1090  * Returns: the timeout in seconds
1091  *
1092  * Since: 2.26
1093  */
1094 guint
1095 g_socket_get_timeout (GSocket *socket)
1096 {
1097   g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1098
1099   return socket->priv->timeout;
1100 }
1101
1102 /**
1103  * g_socket_set_timeout:
1104  * @socket: a #GSocket.
1105  * @timeout: the timeout for @socket, in seconds, or 0 for none
1106  *
1107  * Sets the time in seconds after which I/O operations on @socket will
1108  * time out if they have not yet completed.
1109  *
1110  * On a blocking socket, this means that any blocking #GSocket
1111  * operation will time out after @timeout seconds of inactivity,
1112  * returning %G_IO_ERROR_TIMED_OUT.
1113  *
1114  * On a non-blocking socket, calls to g_socket_condition_wait() will
1115  * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1116  * created with g_socket_create_source() will trigger after
1117  * @timeout seconds of inactivity, with the requested condition
1118  * set, at which point calling g_socket_receive(), g_socket_send(),
1119  * g_socket_check_connect_result(), etc, will fail with
1120  * %G_IO_ERROR_TIMED_OUT.
1121  *
1122  * If @timeout is 0 (the default), operations will never time out
1123  * on their own.
1124  *
1125  * Note that if an I/O operation is interrupted by a signal, this may
1126  * cause the timeout to be reset.
1127  *
1128  * Since: 2.26
1129  */
1130 void
1131 g_socket_set_timeout (GSocket *socket,
1132                       guint    timeout)
1133 {
1134   g_return_if_fail (G_IS_SOCKET (socket));
1135
1136   if (timeout != socket->priv->timeout)
1137     {
1138       socket->priv->timeout = timeout;
1139       g_object_notify (G_OBJECT (socket), "timeout");
1140     }
1141 }
1142
1143 /**
1144  * g_socket_get_family:
1145  * @socket: a #GSocket.
1146  *
1147  * Gets the socket family of the socket.
1148  *
1149  * Returns: a #GSocketFamily
1150  *
1151  * Since: 2.22
1152  */
1153 GSocketFamily
1154 g_socket_get_family (GSocket *socket)
1155 {
1156   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1157
1158   return socket->priv->family;
1159 }
1160
1161 /**
1162  * g_socket_get_socket_type:
1163  * @socket: a #GSocket.
1164  *
1165  * Gets the socket type of the socket.
1166  *
1167  * Returns: a #GSocketType
1168  *
1169  * Since: 2.22
1170  */
1171 GSocketType
1172 g_socket_get_socket_type (GSocket *socket)
1173 {
1174   g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1175
1176   return socket->priv->type;
1177 }
1178
1179 /**
1180  * g_socket_get_protocol:
1181  * @socket: a #GSocket.
1182  *
1183  * Gets the socket protocol id the socket was created with.
1184  * In case the protocol is unknown, -1 is returned.
1185  *
1186  * Returns: a protocol id, or -1 if unknown
1187  *
1188  * Since: 2.22
1189  */
1190 GSocketProtocol
1191 g_socket_get_protocol (GSocket *socket)
1192 {
1193   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1194
1195   return socket->priv->protocol;
1196 }
1197
1198 /**
1199  * g_socket_get_fd:
1200  * @socket: a #GSocket.
1201  *
1202  * Returns the underlying OS socket object. On unix this
1203  * is a socket file descriptor, and on windows this is
1204  * a Winsock2 SOCKET handle. This may be useful for
1205  * doing platform specific or otherwise unusual operations
1206  * on the socket.
1207  *
1208  * Returns: the file descriptor of the socket.
1209  *
1210  * Since: 2.22
1211  */
1212 int
1213 g_socket_get_fd (GSocket *socket)
1214 {
1215   g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1216
1217   return socket->priv->fd;
1218 }
1219
1220 /**
1221  * g_socket_get_local_address:
1222  * @socket: a #GSocket.
1223  * @error: #GError for error reporting, or %NULL to ignore.
1224  *
1225  * Try to get the local address of a bound socket. This is only
1226  * useful if the socket has been bound to a local address,
1227  * either explicitly or implicitly when connecting.
1228  *
1229  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1230  *     Free the returned object with g_object_unref().
1231  *
1232  * Since: 2.22
1233  */
1234 GSocketAddress *
1235 g_socket_get_local_address (GSocket  *socket,
1236                             GError  **error)
1237 {
1238   struct sockaddr_storage buffer;
1239   guint32 len = sizeof (buffer);
1240
1241   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1242
1243   if (getsockname (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1244     {
1245       int errsv = get_socket_errno ();
1246       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1247                    _("could not get local address: %s"), socket_strerror (errsv));
1248       return NULL;
1249     }
1250
1251   return g_socket_address_new_from_native (&buffer, len);
1252 }
1253
1254 /**
1255  * g_socket_get_remote_address:
1256  * @socket: a #GSocket.
1257  * @error: #GError for error reporting, or %NULL to ignore.
1258  *
1259  * Try to get the remove address of a connected socket. This is only
1260  * useful for connection oriented sockets that have been connected.
1261  *
1262  * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1263  *     Free the returned object with g_object_unref().
1264  *
1265  * Since: 2.22
1266  */
1267 GSocketAddress *
1268 g_socket_get_remote_address (GSocket  *socket,
1269                              GError  **error)
1270 {
1271   struct sockaddr_storage buffer;
1272   guint32 len = sizeof (buffer);
1273
1274   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1275
1276   if (socket->priv->connect_pending)
1277     {
1278       if (!g_socket_check_connect_result (socket, error))
1279         return NULL;
1280       else
1281         socket->priv->connect_pending = FALSE;
1282     }
1283
1284   if (!socket->priv->remote_address)
1285     {
1286       if (getpeername (socket->priv->fd, (struct sockaddr *) &buffer, &len) < 0)
1287         {
1288           int errsv = get_socket_errno ();
1289           g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1290                        _("could not get remote address: %s"), socket_strerror (errsv));
1291           return NULL;
1292         }
1293
1294       socket->priv->remote_address = g_socket_address_new_from_native (&buffer, len);
1295     }
1296
1297   return g_object_ref (socket->priv->remote_address);
1298 }
1299
1300 /**
1301  * g_socket_is_connected:
1302  * @socket: a #GSocket.
1303  *
1304  * Check whether the socket is connected. This is only useful for
1305  * connection-oriented sockets.
1306  *
1307  * Returns: %TRUE if socket is connected, %FALSE otherwise.
1308  *
1309  * Since: 2.22
1310  */
1311 gboolean
1312 g_socket_is_connected (GSocket *socket)
1313 {
1314   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1315
1316   return socket->priv->connected;
1317 }
1318
1319 /**
1320  * g_socket_listen:
1321  * @socket: a #GSocket.
1322  * @error: #GError for error reporting, or %NULL to ignore.
1323  *
1324  * Marks the socket as a server socket, i.e. a socket that is used
1325  * to accept incoming requests using g_socket_accept().
1326  *
1327  * Before calling this the socket must be bound to a local address using
1328  * g_socket_bind().
1329  *
1330  * To set the maximum amount of outstanding clients, use
1331  * g_socket_set_listen_backlog().
1332  *
1333  * Returns: %TRUE on success, %FALSE on error.
1334  *
1335  * Since: 2.22
1336  */
1337 gboolean
1338 g_socket_listen (GSocket  *socket,
1339                  GError  **error)
1340 {
1341   g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1342
1343   if (!check_socket (socket, error))
1344     return FALSE;
1345
1346   if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
1347     {
1348       int errsv = get_socket_errno ();
1349
1350       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1351                    _("could not listen: %s"), socket_strerror (errsv));
1352       return FALSE;
1353     }
1354
1355   socket->priv->listening = TRUE;
1356
1357   return TRUE;
1358 }
1359
1360 /**
1361  * g_socket_bind:
1362  * @socket: a #GSocket.
1363  * @address: a #GSocketAddress specifying the local address.
1364  * @allow_reuse: whether to allow reusing this address
1365  * @error: #GError for error reporting, or %NULL to ignore.
1366  *
1367  * When a socket is created it is attached to an address family, but it
1368  * doesn't have an address in this family. g_socket_bind() assigns the
1369  * address (sometimes called name) of the socket.
1370  *
1371  * It is generally required to bind to a local address before you can
1372  * receive connections. (See g_socket_listen() and g_socket_accept() ).
1373  * In certain situations, you may also want to bind a socket that will be
1374  * used to initiate connections, though this is not normally required.
1375  *
1376  * @allow_reuse should be %TRUE for server sockets (sockets that you will
1377  * eventually call g_socket_accept() on), and %FALSE for client sockets.
1378  * (Specifically, if it is %TRUE, then g_socket_bind() will set the
1379  * %SO_REUSEADDR flag on the socket, allowing it to bind @address even if
1380  * that address was previously used by another socket that has not yet been
1381  * fully cleaned-up by the kernel. Failing to set this flag on a server
1382  * socket may cause the bind call to return %G_IO_ERROR_ADDRESS_IN_USE if
1383  * the server program is stopped and then immediately restarted.)
1384  *
1385  * Returns: %TRUE on success, %FALSE on error.
1386  *
1387  * Since: 2.22
1388  */
1389 gboolean
1390 g_socket_bind (GSocket         *socket,
1391                GSocketAddress  *address,
1392                gboolean         reuse_address,
1393                GError         **error)
1394 {
1395   struct sockaddr_storage addr;
1396
1397   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1398
1399   if (!check_socket (socket, error))
1400     return FALSE;
1401
1402   /* SO_REUSEADDR on windows means something else and is not what we want.
1403      It always allows the unix variant of SO_REUSEADDR anyway */
1404 #ifndef G_OS_WIN32
1405   {
1406     int value;
1407
1408     value = (int) !!reuse_address;
1409     /* Ignore errors here, the only likely error is "not supported", and
1410        this is a "best effort" thing mainly */
1411     setsockopt (socket->priv->fd, SOL_SOCKET, SO_REUSEADDR,
1412                 (gpointer) &value, sizeof (value));
1413   }
1414 #endif
1415
1416   if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
1417     return FALSE;
1418
1419   if (bind (socket->priv->fd, (struct sockaddr *) &addr,
1420             g_socket_address_get_native_size (address)) < 0)
1421     {
1422       int errsv = get_socket_errno ();
1423       g_set_error (error,
1424                    G_IO_ERROR, socket_io_error_from_errno (errsv),
1425                    _("Error binding to address: %s"), socket_strerror (errsv));
1426       return FALSE;
1427     }
1428
1429   return TRUE;
1430 }
1431
1432 /**
1433  * g_socket_speaks_ipv4:
1434  * @socket: a #GSocket
1435  *
1436  * Checks if a socket is capable of speaking IPv4.
1437  *
1438  * IPv4 sockets are capable of speaking IPv4.  On some operating systems
1439  * and under some combinations of circumstances IPv6 sockets are also
1440  * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
1441  * information.
1442  *
1443  * No other types of sockets are currently considered as being capable
1444  * of speaking IPv4.
1445  *
1446  * Returns: %TRUE if this socket can be used with IPv4.
1447  *
1448  * Since: 2.22
1449  **/
1450 gboolean
1451 g_socket_speaks_ipv4 (GSocket *socket)
1452 {
1453   switch (socket->priv->family)
1454     {
1455     case G_SOCKET_FAMILY_IPV4:
1456       return TRUE;
1457
1458     case G_SOCKET_FAMILY_IPV6:
1459 #if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
1460       {
1461         guint sizeof_int = sizeof (int);
1462         gint v6_only;
1463
1464         if (getsockopt (socket->priv->fd,
1465                         IPPROTO_IPV6, IPV6_V6ONLY,
1466                         &v6_only, &sizeof_int) != 0)
1467           return FALSE;
1468
1469         return !v6_only;
1470       }
1471 #else
1472       return FALSE;
1473 #endif
1474
1475     default:
1476       return FALSE;
1477     }
1478 }
1479
1480 /**
1481  * g_socket_accept:
1482  * @socket: a #GSocket.
1483  * @cancellable: (allow-none): a %GCancellable or %NULL
1484  * @error: #GError for error reporting, or %NULL to ignore.
1485  *
1486  * Accept incoming connections on a connection-based socket. This removes
1487  * the first outstanding connection request from the listening socket and
1488  * creates a #GSocket object for it.
1489  *
1490  * The @socket must be bound to a local address with g_socket_bind() and
1491  * must be listening for incoming connections (g_socket_listen()).
1492  *
1493  * If there are no outstanding connections then the operation will block
1494  * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
1495  * To be notified of an incoming connection, wait for the %G_IO_IN condition.
1496  *
1497  * Returns: (transfer full): a new #GSocket, or %NULL on error.
1498  *     Free the returned object with g_object_unref().
1499  *
1500  * Since: 2.22
1501  */
1502 GSocket *
1503 g_socket_accept (GSocket       *socket,
1504                  GCancellable  *cancellable,
1505                  GError       **error)
1506 {
1507   GSocket *new_socket;
1508   gint ret;
1509
1510   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1511
1512   if (!check_socket (socket, error))
1513     return NULL;
1514
1515   while (TRUE)
1516     {
1517       if (socket->priv->blocking &&
1518           !g_socket_condition_wait (socket,
1519                                     G_IO_IN, cancellable, error))
1520         return NULL;
1521
1522       if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
1523         {
1524           int errsv = get_socket_errno ();
1525
1526           win32_unset_event_mask (socket, FD_ACCEPT);
1527
1528           if (errsv == EINTR)
1529             continue;
1530
1531           if (socket->priv->blocking)
1532             {
1533 #ifdef WSAEWOULDBLOCK
1534               if (errsv == WSAEWOULDBLOCK)
1535                 continue;
1536 #else
1537               if (errsv == EWOULDBLOCK ||
1538                   errsv == EAGAIN)
1539                 continue;
1540 #endif
1541             }
1542
1543           g_set_error (error, G_IO_ERROR,
1544                        socket_io_error_from_errno (errsv),
1545                        _("Error accepting connection: %s"), socket_strerror (errsv));
1546           return NULL;
1547         }
1548       break;
1549     }
1550
1551   win32_unset_event_mask (socket, FD_ACCEPT);
1552
1553 #ifdef G_OS_WIN32
1554   {
1555     /* The socket inherits the accepting sockets event mask and even object,
1556        we need to remove that */
1557     WSAEventSelect (ret, NULL, 0);
1558   }
1559 #else
1560   {
1561     int flags;
1562
1563     /* We always want to set close-on-exec to protect users. If you
1564        need to so some weird inheritance to exec you can re-enable this
1565        using lower level hacks with g_socket_get_fd(). */
1566     flags = fcntl (ret, F_GETFD, 0);
1567     if (flags != -1 &&
1568         (flags & FD_CLOEXEC) == 0)
1569       {
1570         flags |= FD_CLOEXEC;
1571         fcntl (ret, F_SETFD, flags);
1572       }
1573   }
1574 #endif
1575
1576   new_socket = g_socket_new_from_fd (ret, error);
1577   if (new_socket == NULL)
1578     {
1579 #ifdef G_OS_WIN32
1580       closesocket (ret);
1581 #else
1582       close (ret);
1583 #endif
1584     }
1585   else
1586     new_socket->priv->protocol = socket->priv->protocol;
1587
1588   return new_socket;
1589 }
1590
1591 /**
1592  * g_socket_connect:
1593  * @socket: a #GSocket.
1594  * @address: a #GSocketAddress specifying the remote address.
1595  * @cancellable: (allow-none): a %GCancellable or %NULL
1596  * @error: #GError for error reporting, or %NULL to ignore.
1597  *
1598  * Connect the socket to the specified remote address.
1599  *
1600  * For connection oriented socket this generally means we attempt to make
1601  * a connection to the @address. For a connection-less socket it sets
1602  * the default address for g_socket_send() and discards all incoming datagrams
1603  * from other sources.
1604  *
1605  * Generally connection oriented sockets can only connect once, but
1606  * connection-less sockets can connect multiple times to change the
1607  * default address.
1608  *
1609  * If the connect call needs to do network I/O it will block, unless
1610  * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
1611  * and the user can be notified of the connection finishing by waiting
1612  * for the G_IO_OUT condition. The result of the connection can then be
1613  * checked with g_socket_check_connect_result().
1614  *
1615  * Returns: %TRUE if connected, %FALSE on error.
1616  *
1617  * Since: 2.22
1618  */
1619 gboolean
1620 g_socket_connect (GSocket         *socket,
1621                   GSocketAddress  *address,
1622                   GCancellable    *cancellable,
1623                   GError         **error)
1624 {
1625   struct sockaddr_storage buffer;
1626
1627   g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
1628
1629   if (!check_socket (socket, error))
1630     return FALSE;
1631
1632   if (!g_socket_address_to_native (address, &buffer, sizeof buffer, error))
1633     return FALSE;
1634
1635   if (socket->priv->remote_address)
1636     g_object_unref (socket->priv->remote_address);
1637   socket->priv->remote_address = g_object_ref (address);
1638
1639   while (1)
1640     {
1641       if (connect (socket->priv->fd, (struct sockaddr *) &buffer,
1642                    g_socket_address_get_native_size (address)) < 0)
1643         {
1644           int errsv = get_socket_errno ();
1645
1646           if (errsv == EINTR)
1647             continue;
1648
1649 #ifndef G_OS_WIN32
1650           if (errsv == EINPROGRESS)
1651 #else
1652           if (errsv == WSAEWOULDBLOCK)
1653 #endif
1654             {
1655               if (socket->priv->blocking)
1656                 {
1657                   if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
1658                     {
1659                       if (g_socket_check_connect_result (socket, error))
1660                         break;
1661                     }
1662                   g_prefix_error (error, _("Error connecting: "));
1663                 }
1664               else
1665                 {
1666                   g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
1667                                        _("Connection in progress"));
1668                   socket->priv->connect_pending = TRUE;
1669                 }
1670             }
1671           else
1672             g_set_error (error, G_IO_ERROR,
1673                          socket_io_error_from_errno (errsv),
1674                          _("Error connecting: %s"), socket_strerror (errsv));
1675
1676           return FALSE;
1677         }
1678       break;
1679     }
1680
1681   win32_unset_event_mask (socket, FD_CONNECT);
1682
1683   socket->priv->connected = TRUE;
1684
1685   return TRUE;
1686 }
1687
1688 /**
1689  * g_socket_check_connect_result:
1690  * @socket: a #GSocket
1691  * @error: #GError for error reporting, or %NULL to ignore.
1692  *
1693  * Checks and resets the pending connect error for the socket.
1694  * This is used to check for errors when g_socket_connect() is
1695  * used in non-blocking mode.
1696  *
1697  * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
1698  *
1699  * Since: 2.22
1700  */
1701 gboolean
1702 g_socket_check_connect_result (GSocket  *socket,
1703                                GError  **error)
1704 {
1705   guint optlen;
1706   int value;
1707
1708   if (!check_socket (socket, error))
1709     return FALSE;
1710
1711   optlen = sizeof (value);
1712   if (getsockopt (socket->priv->fd, SOL_SOCKET, SO_ERROR, (void *)&value, &optlen) != 0)
1713     {
1714       int errsv = get_socket_errno ();
1715
1716       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
1717                    _("Unable to get pending error: %s"), socket_strerror (errsv));
1718       return FALSE;
1719     }
1720
1721   if (value != 0)
1722     {
1723       g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
1724                            socket_strerror (value));
1725       if (socket->priv->remote_address)
1726         {
1727           g_object_unref (socket->priv->remote_address);
1728           socket->priv->remote_address = NULL;
1729         }
1730       return FALSE;
1731     }
1732   return TRUE;
1733 }
1734
1735 /**
1736  * g_socket_receive:
1737  * @socket: a #GSocket
1738  * @buffer: a buffer to read data into (which should be at least @size
1739  *     bytes long).
1740  * @size: the number of bytes you want to read from the socket
1741  * @cancellable: (allow-none): a %GCancellable or %NULL
1742  * @error: #GError for error reporting, or %NULL to ignore.
1743  *
1744  * Receive data (up to @size bytes) from a socket. This is mainly used by
1745  * connection-oriented sockets; it is identical to g_socket_receive_from()
1746  * with @address set to %NULL.
1747  *
1748  * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
1749  * g_socket_receive() will always read either 0 or 1 complete messages from
1750  * the socket. If the received message is too large to fit in @buffer, then
1751  * the data beyond @size bytes will be discarded, without any explicit
1752  * indication that this has occurred.
1753  *
1754  * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
1755  * number of bytes, up to @size. If more than @size bytes have been
1756  * received, the additional data will be returned in future calls to
1757  * g_socket_receive().
1758  *
1759  * If the socket is in blocking mode the call will block until there is
1760  * some data to receive or there is an error. If there is no data available
1761  * and the socket is in non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error
1762  * will be returned. To be notified when data is available, wait for the
1763  * %G_IO_IN condition.
1764  *
1765  * On error -1 is returned and @error is set accordingly.
1766  *
1767  * Returns: Number of bytes read, or -1 on error
1768  *
1769  * Since: 2.22
1770  */
1771 gssize
1772 g_socket_receive (GSocket       *socket,
1773                   gchar         *buffer,
1774                   gsize          size,
1775                   GCancellable  *cancellable,
1776                   GError       **error)
1777 {
1778   return g_socket_receive_with_blocking (socket, buffer, size,
1779                                          socket->priv->blocking,
1780                                          cancellable, error);
1781 }
1782
1783 /**
1784  * g_socket_receive_with_blocking:
1785  * @socket: a #GSocket
1786  * @buffer: a buffer to read data into (which should be at least @size
1787  *     bytes long).
1788  * @size: the number of bytes you want to read from the socket
1789  * @blocking: whether to do blocking or non-blocking I/O
1790  * @cancellable: (allow-none): a %GCancellable or %NULL
1791  * @error: #GError for error reporting, or %NULL to ignore.
1792  *
1793  * This behaves exactly the same as g_socket_receive(), except that
1794  * the choice of blocking or non-blocking behavior is determined by
1795  * the @blocking argument rather than by @socket's properties.
1796  *
1797  * Returns: Number of bytes read, or -1 on error
1798  *
1799  * Since: 2.26
1800  */
1801 gssize
1802 g_socket_receive_with_blocking (GSocket       *socket,
1803                                 gchar         *buffer,
1804                                 gsize          size,
1805                                 gboolean       blocking,
1806                                 GCancellable  *cancellable,
1807                                 GError       **error)
1808 {
1809   gssize ret;
1810
1811   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1812
1813   if (!check_socket (socket, error))
1814     return -1;
1815
1816   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1817     return -1;
1818
1819   while (1)
1820     {
1821       if (blocking &&
1822           !g_socket_condition_wait (socket,
1823                                     G_IO_IN, cancellable, error))
1824         return -1;
1825
1826       if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
1827         {
1828           int errsv = get_socket_errno ();
1829
1830           if (errsv == EINTR)
1831             continue;
1832
1833           if (blocking)
1834             {
1835 #ifdef WSAEWOULDBLOCK
1836               if (errsv == WSAEWOULDBLOCK)
1837                 continue;
1838 #else
1839               if (errsv == EWOULDBLOCK ||
1840                   errsv == EAGAIN)
1841                 continue;
1842 #endif
1843             }
1844
1845           win32_unset_event_mask (socket, FD_READ);
1846
1847           g_set_error (error, G_IO_ERROR,
1848                        socket_io_error_from_errno (errsv),
1849                        _("Error receiving data: %s"), socket_strerror (errsv));
1850           return -1;
1851         }
1852
1853       win32_unset_event_mask (socket, FD_READ);
1854
1855       break;
1856     }
1857
1858   return ret;
1859 }
1860
1861 /**
1862  * g_socket_receive_from:
1863  * @socket: a #GSocket
1864  * @address: a pointer to a #GSocketAddress pointer, or %NULL
1865  * @buffer: a buffer to read data into (which should be at least @size
1866  *     bytes long).
1867  * @size: the number of bytes you want to read from the socket
1868  * @cancellable: (allow-none): a %GCancellable or %NULL
1869  * @error: #GError for error reporting, or %NULL to ignore.
1870  *
1871  * Receive data (up to @size bytes) from a socket.
1872  *
1873  * If @address is non-%NULL then @address will be set equal to the
1874  * source address of the received packet.
1875  * @address is owned by the caller.
1876  *
1877  * See g_socket_receive() for additional information.
1878  *
1879  * Returns: Number of bytes read, or -1 on error
1880  *
1881  * Since: 2.22
1882  */
1883 gssize
1884 g_socket_receive_from (GSocket         *socket,
1885                        GSocketAddress **address,
1886                        gchar           *buffer,
1887                        gsize            size,
1888                        GCancellable    *cancellable,
1889                        GError         **error)
1890 {
1891   GInputVector v;
1892
1893   v.buffer = buffer;
1894   v.size = size;
1895
1896   return g_socket_receive_message (socket,
1897                                    address,
1898                                    &v, 1,
1899                                    NULL, 0, NULL,
1900                                    cancellable,
1901                                    error);
1902 }
1903
1904 /* Although we ignore SIGPIPE, gdb will still stop if the app receives
1905  * one, which can be confusing and annoying. So if possible, we want
1906  * to suppress the signal entirely.
1907  */
1908 #ifdef MSG_NOSIGNAL
1909 #define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
1910 #else
1911 #define G_SOCKET_DEFAULT_SEND_FLAGS 0
1912 #endif
1913
1914 /**
1915  * g_socket_send:
1916  * @socket: a #GSocket
1917  * @buffer: (array length=size): the buffer containing the data to send.
1918  * @size: the number of bytes to send
1919  * @cancellable: (allow-none): a %GCancellable or %NULL
1920  * @error: #GError for error reporting, or %NULL to ignore.
1921  *
1922  * Tries to send @size bytes from @buffer on the socket. This is
1923  * mainly used by connection-oriented sockets; it is identical to
1924  * g_socket_send_to() with @address set to %NULL.
1925  *
1926  * If the socket is in blocking mode the call will block until there is
1927  * space for the data in the socket queue. If there is no space available
1928  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
1929  * will be returned. To be notified when space is available, wait for the
1930  * %G_IO_OUT condition. Note though that you may still receive
1931  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
1932  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
1933  * very common due to the way the underlying APIs work.)
1934  *
1935  * On error -1 is returned and @error is set accordingly.
1936  *
1937  * Returns: Number of bytes written (which may be less than @size), or -1
1938  * on error
1939  *
1940  * Since: 2.22
1941  */
1942 gssize
1943 g_socket_send (GSocket       *socket,
1944                const gchar   *buffer,
1945                gsize          size,
1946                GCancellable  *cancellable,
1947                GError       **error)
1948 {
1949   return g_socket_send_with_blocking (socket, buffer, size,
1950                                       socket->priv->blocking,
1951                                       cancellable, error);
1952 }
1953
1954 /**
1955  * g_socket_send_with_blocking:
1956  * @socket: a #GSocket
1957  * @buffer: (array length=size): the buffer containing the data to send.
1958  * @size: the number of bytes to send
1959  * @blocking: whether to do blocking or non-blocking I/O
1960  * @cancellable: (allow-none): a %GCancellable or %NULL
1961  * @error: #GError for error reporting, or %NULL to ignore.
1962  *
1963  * This behaves exactly the same as g_socket_send(), except that
1964  * the choice of blocking or non-blocking behavior is determined by
1965  * the @blocking argument rather than by @socket's properties.
1966  *
1967  * Returns: Number of bytes written (which may be less than @size), or -1
1968  * on error
1969  *
1970  * Since: 2.26
1971  */
1972 gssize
1973 g_socket_send_with_blocking (GSocket       *socket,
1974                              const gchar   *buffer,
1975                              gsize          size,
1976                              gboolean       blocking,
1977                              GCancellable  *cancellable,
1978                              GError       **error)
1979 {
1980   gssize ret;
1981
1982   g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, FALSE);
1983
1984   if (!check_socket (socket, error))
1985     return -1;
1986
1987   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1988     return -1;
1989
1990   while (1)
1991     {
1992       if (blocking &&
1993           !g_socket_condition_wait (socket,
1994                                     G_IO_OUT, cancellable, error))
1995         return -1;
1996
1997       if ((ret = send (socket->priv->fd, buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
1998         {
1999           int errsv = get_socket_errno ();
2000
2001           if (errsv == EINTR)
2002             continue;
2003
2004 #ifdef WSAEWOULDBLOCK
2005           if (errsv == WSAEWOULDBLOCK)
2006             win32_unset_event_mask (socket, FD_WRITE);
2007 #endif
2008
2009           if (blocking)
2010             {
2011 #ifdef WSAEWOULDBLOCK
2012               if (errsv == WSAEWOULDBLOCK)
2013                 continue;
2014 #else
2015               if (errsv == EWOULDBLOCK ||
2016                   errsv == EAGAIN)
2017                 continue;
2018 #endif
2019             }
2020
2021           g_set_error (error, G_IO_ERROR,
2022                        socket_io_error_from_errno (errsv),
2023                        _("Error sending data: %s"), socket_strerror (errsv));
2024           return -1;
2025         }
2026       break;
2027     }
2028
2029   return ret;
2030 }
2031
2032 /**
2033  * g_socket_send_to:
2034  * @socket: a #GSocket
2035  * @address: a #GSocketAddress, or %NULL
2036  * @buffer: (array length=size): the buffer containing the data to send.
2037  * @size: the number of bytes to send
2038  * @cancellable: (allow-none): a %GCancellable or %NULL
2039  * @error: #GError for error reporting, or %NULL to ignore.
2040  *
2041  * Tries to send @size bytes from @buffer to @address. If @address is
2042  * %NULL then the message is sent to the default receiver (set by
2043  * g_socket_connect()).
2044  *
2045  * See g_socket_send() for additional information.
2046  *
2047  * Returns: Number of bytes written (which may be less than @size), or -1
2048  * on error
2049  *
2050  * Since: 2.22
2051  */
2052 gssize
2053 g_socket_send_to (GSocket         *socket,
2054                   GSocketAddress  *address,
2055                   const gchar     *buffer,
2056                   gsize            size,
2057                   GCancellable    *cancellable,
2058                   GError         **error)
2059 {
2060   GOutputVector v;
2061
2062   v.buffer = buffer;
2063   v.size = size;
2064
2065   return g_socket_send_message (socket,
2066                                 address,
2067                                 &v, 1,
2068                                 NULL, 0,
2069                                 0,
2070                                 cancellable,
2071                                 error);
2072 }
2073
2074 /**
2075  * g_socket_shutdown:
2076  * @socket: a #GSocket
2077  * @shutdown_read: whether to shut down the read side
2078  * @shutdown_write: whether to shut down the write side
2079  * @error: #GError for error reporting, or %NULL to ignore.
2080  *
2081  * Shut down part of a full-duplex connection.
2082  *
2083  * If @shutdown_read is %TRUE then the recieving side of the connection
2084  * is shut down, and further reading is disallowed.
2085  *
2086  * If @shutdown_write is %TRUE then the sending side of the connection
2087  * is shut down, and further writing is disallowed.
2088  *
2089  * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
2090  *
2091  * One example where this is used is graceful disconnect for TCP connections
2092  * where you close the sending side, then wait for the other side to close
2093  * the connection, thus ensuring that the other side saw all sent data.
2094  *
2095  * Returns: %TRUE on success, %FALSE on error
2096  *
2097  * Since: 2.22
2098  */
2099 gboolean
2100 g_socket_shutdown (GSocket   *socket,
2101                    gboolean   shutdown_read,
2102                    gboolean   shutdown_write,
2103                    GError   **error)
2104 {
2105   int how;
2106
2107   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2108
2109   if (!check_socket (socket, NULL))
2110     return FALSE;
2111
2112   /* Do nothing? */
2113   if (!shutdown_read && !shutdown_write)
2114     return TRUE;
2115
2116 #ifndef G_OS_WIN32
2117   if (shutdown_read && shutdown_write)
2118     how = SHUT_RDWR;
2119   else if (shutdown_read)
2120     how = SHUT_RD;
2121   else
2122     how = SHUT_WR;
2123 #else
2124   if (shutdown_read && shutdown_write)
2125     how = SD_BOTH;
2126   else if (shutdown_read)
2127     how = SD_RECEIVE;
2128   else
2129     how = SD_SEND;
2130 #endif
2131
2132   if (shutdown (socket->priv->fd, how) != 0)
2133     {
2134       int errsv = get_socket_errno ();
2135       g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2136                    _("Unable to create socket: %s"), socket_strerror (errsv));
2137       return FALSE;
2138     }
2139
2140   if (shutdown_read && shutdown_write)
2141     socket->priv->connected = FALSE;
2142
2143   return TRUE;
2144 }
2145
2146 /**
2147  * g_socket_close:
2148  * @socket: a #GSocket
2149  * @error: #GError for error reporting, or %NULL to ignore.
2150  *
2151  * Closes the socket, shutting down any active connection.
2152  *
2153  * Closing a socket does not wait for all outstanding I/O operations
2154  * to finish, so the caller should not rely on them to be guaranteed
2155  * to complete even if the close returns with no error.
2156  *
2157  * Once the socket is closed, all other operations will return
2158  * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
2159  * return an error.
2160  *
2161  * Sockets will be automatically closed when the last reference
2162  * is dropped, but you might want to call this function to make sure
2163  * resources are released as early as possible.
2164  *
2165  * Beware that due to the way that TCP works, it is possible for
2166  * recently-sent data to be lost if either you close a socket while the
2167  * %G_IO_IN condition is set, or else if the remote connection tries to
2168  * send something to you after you close the socket but before it has
2169  * finished reading all of the data you sent. There is no easy generic
2170  * way to avoid this problem; the easiest fix is to design the network
2171  * protocol such that the client will never send data "out of turn".
2172  * Another solution is for the server to half-close the connection by
2173  * calling g_socket_shutdown() with only the @shutdown_write flag set,
2174  * and then wait for the client to notice this and close its side of the
2175  * connection, after which the server can safely call g_socket_close().
2176  * (This is what #GTcpConnection does if you call
2177  * g_tcp_connection_set_graceful_disconnect(). But of course, this
2178  * only works if the client will close its connection after the server
2179  * does.)
2180  *
2181  * Returns: %TRUE on success, %FALSE on error
2182  *
2183  * Since: 2.22
2184  */
2185 gboolean
2186 g_socket_close (GSocket  *socket,
2187                 GError  **error)
2188 {
2189   int res;
2190
2191   g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
2192
2193   if (socket->priv->closed)
2194     return TRUE; /* Multiple close not an error */
2195
2196   if (!check_socket (socket, NULL))
2197     return FALSE;
2198
2199   while (1)
2200     {
2201 #ifdef G_OS_WIN32
2202       res = closesocket (socket->priv->fd);
2203 #else
2204       res = close (socket->priv->fd);
2205 #endif
2206       if (res == -1)
2207         {
2208           int errsv = get_socket_errno ();
2209
2210           if (errsv == EINTR)
2211             continue;
2212
2213           g_set_error (error, G_IO_ERROR,
2214                        socket_io_error_from_errno (errsv),
2215                        _("Error closing socket: %s"),
2216                        socket_strerror (errsv));
2217           return FALSE;
2218         }
2219       break;
2220     }
2221
2222   socket->priv->connected = FALSE;
2223   socket->priv->closed = TRUE;
2224   if (socket->priv->remote_address)
2225     {
2226       g_object_unref (socket->priv->remote_address);
2227       socket->priv->remote_address = NULL;
2228     }
2229
2230   return TRUE;
2231 }
2232
2233 /**
2234  * g_socket_is_closed:
2235  * @socket: a #GSocket
2236  *
2237  * Checks whether a socket is closed.
2238  *
2239  * Returns: %TRUE if socket is closed, %FALSE otherwise
2240  *
2241  * Since: 2.22
2242  */
2243 gboolean
2244 g_socket_is_closed (GSocket *socket)
2245 {
2246   return socket->priv->closed;
2247 }
2248
2249 #ifdef G_OS_WIN32
2250 /* Broken source, used on errors */
2251 static gboolean
2252 broken_prepare  (GSource *source,
2253                  gint    *timeout)
2254 {
2255   return FALSE;
2256 }
2257
2258 static gboolean
2259 broken_check (GSource *source)
2260 {
2261   return FALSE;
2262 }
2263
2264 static gboolean
2265 broken_dispatch (GSource     *source,
2266                  GSourceFunc  callback,
2267                  gpointer     user_data)
2268 {
2269   return TRUE;
2270 }
2271
2272 static GSourceFuncs broken_funcs =
2273 {
2274   broken_prepare,
2275   broken_check,
2276   broken_dispatch,
2277   NULL
2278 };
2279
2280 static gint
2281 network_events_for_condition (GIOCondition condition)
2282 {
2283   int event_mask = 0;
2284
2285   if (condition & G_IO_IN)
2286     event_mask |= (FD_READ | FD_ACCEPT);
2287   if (condition & G_IO_OUT)
2288     event_mask |= (FD_WRITE | FD_CONNECT);
2289   event_mask |= FD_CLOSE;
2290
2291   return event_mask;
2292 }
2293
2294 static void
2295 ensure_event (GSocket *socket)
2296 {
2297   if (socket->priv->event == WSA_INVALID_EVENT)
2298     socket->priv->event = WSACreateEvent();
2299 }
2300
2301 static void
2302 update_select_events (GSocket *socket)
2303 {
2304   int event_mask;
2305   GIOCondition *ptr;
2306   GList *l;
2307   WSAEVENT event;
2308
2309   ensure_event (socket);
2310
2311   event_mask = 0;
2312   for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
2313     {
2314       ptr = l->data;
2315       event_mask |= network_events_for_condition (*ptr);
2316     }
2317
2318   if (event_mask != socket->priv->selected_events)
2319     {
2320       /* If no events selected, disable event so we can unset
2321          nonblocking mode */
2322
2323       if (event_mask == 0)
2324         event = NULL;
2325       else
2326         event = socket->priv->event;
2327
2328       if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
2329         socket->priv->selected_events = event_mask;
2330     }
2331 }
2332
2333 static void
2334 add_condition_watch (GSocket      *socket,
2335                      GIOCondition *condition)
2336 {
2337   g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
2338
2339   socket->priv->requested_conditions =
2340     g_list_prepend (socket->priv->requested_conditions, condition);
2341
2342   update_select_events (socket);
2343 }
2344
2345 static void
2346 remove_condition_watch (GSocket      *socket,
2347                         GIOCondition *condition)
2348 {
2349   g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
2350
2351   socket->priv->requested_conditions =
2352     g_list_remove (socket->priv->requested_conditions, condition);
2353
2354   update_select_events (socket);
2355 }
2356
2357 static GIOCondition
2358 update_condition (GSocket *socket)
2359 {
2360   WSANETWORKEVENTS events;
2361   GIOCondition condition;
2362
2363   if (WSAEnumNetworkEvents (socket->priv->fd,
2364                             socket->priv->event,
2365                             &events) == 0)
2366     {
2367       socket->priv->current_events |= events.lNetworkEvents;
2368       if (events.lNetworkEvents & FD_WRITE &&
2369           events.iErrorCode[FD_WRITE_BIT] != 0)
2370         socket->priv->current_errors |= FD_WRITE;
2371       if (events.lNetworkEvents & FD_CONNECT &&
2372           events.iErrorCode[FD_CONNECT_BIT] != 0)
2373         socket->priv->current_errors |= FD_CONNECT;
2374     }
2375
2376   condition = 0;
2377   if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
2378     condition |= G_IO_IN;
2379
2380   if (socket->priv->current_events & FD_CLOSE ||
2381       socket->priv->closed)
2382     condition |= G_IO_HUP;
2383
2384   /* Never report both G_IO_OUT and HUP, these are
2385      mutually exclusive (can't write to a closed socket) */
2386   if ((condition & G_IO_HUP) == 0 &&
2387       socket->priv->current_events & FD_WRITE)
2388     {
2389       if (socket->priv->current_errors & FD_WRITE)
2390         condition |= G_IO_ERR;
2391       else
2392         condition |= G_IO_OUT;
2393     }
2394   else
2395     {
2396       if (socket->priv->current_events & FD_CONNECT)
2397         {
2398           if (socket->priv->current_errors & FD_CONNECT)
2399             condition |= (G_IO_HUP | G_IO_ERR);
2400           else
2401             condition |= G_IO_OUT;
2402         }
2403     }
2404
2405   return condition;
2406 }
2407 #endif
2408
2409 typedef struct {
2410   GSource       source;
2411   GPollFD       pollfd;
2412   GSocket      *socket;
2413   GIOCondition  condition;
2414   GCancellable *cancellable;
2415   GPollFD       cancel_pollfd;
2416   gint64        timeout_time;
2417 } GSocketSource;
2418
2419 static gboolean
2420 socket_source_prepare (GSource *source,
2421                        gint    *timeout)
2422 {
2423   GSocketSource *socket_source = (GSocketSource *)source;
2424
2425   if (g_cancellable_is_cancelled (socket_source->cancellable))
2426     return TRUE;
2427
2428   if (socket_source->timeout_time)
2429     {
2430       gint64 now;
2431
2432       now = g_source_get_time (source);
2433       /* Round up to ensure that we don't try again too early */
2434       *timeout = (socket_source->timeout_time - now + 999) / 1000;
2435       if (*timeout < 0)
2436         {
2437           socket_source->socket->priv->timed_out = TRUE;
2438           socket_source->pollfd.revents = socket_source->condition & (G_IO_IN | G_IO_OUT);
2439           *timeout = 0;
2440           return TRUE;
2441         }
2442     }
2443   else
2444     *timeout = -1;
2445
2446 #ifdef G_OS_WIN32
2447   socket_source->pollfd.revents = update_condition (socket_source->socket);
2448 #endif
2449
2450   if ((socket_source->condition & socket_source->pollfd.revents) != 0)
2451     return TRUE;
2452
2453   return FALSE;
2454 }
2455
2456 static gboolean
2457 socket_source_check (GSource *source)
2458 {
2459   int timeout;
2460
2461   return socket_source_prepare (source, &timeout);
2462 }
2463
2464 static gboolean
2465 socket_source_dispatch (GSource     *source,
2466                         GSourceFunc  callback,
2467                         gpointer     user_data)
2468 {
2469   GSocketSourceFunc func = (GSocketSourceFunc)callback;
2470   GSocketSource *socket_source = (GSocketSource *)source;
2471
2472 #ifdef G_OS_WIN32
2473   socket_source->pollfd.revents = update_condition (socket_source->socket);
2474 #endif
2475
2476   return (*func) (socket_source->socket,
2477                   socket_source->pollfd.revents & socket_source->condition,
2478                   user_data);
2479 }
2480
2481 static void
2482 socket_source_finalize (GSource *source)
2483 {
2484   GSocketSource *socket_source = (GSocketSource *)source;
2485   GSocket *socket;
2486
2487   socket = socket_source->socket;
2488
2489 #ifdef G_OS_WIN32
2490   remove_condition_watch (socket, &socket_source->condition);
2491 #endif
2492
2493   g_object_unref (socket);
2494
2495   if (socket_source->cancellable)
2496     {
2497       g_cancellable_release_fd (socket_source->cancellable);
2498       g_object_unref (socket_source->cancellable);
2499     }
2500 }
2501
2502 static gboolean
2503 socket_source_closure_callback (GSocket      *socket,
2504                                 GIOCondition  condition,
2505                                 gpointer      data)
2506 {
2507   GClosure *closure = data;
2508
2509   GValue params[2] = { { 0, }, { 0, } };
2510   GValue result_value = { 0, };
2511   gboolean result;
2512
2513   g_value_init (&result_value, G_TYPE_BOOLEAN);
2514
2515   g_value_init (&params[0], G_TYPE_SOCKET);
2516   g_value_set_object (&params[0], socket);
2517   g_value_init (&params[1], G_TYPE_IO_CONDITION);
2518   g_value_set_flags (&params[1], condition);
2519
2520   g_closure_invoke (closure, &result_value, 2, params, NULL);
2521
2522   result = g_value_get_boolean (&result_value);
2523   g_value_unset (&result_value);
2524   g_value_unset (&params[0]);
2525   g_value_unset (&params[1]);
2526
2527   return result;
2528 }
2529
2530 static GSourceFuncs socket_source_funcs =
2531 {
2532   socket_source_prepare,
2533   socket_source_check,
2534   socket_source_dispatch,
2535   socket_source_finalize,
2536   (GSourceFunc)socket_source_closure_callback,
2537   (GSourceDummyMarshal)_gio_marshal_BOOLEAN__FLAGS,
2538 };
2539
2540 static GSource *
2541 socket_source_new (GSocket      *socket,
2542                    GIOCondition  condition,
2543                    GCancellable *cancellable)
2544 {
2545   GSource *source;
2546   GSocketSource *socket_source;
2547
2548 #ifdef G_OS_WIN32
2549   ensure_event (socket);
2550
2551   if (socket->priv->event == WSA_INVALID_EVENT)
2552     {
2553       g_warning ("Failed to create WSAEvent");
2554       return g_source_new (&broken_funcs, sizeof (GSource));
2555     }
2556 #endif
2557
2558   condition |= G_IO_HUP | G_IO_ERR;
2559
2560   source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
2561   g_source_set_name (source, "GSocket");
2562   socket_source = (GSocketSource *)source;
2563
2564   socket_source->socket = g_object_ref (socket);
2565   socket_source->condition = condition;
2566
2567   if (g_cancellable_make_pollfd (cancellable,
2568                                  &socket_source->cancel_pollfd))
2569     {
2570       socket_source->cancellable = g_object_ref (cancellable);
2571       g_source_add_poll (source, &socket_source->cancel_pollfd);
2572     }
2573
2574 #ifdef G_OS_WIN32
2575   add_condition_watch (socket, &socket_source->condition);
2576   socket_source->pollfd.fd = (gintptr) socket->priv->event;
2577 #else
2578   socket_source->pollfd.fd = socket->priv->fd;
2579 #endif
2580
2581   socket_source->pollfd.events = condition;
2582   socket_source->pollfd.revents = 0;
2583   g_source_add_poll (source, &socket_source->pollfd);
2584
2585   if (socket->priv->timeout)
2586     socket_source->timeout_time = g_get_monotonic_time () +
2587                                   socket->priv->timeout * 1000000;
2588
2589   else
2590     socket_source->timeout_time = 0;
2591
2592   return source;
2593 }
2594
2595 /**
2596  * g_socket_create_source: (skip)
2597  * @socket: a #GSocket
2598  * @condition: a #GIOCondition mask to monitor
2599  * @cancellable: (allow-none): a %GCancellable or %NULL
2600  *
2601  * Creates a %GSource that can be attached to a %GMainContext to monitor
2602  * for the availibility of the specified @condition on the socket.
2603  *
2604  * The callback on the source is of the #GSocketSourceFunc type.
2605  *
2606  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
2607  * these conditions will always be reported output if they are true.
2608  *
2609  * @cancellable if not %NULL can be used to cancel the source, which will
2610  * cause the source to trigger, reporting the current condition (which
2611  * is likely 0 unless cancellation happened at the same time as a
2612  * condition change). You can check for this in the callback using
2613  * g_cancellable_is_cancelled().
2614  *
2615  * If @socket has a timeout set, and it is reached before @condition
2616  * occurs, the source will then trigger anyway, reporting %G_IO_IN or
2617  * %G_IO_OUT depending on @condition. However, @socket will have been
2618  * marked as having had a timeout, and so the next #GSocket I/O method
2619  * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
2620  *
2621  * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
2622  *
2623  * Since: 2.22
2624  */
2625 GSource *
2626 g_socket_create_source (GSocket      *socket,
2627                         GIOCondition  condition,
2628                         GCancellable *cancellable)
2629 {
2630   g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
2631
2632   return socket_source_new (socket, condition, cancellable);
2633 }
2634
2635 /**
2636  * g_socket_condition_check:
2637  * @socket: a #GSocket
2638  * @condition: a #GIOCondition mask to check
2639  *
2640  * Checks on the readiness of @socket to perform operations.
2641  * The operations specified in @condition are checked for and masked
2642  * against the currently-satisfied conditions on @socket. The result
2643  * is returned.
2644  *
2645  * Note that on Windows, it is possible for an operation to return
2646  * %G_IO_ERROR_WOULD_BLOCK even immediately after
2647  * g_socket_condition_check() has claimed that the socket is ready for
2648  * writing. Rather than calling g_socket_condition_check() and then
2649  * writing to the socket if it succeeds, it is generally better to
2650  * simply try writing to the socket right away, and try again later if
2651  * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
2652  *
2653  * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
2654  * these conditions will always be set in the output if they are true.
2655  *
2656  * This call never blocks.
2657  *
2658  * Returns: the @GIOCondition mask of the current state
2659  *
2660  * Since: 2.22
2661  */
2662 GIOCondition
2663 g_socket_condition_check (GSocket      *socket,
2664                           GIOCondition  condition)
2665 {
2666   if (!check_socket (socket, NULL))
2667     return 0;
2668
2669 #ifdef G_OS_WIN32
2670   {
2671     GIOCondition current_condition;
2672
2673     condition |= G_IO_ERR | G_IO_HUP;
2674
2675     add_condition_watch (socket, &condition);
2676     current_condition = update_condition (socket);
2677     remove_condition_watch (socket, &condition);
2678     return condition & current_condition;
2679   }
2680 #else
2681   {
2682     GPollFD poll_fd;
2683     gint result;
2684     poll_fd.fd = socket->priv->fd;
2685     poll_fd.events = condition;
2686
2687     do
2688       result = g_poll (&poll_fd, 1, 0);
2689     while (result == -1 && get_socket_errno () == EINTR);
2690
2691     return poll_fd.revents;
2692   }
2693 #endif
2694 }
2695
2696 /**
2697  * g_socket_condition_wait:
2698  * @socket: a #GSocket
2699  * @condition: a #GIOCondition mask to wait for
2700  * @cancellable: (allow-none): a #GCancellable, or %NULL
2701  * @error: a #GError pointer, or %NULL
2702  *
2703  * Waits for @condition to become true on @socket. When the condition
2704  * is met, %TRUE is returned.
2705  *
2706  * If @cancellable is cancelled before the condition is met, or if the
2707  * socket has a timeout set and it is reached before the condition is
2708  * met, then %FALSE is returned and @error, if non-%NULL, is set to
2709  * the appropriate value (%G_IO_ERROR_CANCELLED or
2710  * %G_IO_ERROR_TIMED_OUT).
2711  *
2712  * Returns: %TRUE if the condition was met, %FALSE otherwise
2713  *
2714  * Since: 2.22
2715  */
2716 gboolean
2717 g_socket_condition_wait (GSocket       *socket,
2718                          GIOCondition   condition,
2719                          GCancellable  *cancellable,
2720                          GError       **error)
2721 {
2722   if (!check_socket (socket, error))
2723     return FALSE;
2724
2725   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2726     return FALSE;
2727
2728 #ifdef G_OS_WIN32
2729   {
2730     GIOCondition current_condition;
2731     WSAEVENT events[2];
2732     DWORD res, timeout;
2733     GPollFD cancel_fd;
2734     int num_events;
2735
2736     /* Always check these */
2737     condition |=  G_IO_ERR | G_IO_HUP;
2738
2739     add_condition_watch (socket, &condition);
2740
2741     num_events = 0;
2742     events[num_events++] = socket->priv->event;
2743
2744     if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
2745       events[num_events++] = (WSAEVENT)cancel_fd.fd;
2746
2747     if (socket->priv->timeout)
2748       timeout = socket->priv->timeout * 1000;
2749     else
2750       timeout = WSA_INFINITE;
2751
2752     current_condition = update_condition (socket);
2753     while ((condition & current_condition) == 0)
2754       {
2755         res = WSAWaitForMultipleEvents(num_events, events,
2756                                        FALSE, timeout, FALSE);
2757         if (res == WSA_WAIT_FAILED)
2758           {
2759             int errsv = get_socket_errno ();
2760
2761             g_set_error (error, G_IO_ERROR,
2762                          socket_io_error_from_errno (errsv),
2763                          _("Waiting for socket condition: %s"),
2764                          socket_strerror (errsv));
2765             break;
2766           }
2767         else if (res == WSA_WAIT_TIMEOUT)
2768           {
2769             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2770                                  _("Socket I/O timed out"));
2771             break;
2772           }
2773
2774         if (g_cancellable_set_error_if_cancelled (cancellable, error))
2775           break;
2776
2777         current_condition = update_condition (socket);
2778       }
2779     remove_condition_watch (socket, &condition);
2780     if (num_events > 1)
2781       g_cancellable_release_fd (cancellable);
2782
2783     return (condition & current_condition) != 0;
2784   }
2785 #else
2786   {
2787     GPollFD poll_fd[2];
2788     gint result;
2789     gint num;
2790     gint timeout;
2791
2792     poll_fd[0].fd = socket->priv->fd;
2793     poll_fd[0].events = condition;
2794     num = 1;
2795
2796     if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
2797       num++;
2798
2799     if (socket->priv->timeout)
2800       timeout = socket->priv->timeout * 1000;
2801     else
2802       timeout = -1;
2803
2804     do
2805       result = g_poll (poll_fd, num, timeout);
2806     while (result == -1 && get_socket_errno () == EINTR);
2807     
2808     if (num > 1)
2809       g_cancellable_release_fd (cancellable);
2810
2811     if (result == 0)
2812       {
2813         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
2814                              _("Socket I/O timed out"));
2815         return FALSE;
2816       }
2817
2818     return !g_cancellable_set_error_if_cancelled (cancellable, error);
2819   }
2820   #endif
2821 }
2822
2823 /**
2824  * g_socket_send_message:
2825  * @socket: a #GSocket
2826  * @address: a #GSocketAddress, or %NULL
2827  * @vectors: (array length=num_vectors): an array of #GOutputVector structs
2828  * @num_vectors: the number of elements in @vectors, or -1
2829  * @messages: (array length=num_messages) (allow-none): a pointer to an
2830  *   array of #GSocketControlMessages, or %NULL.
2831  * @num_messages: number of elements in @messages, or -1.
2832  * @flags: an int containing #GSocketMsgFlags flags
2833  * @cancellable: (allow-none): a %GCancellable or %NULL
2834  * @error: #GError for error reporting, or %NULL to ignore.
2835  *
2836  * Send data to @address on @socket.  This is the most complicated and
2837  * fully-featured version of this call. For easier use, see
2838  * g_socket_send() and g_socket_send_to().
2839  *
2840  * If @address is %NULL then the message is sent to the default receiver
2841  * (set by g_socket_connect()).
2842  *
2843  * @vectors must point to an array of #GOutputVector structs and
2844  * @num_vectors must be the length of this array. (If @num_vectors is -1,
2845  * then @vectors is assumed to be terminated by a #GOutputVector with a
2846  * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
2847  * that the sent data will be gathered from. Using multiple
2848  * #GOutputVector<!-- -->s is more memory-efficient than manually copying
2849  * data from multiple sources into a single buffer, and more
2850  * network-efficient than making multiple calls to g_socket_send().
2851  *
2852  * @messages, if non-%NULL, is taken to point to an array of @num_messages
2853  * #GSocketControlMessage instances. These correspond to the control
2854  * messages to be sent on the socket.
2855  * If @num_messages is -1 then @messages is treated as a %NULL-terminated
2856  * array.
2857  *
2858  * @flags modify how the message is sent. The commonly available arguments
2859  * for this are available in the #GSocketMsgFlags enum, but the
2860  * values there are the same as the system values, and the flags
2861  * are passed in as-is, so you can pass in system-specific flags too.
2862  *
2863  * If the socket is in blocking mode the call will block until there is
2864  * space for the data in the socket queue. If there is no space available
2865  * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
2866  * will be returned. To be notified when space is available, wait for the
2867  * %G_IO_OUT condition. Note though that you may still receive
2868  * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
2869  * notified of a %G_IO_OUT condition. (On Windows in particular, this is
2870  * very common due to the way the underlying APIs work.)
2871  *
2872  * On error -1 is returned and @error is set accordingly.
2873  *
2874  * Returns: Number of bytes written (which may be less than @size), or -1
2875  * on error
2876  *
2877  * Since: 2.22
2878  */
2879 gssize
2880 g_socket_send_message (GSocket                *socket,
2881                        GSocketAddress         *address,
2882                        GOutputVector          *vectors,
2883                        gint                    num_vectors,
2884                        GSocketControlMessage **messages,
2885                        gint                    num_messages,
2886                        gint                    flags,
2887                        GCancellable           *cancellable,
2888                        GError                **error)
2889 {
2890   GOutputVector one_vector;
2891   char zero;
2892
2893   if (!check_socket (socket, error))
2894     return -1;
2895
2896   if (g_cancellable_set_error_if_cancelled (cancellable, error))
2897     return -1;
2898
2899   if (num_vectors == -1)
2900     {
2901       for (num_vectors = 0;
2902            vectors[num_vectors].buffer != NULL;
2903            num_vectors++)
2904         ;
2905     }
2906
2907   if (num_messages == -1)
2908     {
2909       for (num_messages = 0;
2910            messages != NULL && messages[num_messages] != NULL;
2911            num_messages++)
2912         ;
2913     }
2914
2915   if (num_vectors == 0)
2916     {
2917       zero = '\0';
2918
2919       one_vector.buffer = &zero;
2920       one_vector.size = 1;
2921       num_vectors = 1;
2922       vectors = &one_vector;
2923     }
2924
2925 #ifndef G_OS_WIN32
2926   {
2927     struct msghdr msg;
2928     gssize result;
2929
2930    msg.msg_flags = 0;
2931
2932     /* name */
2933     if (address)
2934       {
2935         msg.msg_namelen = g_socket_address_get_native_size (address);
2936         msg.msg_name = g_alloca (msg.msg_namelen);
2937         if (!g_socket_address_to_native (address, msg.msg_name, msg.msg_namelen, error))
2938           return -1;
2939       }
2940     else
2941       {
2942         msg.msg_name = NULL;
2943         msg.msg_namelen = 0;
2944       }
2945
2946     /* iov */
2947     {
2948       /* this entire expression will be evaluated at compile time */
2949       if (sizeof *msg.msg_iov == sizeof *vectors &&
2950           sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
2951           G_STRUCT_OFFSET (struct iovec, iov_base) ==
2952           G_STRUCT_OFFSET (GOutputVector, buffer) &&
2953           sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
2954           G_STRUCT_OFFSET (struct iovec, iov_len) ==
2955           G_STRUCT_OFFSET (GOutputVector, size))
2956         /* ABI is compatible */
2957         {
2958           msg.msg_iov = (struct iovec *) vectors;
2959           msg.msg_iovlen = num_vectors;
2960         }
2961       else
2962         /* ABI is incompatible */
2963         {
2964           gint i;
2965
2966           msg.msg_iov = g_newa (struct iovec, num_vectors);
2967           for (i = 0; i < num_vectors; i++)
2968             {
2969               msg.msg_iov[i].iov_base = (void *) vectors[i].buffer;
2970               msg.msg_iov[i].iov_len = vectors[i].size;
2971             }
2972           msg.msg_iovlen = num_vectors;
2973         }
2974     }
2975
2976     /* control */
2977     {
2978       struct cmsghdr *cmsg;
2979       gint i;
2980
2981       msg.msg_controllen = 0;
2982       for (i = 0; i < num_messages; i++)
2983         msg.msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (messages[i]));
2984
2985       if (msg.msg_controllen == 0)
2986         msg.msg_control = NULL;
2987       else
2988         {
2989           msg.msg_control = g_alloca (msg.msg_controllen);
2990           memset (msg.msg_control, '\0', msg.msg_controllen);
2991         }
2992
2993       cmsg = CMSG_FIRSTHDR (&msg);
2994       for (i = 0; i < num_messages; i++)
2995         {
2996           cmsg->cmsg_level = g_socket_control_message_get_level (messages[i]);
2997           cmsg->cmsg_type = g_socket_control_message_get_msg_type (messages[i]);
2998           cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (messages[i]));
2999           g_socket_control_message_serialize (messages[i],
3000                                               CMSG_DATA (cmsg));
3001           cmsg = CMSG_NXTHDR (&msg, cmsg);
3002         }
3003       g_assert (cmsg == NULL);
3004     }
3005
3006     while (1)
3007       {
3008         if (socket->priv->blocking &&
3009             !g_socket_condition_wait (socket,
3010                                       G_IO_OUT, cancellable, error))
3011           return -1;
3012
3013         result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
3014         if (result < 0)
3015           {
3016             int errsv = get_socket_errno ();
3017
3018             if (errsv == EINTR)
3019               continue;
3020
3021             if (socket->priv->blocking &&
3022                 (errsv == EWOULDBLOCK ||
3023                  errsv == EAGAIN))
3024               continue;
3025
3026             g_set_error (error, G_IO_ERROR,
3027                          socket_io_error_from_errno (errsv),
3028                          _("Error sending message: %s"), socket_strerror (errsv));
3029
3030             return -1;
3031           }
3032         break;
3033       }
3034
3035     return result;
3036   }
3037 #else
3038   {
3039     struct sockaddr_storage addr;
3040     guint addrlen;
3041     DWORD bytes_sent;
3042     int result;
3043     WSABUF *bufs;
3044     gint i;
3045
3046     /* Win32 doesn't support control messages.
3047        Actually this is possible for raw and datagram sockets
3048        via WSASendMessage on Vista or later, but that doesn't
3049        seem very useful */
3050     if (num_messages != 0)
3051       {
3052         g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
3053                              _("GSocketControlMessage not supported on windows"));
3054         return -1;
3055       }
3056
3057     /* iov */
3058     bufs = g_newa (WSABUF, num_vectors);
3059     for (i = 0; i < num_vectors; i++)
3060       {
3061         bufs[i].buf = (char *)vectors[i].buffer;
3062         bufs[i].len = (gulong)vectors[i].size;
3063       }
3064
3065     /* name */
3066     addrlen = 0; /* Avoid warning */
3067     if (address)
3068       {
3069         addrlen = g_socket_address_get_native_size (address);
3070         if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
3071           return -1;
3072       }
3073
3074     while (1)
3075       {
3076         if (socket->priv->blocking &&
3077             !g_socket_condition_wait (socket,
3078                                       G_IO_OUT, cancellable, error))
3079           return -1;
3080
3081         if (address)
3082           result = WSASendTo (socket->priv->fd,
3083                               bufs, num_vectors,
3084                               &bytes_sent, flags,
3085                               (const struct sockaddr *)&addr, addrlen,
3086                               NULL, NULL);
3087         else
3088           result = WSASend (socket->priv->fd,
3089                             bufs, num_vectors,
3090                             &bytes_sent, flags,
3091                             NULL, NULL);
3092
3093         if (result != 0)
3094           {
3095             int errsv = get_socket_errno ();
3096
3097             if (errsv == WSAEINTR)
3098               continue;
3099
3100             if (errsv == WSAEWOULDBLOCK)
3101               win32_unset_event_mask (socket, FD_WRITE);
3102
3103             if (socket->priv->blocking &&
3104                 errsv == WSAEWOULDBLOCK)
3105               continue;
3106
3107             g_set_error (error, G_IO_ERROR,
3108                          socket_io_error_from_errno (errsv),
3109                          _("Error sending message: %s"), socket_strerror (errsv));
3110
3111             return -1;
3112           }
3113         break;
3114       }
3115
3116     return bytes_sent;
3117   }
3118 #endif
3119 }
3120
3121 /**
3122  * g_socket_receive_message:
3123  * @socket: a #GSocket
3124  * @address: a pointer to a #GSocketAddress pointer, or %NULL
3125  * @vectors: (array length=num_vectors): an array of #GInputVector structs
3126  * @num_vectors: the number of elements in @vectors, or -1
3127  * @messages: (array length=num_messages) (allow-none): a pointer which
3128  *    may be filled with an array of #GSocketControlMessages, or %NULL
3129  * @num_messages: a pointer which will be filled with the number of
3130  *    elements in @messages, or %NULL
3131  * @flags: a pointer to an int containing #GSocketMsgFlags flags
3132  * @cancellable: (allow-none): a %GCancellable or %NULL
3133  * @error: a #GError pointer, or %NULL
3134  *
3135  * Receive data from a socket.  This is the most complicated and
3136  * fully-featured version of this call. For easier use, see
3137  * g_socket_receive() and g_socket_receive_from().
3138  *
3139  * If @address is non-%NULL then @address will be set equal to the
3140  * source address of the received packet.
3141  * @address is owned by the caller.
3142  *
3143  * @vector must point to an array of #GInputVector structs and
3144  * @num_vectors must be the length of this array.  These structs
3145  * describe the buffers that received data will be scattered into.
3146  * If @num_vectors is -1, then @vectors is assumed to be terminated
3147  * by a #GInputVector with a %NULL buffer pointer.
3148  *
3149  * As a special case, if @num_vectors is 0 (in which case, @vectors
3150  * may of course be %NULL), then a single byte is received and
3151  * discarded. This is to facilitate the common practice of sending a
3152  * single '\0' byte for the purposes of transferring ancillary data.
3153  *
3154  * @messages, if non-%NULL, will be set to point to a newly-allocated
3155  * array of #GSocketControlMessage instances or %NULL if no such
3156  * messages was received. These correspond to the control messages
3157  * received from the kernel, one #GSocketControlMessage per message
3158  * from the kernel. This array is %NULL-terminated and must be freed
3159  * by the caller using g_free() after calling g_object_unref() on each
3160  * element. If @messages is %NULL, any control messages received will
3161  * be discarded.
3162  *
3163  * @num_messages, if non-%NULL, will be set to the number of control
3164  * messages received.
3165  *
3166  * If both @messages and @num_messages are non-%NULL, then
3167  * @num_messages gives the number of #GSocketControlMessage instances
3168  * in @messages (ie: not including the %NULL terminator).
3169  *
3170  * @flags is an in/out parameter. The commonly available arguments
3171  * for this are available in the #GSocketMsgFlags enum, but the
3172  * values there are the same as the system values, and the flags
3173  * are passed in as-is, so you can pass in system-specific flags too
3174  * (and g_socket_receive_message() may pass system-specific flags out).
3175  *
3176  * As with g_socket_receive(), data may be discarded if @socket is
3177  * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
3178  * provide enough buffer space to read a complete message. You can pass
3179  * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
3180  * removing it from the receive queue, but there is no portable way to find
3181  * out the length of the message other than by reading it into a
3182  * sufficiently-large buffer.
3183  *
3184  * If the socket is in blocking mode the call will block until there
3185  * is some data to receive or there is an error. If there is no data
3186  * available and the socket is in non-blocking mode, a
3187  * %G_IO_ERROR_WOULD_BLOCK error will be returned. To be notified when
3188  * data is available, wait for the %G_IO_IN condition.
3189  *
3190  * On error -1 is returned and @error is set accordingly.
3191  *
3192  * Returns: Number of bytes read, or -1 on error
3193  *
3194  * Since: 2.22
3195  */
3196 gssize
3197 g_socket_receive_message (GSocket                 *socket,
3198                           GSocketAddress         **address,
3199                           GInputVector            *vectors,
3200                           gint                     num_vectors,
3201                           GSocketControlMessage ***messages,
3202                           gint                    *num_messages,
3203                           gint                    *flags,
3204                           GCancellable            *cancellable,
3205                           GError                 **error)
3206 {
3207   GInputVector one_vector;
3208   char one_byte;
3209
3210   if (!check_socket (socket, error))
3211     return -1;
3212
3213   if (g_cancellable_set_error_if_cancelled (cancellable, error))
3214     return -1;
3215
3216   if (num_vectors == -1)
3217     {
3218       for (num_vectors = 0;
3219            vectors[num_vectors].buffer != NULL;
3220            num_vectors++)
3221         ;
3222     }
3223
3224   if (num_vectors == 0)
3225     {
3226       one_vector.buffer = &one_byte;
3227       one_vector.size = 1;
3228       num_vectors = 1;
3229       vectors = &one_vector;
3230     }
3231
3232 #ifndef G_OS_WIN32
3233   {
3234     struct msghdr msg;
3235     gssize result;
3236     struct sockaddr_storage one_sockaddr;
3237
3238     /* name */
3239     if (address)
3240       {
3241         msg.msg_name = &one_sockaddr;
3242         msg.msg_namelen = sizeof (struct sockaddr_storage);
3243       }
3244     else
3245       {
3246         msg.msg_name = NULL;
3247         msg.msg_namelen = 0;
3248       }
3249
3250     /* iov */
3251     /* this entire expression will be evaluated at compile time */
3252     if (sizeof *msg.msg_iov == sizeof *vectors &&
3253         sizeof msg.msg_iov->iov_base == sizeof vectors->buffer &&
3254         G_STRUCT_OFFSET (struct iovec, iov_base) ==
3255         G_STRUCT_OFFSET (GInputVector, buffer) &&
3256         sizeof msg.msg_iov->iov_len == sizeof vectors->size &&
3257         G_STRUCT_OFFSET (struct iovec, iov_len) ==
3258         G_STRUCT_OFFSET (GInputVector, size))
3259       /* ABI is compatible */
3260       {
3261         msg.msg_iov = (struct iovec *) vectors;
3262         msg.msg_iovlen = num_vectors;
3263       }
3264     else
3265       /* ABI is incompatible */
3266       {
3267         gint i;
3268
3269         msg.msg_iov = g_newa (struct iovec, num_vectors);
3270         for (i = 0; i < num_vectors; i++)
3271           {
3272             msg.msg_iov[i].iov_base = vectors[i].buffer;
3273             msg.msg_iov[i].iov_len = vectors[i].size;
3274           }
3275         msg.msg_iovlen = num_vectors;
3276       }
3277
3278     /* control */
3279     msg.msg_control = g_alloca (2048);
3280     msg.msg_controllen = 2048;
3281
3282     /* flags */
3283     if (flags != NULL)
3284       msg.msg_flags = *flags;
3285     else
3286       msg.msg_flags = 0;
3287
3288     /* do it */
3289     while (1)
3290       {
3291         if (socket->priv->blocking &&
3292             !g_socket_condition_wait (socket,
3293                                       G_IO_IN, cancellable, error))
3294           return -1;
3295
3296         result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
3297
3298         if (result < 0)
3299           {
3300             int errsv = get_socket_errno ();
3301
3302             if (errsv == EINTR)
3303               continue;
3304
3305             if (socket->priv->blocking &&
3306                 (errsv == EWOULDBLOCK ||
3307                  errsv == EAGAIN))
3308               continue;
3309
3310             g_set_error (error, G_IO_ERROR,
3311                          socket_io_error_from_errno (errsv),
3312                          _("Error receiving message: %s"), socket_strerror (errsv));
3313
3314             return -1;
3315           }
3316         break;
3317       }
3318
3319     /* decode address */
3320     if (address != NULL)
3321       {
3322         if (msg.msg_namelen > 0)
3323           *address = g_socket_address_new_from_native (msg.msg_name,
3324                                                        msg.msg_namelen);
3325         else
3326           *address = NULL;
3327       }
3328
3329     /* decode control messages */
3330     {
3331       GPtrArray *my_messages = NULL;
3332       struct cmsghdr *cmsg;
3333
3334       for (cmsg = CMSG_FIRSTHDR (&msg); cmsg; cmsg = CMSG_NXTHDR (&msg, cmsg))
3335         {
3336           GSocketControlMessage *message;
3337
3338           message = g_socket_control_message_deserialize (cmsg->cmsg_level,
3339                                                           cmsg->cmsg_type,
3340                                                           cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
3341                                                           CMSG_DATA (cmsg));
3342           if (message == NULL)
3343             /* We've already spewed about the problem in the
3344                deserialization code, so just continue */
3345             continue;
3346
3347           if (messages == NULL)
3348             {
3349               /* we have to do it this way if the user ignores the
3350                * messages so that we will close any received fds.
3351                */
3352               g_object_unref (message);
3353             }
3354           else
3355             {
3356               if (my_messages == NULL)
3357                 my_messages = g_ptr_array_new ();
3358               g_ptr_array_add (my_messages, message);
3359             }
3360         }
3361
3362       if (num_messages)
3363         *num_messages = my_messages != NULL ? my_messages->len : 0;
3364
3365       if (messages)
3366         {
3367           if (my_messages == NULL)
3368             {
3369               *messages = NULL;
3370             }
3371           else
3372             {
3373               g_ptr_array_add (my_messages, NULL);
3374               *messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
3375             }
3376         }
3377       else
3378         {
3379           g_assert (my_messages == NULL);
3380         }
3381     }
3382
3383     /* capture the flags */
3384     if (flags != NULL)
3385       *flags = msg.msg_flags;
3386
3387     return result;
3388   }
3389 #else
3390   {
3391     struct sockaddr_storage addr;
3392     int addrlen;
3393     DWORD bytes_received;
3394     DWORD win_flags;
3395     int result;
3396     WSABUF *bufs;
3397     gint i;
3398
3399     /* iov */
3400     bufs = g_newa (WSABUF, num_vectors);
3401     for (i = 0; i < num_vectors; i++)
3402       {
3403         bufs[i].buf = (char *)vectors[i].buffer;
3404         bufs[i].len = (gulong)vectors[i].size;
3405       }
3406
3407     /* flags */
3408     if (flags != NULL)
3409       win_flags = *flags;
3410     else
3411       win_flags = 0;
3412
3413     /* do it */
3414     while (1)
3415       {
3416         if (socket->priv->blocking &&
3417             !g_socket_condition_wait (socket,
3418                                       G_IO_IN, cancellable, error))
3419           return -1;
3420
3421         addrlen = sizeof addr;
3422         if (address)
3423           result = WSARecvFrom (socket->priv->fd,
3424                                 bufs, num_vectors,
3425                                 &bytes_received, &win_flags,
3426                                 (struct sockaddr *)&addr, &addrlen,
3427                                 NULL, NULL);
3428         else
3429           result = WSARecv (socket->priv->fd,
3430                             bufs, num_vectors,
3431                             &bytes_received, &win_flags,
3432                             NULL, NULL);
3433         if (result != 0)
3434           {
3435             int errsv = get_socket_errno ();
3436
3437             if (errsv == WSAEINTR)
3438               continue;
3439
3440             win32_unset_event_mask (socket, FD_READ);
3441
3442             if (socket->priv->blocking &&
3443                 errsv == WSAEWOULDBLOCK)
3444               continue;
3445
3446             g_set_error (error, G_IO_ERROR,
3447                          socket_io_error_from_errno (errsv),
3448                          _("Error receiving message: %s"), socket_strerror (errsv));
3449
3450             return -1;
3451           }
3452         win32_unset_event_mask (socket, FD_READ);
3453         break;
3454       }
3455
3456     /* decode address */
3457     if (address != NULL)
3458       {
3459         if (addrlen > 0)
3460           *address = g_socket_address_new_from_native (&addr, addrlen);
3461         else
3462           *address = NULL;
3463       }
3464
3465     /* capture the flags */
3466     if (flags != NULL)
3467       *flags = win_flags;
3468
3469     if (messages != NULL)
3470       *messages = NULL;
3471     if (num_messages != NULL)
3472       *num_messages = 0;
3473
3474     return bytes_received;
3475   }
3476 #endif
3477 }
3478
3479 /**
3480  * g_socket_get_credentials:
3481  * @socket: a #GSocket.
3482  * @error: #GError for error reporting, or %NULL to ignore.
3483  *
3484  * Returns the credentials of the foreign process connected to this
3485  * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
3486  * sockets).
3487  *
3488  * If this operation isn't supported on the OS, the method fails with
3489  * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
3490  * by reading the %SO_PEERCRED option on the underlying socket.
3491  *
3492  * Other ways to obtain credentials from a foreign peer includes the
3493  * #GUnixCredentialsMessage type and
3494  * g_unix_connection_send_credentials() /
3495  * g_unix_connection_receive_credentials() functions.
3496  *
3497  * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
3498  * that must be freed with g_object_unref().
3499  *
3500  * Since: 2.26
3501  */
3502 GCredentials *
3503 g_socket_get_credentials (GSocket   *socket,
3504                           GError   **error)
3505 {
3506   GCredentials *ret;
3507
3508   g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
3509   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3510
3511   ret = NULL;
3512
3513 #ifdef __linux__
3514   {
3515     struct ucred native_creds;
3516     socklen_t optlen;
3517     optlen = sizeof (struct ucred);
3518     if (getsockopt (socket->priv->fd,
3519                     SOL_SOCKET,
3520                     SO_PEERCRED,
3521                     (void *)&native_creds,
3522                     &optlen) != 0)
3523       {
3524         int errsv = get_socket_errno ();
3525         g_set_error (error,
3526                      G_IO_ERROR,
3527                      socket_io_error_from_errno (errsv),
3528                      _("Unable to get pending error: %s"),
3529                      socket_strerror (errsv));
3530       }
3531     else
3532       {
3533         ret = g_credentials_new ();
3534         g_credentials_set_native (ret,
3535                                   G_CREDENTIALS_TYPE_LINUX_UCRED,
3536                                   &native_creds);
3537       }
3538   }
3539 #else
3540   g_set_error_literal (error,
3541                        G_IO_ERROR,
3542                        G_IO_ERROR_NOT_SUPPORTED,
3543                        _("g_socket_get_credentials not implemented for this OS"));
3544 #endif
3545
3546   return ret;
3547 }