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