Coverage Report

Created: 2026-04-10 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/irssi/subprojects/glib-2.74.7/gio/gsocket.c
Line
Count
Source
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
 * Copyright © 2015 Collabora, Ltd.
7
 *
8
 * SPDX-License-Identifier: LGPL-2.1-or-later
9
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * This library is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General
21
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
22
 *
23
 * Authors: Christian Kellner <gicmo@gnome.org>
24
 *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
25
 *          Ryan Lortie <desrt@desrt.ca>
26
 *          Alexander Larsson <alexl@redhat.com>
27
 *          Philip Withnall <philip.withnall@collabora.co.uk>
28
 */
29
30
#include "config.h"
31
32
#include "gsocket.h"
33
34
#ifdef G_OS_UNIX
35
#include "glib-unix.h"
36
#endif
37
38
#include <errno.h>
39
#include <signal.h>
40
#include <string.h>
41
#include <stdlib.h>
42
43
#ifndef G_OS_WIN32
44
# include <fcntl.h>
45
# include <unistd.h>
46
# include <sys/ioctl.h>
47
#endif
48
49
#ifdef HAVE_SIOCGIFADDR
50
#include <net/if.h>
51
#endif
52
53
#ifdef HAVE_SYS_FILIO_H
54
# include <sys/filio.h>
55
#endif
56
57
#ifdef G_OS_UNIX
58
#include <sys/uio.h>
59
#endif
60
61
#define GOBJECT_COMPILATION
62
#include "gobject/gtype-private.h" /* For _PRELUDE type define */
63
#undef GOBJECT_COMPILATION
64
#include "gcancellable.h"
65
#include "gdatagrambased.h"
66
#include "gioenumtypes.h"
67
#include "ginetaddress.h"
68
#include "ginetsocketaddress.h"
69
#include "ginitable.h"
70
#include "gioerror.h"
71
#include "gioenums.h"
72
#include "gioerror.h"
73
#include "gnetworkingprivate.h"
74
#include "gsocketaddress.h"
75
#include "gsocketcontrolmessage.h"
76
#include "gcredentials.h"
77
#include "gcredentialsprivate.h"
78
#include "glibintl.h"
79
#include "gioprivate.h"
80
81
#ifdef G_OS_WIN32
82
#include "giowin32-afunix.h"
83
#endif
84
85
/**
86
 * SECTION:gsocket
87
 * @short_description: Low-level socket object
88
 * @include: gio/gio.h
89
 * @see_also: #GInitable, [<gnetworking.h>][gio-gnetworking.h]
90
 *
91
 * A #GSocket is a low-level networking primitive. It is a more or less
92
 * direct mapping of the BSD socket API in a portable GObject based API.
93
 * It supports both the UNIX socket implementations and winsock2 on Windows.
94
 *
95
 * #GSocket is the platform independent base upon which the higher level
96
 * network primitives are based. Applications are not typically meant to
97
 * use it directly, but rather through classes like #GSocketClient,
98
 * #GSocketService and #GSocketConnection. However there may be cases where
99
 * direct use of #GSocket is useful.
100
 *
101
 * #GSocket implements the #GInitable interface, so if it is manually constructed
102
 * by e.g. g_object_new() you must call g_initable_init() and check the
103
 * results before using the object. This is done automatically in
104
 * g_socket_new() and g_socket_new_from_fd(), so these functions can return
105
 * %NULL.
106
 *
107
 * Sockets operate in two general modes, blocking or non-blocking. When
108
 * in blocking mode all operations (which don’t take an explicit blocking
109
 * parameter) block until the requested operation
110
 * is finished or there is an error. In non-blocking mode all calls that
111
 * would block return immediately with a %G_IO_ERROR_WOULD_BLOCK error.
112
 * To know when a call would successfully run you can call g_socket_condition_check(),
113
 * or g_socket_condition_wait(). You can also use g_socket_create_source() and
114
 * attach it to a #GMainContext to get callbacks when I/O is possible.
115
 * Note that all sockets are always set to non blocking mode in the system, and
116
 * blocking mode is emulated in GSocket.
117
 *
118
 * When working in non-blocking mode applications should always be able to
119
 * handle getting a %G_IO_ERROR_WOULD_BLOCK error even when some other
120
 * function said that I/O was possible. This can easily happen in case
121
 * of a race condition in the application, but it can also happen for other
122
 * reasons. For instance, on Windows a socket is always seen as writable
123
 * until a write returns %G_IO_ERROR_WOULD_BLOCK.
124
 *
125
 * #GSockets can be either connection oriented or datagram based.
126
 * For connection oriented types you must first establish a connection by
127
 * either connecting to an address or accepting a connection from another
128
 * address. For connectionless socket types the target/source address is
129
 * specified or received in each I/O operation.
130
 *
131
 * All socket file descriptors are set to be close-on-exec.
132
 *
133
 * Note that creating a #GSocket causes the signal %SIGPIPE to be
134
 * ignored for the remainder of the program. If you are writing a
135
 * command-line utility that uses #GSocket, you may need to take into
136
 * account the fact that your program will not automatically be killed
137
 * if it tries to write to %stdout after it has been closed.
138
 *
139
 * Like most other APIs in GLib, #GSocket is not inherently thread safe. To use
140
 * a #GSocket concurrently from multiple threads, you must implement your own
141
 * locking.
142
 *
143
 * Since: 2.22
144
 */
145
146
static void     g_socket_initable_iface_init (GInitableIface  *iface);
147
static gboolean g_socket_initable_init       (GInitable       *initable,
148
                GCancellable    *cancellable,
149
                GError         **error);
150
151
static void     g_socket_datagram_based_iface_init       (GDatagramBasedInterface *iface);
152
static gint     g_socket_datagram_based_receive_messages (GDatagramBased  *self,
153
                                                          GInputMessage   *messages,
154
                                                          guint            num_messages,
155
                                                          gint             flags,
156
                                                          gint64           timeout_us,
157
                                                          GCancellable    *cancellable,
158
                                                          GError         **error);
159
static gint     g_socket_datagram_based_send_messages    (GDatagramBased  *self,
160
                                                          GOutputMessage  *messages,
161
                                                          guint            num_messages,
162
                                                          gint             flags,
163
                                                          gint64           timeout_us,
164
                                                          GCancellable    *cancellable,
165
                                                          GError         **error);
166
static GSource *g_socket_datagram_based_create_source    (GDatagramBased           *self,
167
                                                          GIOCondition              condition,
168
                                                          GCancellable             *cancellable);
169
static GIOCondition g_socket_datagram_based_condition_check      (GDatagramBased   *datagram_based,
170
                                                                  GIOCondition      condition);
171
static gboolean     g_socket_datagram_based_condition_wait       (GDatagramBased   *datagram_based,
172
                                                                  GIOCondition      condition,
173
                                                                  gint64            timeout_us,
174
                                                                  GCancellable     *cancellable,
175
                                                                  GError          **error);
176
177
static GSocketAddress *
178
cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len);
179
180
static gssize
181
g_socket_receive_message_with_timeout  (GSocket                 *socket,
182
                                        GSocketAddress         **address,
183
                                        GInputVector            *vectors,
184
                                        gint                     num_vectors,
185
                                        GSocketControlMessage ***messages,
186
                                        gint                    *num_messages,
187
                                        gint                    *flags,
188
                                        gint64                   timeout_us,
189
                                        GCancellable            *cancellable,
190
                                        GError                 **error);
191
static gint
192
g_socket_receive_messages_with_timeout (GSocket        *socket,
193
                                        GInputMessage  *messages,
194
                                        guint           num_messages,
195
                                        gint            flags,
196
                                        gint64          timeout_us,
197
                                        GCancellable   *cancellable,
198
                                        GError        **error);
199
static gint
200
g_socket_send_messages_with_timeout    (GSocket        *socket,
201
                                        GOutputMessage *messages,
202
                                        guint           num_messages,
203
                                        gint            flags,
204
                                        gint64          timeout_us,
205
                                        GCancellable   *cancellable,
206
                                        GError        **error);
207
208
enum
209
{
210
  PROP_0,
211
  PROP_FAMILY,
212
  PROP_TYPE,
213
  PROP_PROTOCOL,
214
  PROP_FD,
215
  PROP_BLOCKING,
216
  PROP_LISTEN_BACKLOG,
217
  PROP_KEEPALIVE,
218
  PROP_LOCAL_ADDRESS,
219
  PROP_REMOTE_ADDRESS,
220
  PROP_TIMEOUT,
221
  PROP_TTL,
222
  PROP_BROADCAST,
223
  PROP_MULTICAST_LOOPBACK,
224
  PROP_MULTICAST_TTL
225
};
226
227
/* Size of the receiver cache for g_socket_receive_from() */
228
0
#define RECV_ADDR_CACHE_SIZE 8
229
230
struct _GSocketPrivate
231
{
232
  GSocketFamily   family;
233
  GSocketType     type;
234
  GSocketProtocol protocol;
235
  gint            fd;
236
  gint            listen_backlog;
237
  guint           timeout;
238
  GError         *construct_error;
239
  GSocketAddress *remote_address;
240
  guint           inited : 1;
241
  guint           blocking : 1;
242
  guint           keepalive : 1;
243
  guint           closed : 1;
244
  guint           connected_read : 1;
245
  guint           connected_write : 1;
246
  guint           listening : 1;
247
  guint           timed_out : 1;
248
  guint           connect_pending : 1;
249
#ifdef G_OS_WIN32
250
  WSAEVENT        event;
251
  gboolean        waiting;
252
  DWORD           waiting_result;
253
  int             current_events;
254
  int             current_errors;
255
  int             selected_events;
256
  GList          *requested_conditions; /* list of requested GIOCondition * */
257
  GMutex          win32_source_lock;
258
  GCond           win32_source_cond;
259
#endif
260
261
  struct {
262
    GSocketAddress *addr;
263
    struct sockaddr *native;
264
    gsize native_len;
265
    guint64 last_used;
266
  } recv_addr_cache[RECV_ADDR_CACHE_SIZE];
267
};
268
269
0
_G_DEFINE_TYPE_EXTENDED_WITH_PRELUDE (GSocket, g_socket, G_TYPE_OBJECT, 0,
270
                                      /* Need a prelude for https://bugzilla.gnome.org/show_bug.cgi?id=674885 */
271
                                      g_type_ensure (G_TYPE_SOCKET_FAMILY);
272
                                      g_type_ensure (G_TYPE_SOCKET_TYPE);
273
                                      g_type_ensure (G_TYPE_SOCKET_PROTOCOL);
274
                                      g_type_ensure (G_TYPE_SOCKET_ADDRESS);
275
                                      /* And networking init is appropriate for the prelude */
276
                                      g_networking_init ();
277
                                      , /* And now the regular type init code */
278
                                      G_ADD_PRIVATE (GSocket)
279
                                      G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
280
                                                             g_socket_initable_iface_init);
281
                                      G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
282
                                                             g_socket_datagram_based_iface_init));
283
284
static int
285
get_socket_errno (void)
286
0
{
287
0
#ifndef G_OS_WIN32
288
0
  return errno;
289
#else
290
  return WSAGetLastError ();
291
#endif
292
0
}
293
294
static GIOErrorEnum
295
socket_io_error_from_errno (int err)
296
0
{
297
#ifdef G_OS_WIN32
298
  return g_io_error_from_win32_error (err);
299
#else
300
0
  return g_io_error_from_errno (err);
301
0
#endif
302
0
}
303
304
static const char *
305
socket_strerror (int err)
306
0
{
307
0
#ifndef G_OS_WIN32
308
0
  return g_strerror (err);
309
#else
310
  const char *msg_ret;
311
  char *msg;
312
313
  msg = g_win32_error_message (err);
314
315
  msg_ret = g_intern_string (msg);
316
  g_free (msg);
317
318
  return msg_ret;
319
#endif
320
0
}
321
322
/* Wrapper around g_set_error() to avoid doing excess work */
323
#define socket_set_error_lazy(err, errsv, fmt)                          \
324
0
  G_STMT_START {                                                        \
325
0
    GError **__err = (err);                                             \
326
0
    int __errsv = (errsv);                                              \
327
0
                                                                        \
328
0
    if (__err)                                                          \
329
0
      {                                                                 \
330
0
        int __code = socket_io_error_from_errno (__errsv);              \
331
0
        const char *__strerr = socket_strerror (__errsv);               \
332
0
                                                                        \
333
0
        if (__code == G_IO_ERROR_WOULD_BLOCK)                           \
334
0
          g_set_error_literal (__err, G_IO_ERROR, __code, __strerr);    \
335
0
        else                                                            \
336
0
          g_set_error (__err, G_IO_ERROR, __code, fmt, __strerr);       \
337
0
      }                                                                 \
338
0
  } G_STMT_END
339
340
#ifdef G_OS_WIN32
341
#define win32_unset_event_mask(_socket, _mask) _win32_unset_event_mask (_socket, _mask)
342
static void
343
_win32_unset_event_mask (GSocket *socket, int mask)
344
{
345
  g_mutex_lock (&socket->priv->win32_source_lock);
346
  socket->priv->current_events &= ~mask;
347
  socket->priv->current_errors &= ~mask;
348
  g_mutex_unlock (&socket->priv->win32_source_lock);
349
}
350
#else
351
#define win32_unset_event_mask(_socket, _mask)
352
#endif
353
354
/* Windows has broken prototypes... */
355
#ifdef G_OS_WIN32
356
#define getsockopt(sockfd, level, optname, optval, optlen) \
357
  getsockopt (sockfd, level, optname, (gpointer) optval, (int*) optlen)
358
#define setsockopt(sockfd, level, optname, optval, optlen) \
359
  setsockopt (sockfd, level, optname, (gpointer) optval, optlen)
360
#define getsockname(sockfd, addr, addrlen) \
361
  getsockname (sockfd, addr, (int *)addrlen)
362
#define getpeername(sockfd, addr, addrlen) \
363
  getpeername (sockfd, addr, (int *)addrlen)
364
#define recv(sockfd, buf, len, flags) \
365
  recv (sockfd, (gpointer)buf, len, flags)
366
#endif
367
368
static gchar *
369
address_to_string (GSocketAddress *address)
370
0
{
371
0
  GString *ret = g_string_new ("");
372
373
0
  if (G_IS_INET_SOCKET_ADDRESS (address))
374
0
    {
375
0
      GInetSocketAddress *isa = G_INET_SOCKET_ADDRESS (address);
376
0
      GInetAddress *ia = g_inet_socket_address_get_address (isa);
377
0
      GSocketFamily family = g_inet_address_get_family (ia);
378
0
      gchar *tmp;
379
380
      /* Represent IPv6 addresses in URL style:
381
       * ::1 port 12345 -> [::1]:12345 */
382
0
      if (family == G_SOCKET_FAMILY_IPV6)
383
0
        g_string_append_c (ret, '[');
384
385
0
      tmp = g_inet_address_to_string (ia);
386
0
      g_string_append (ret, tmp);
387
0
      g_free (tmp);
388
389
0
      if (family == G_SOCKET_FAMILY_IPV6)
390
0
        {
391
0
          guint32 scope = g_inet_socket_address_get_scope_id (isa);
392
393
0
          if (scope != 0)
394
0
            g_string_append_printf (ret, "%%%u", scope);
395
396
0
          g_string_append_c (ret, ']');
397
0
        }
398
399
0
      g_string_append_c (ret, ':');
400
401
0
      g_string_append_printf (ret, "%u", g_inet_socket_address_get_port (isa));
402
0
    }
403
0
  else
404
0
    {
405
      /* For unknown address types, just show the type */
406
0
      g_string_append_printf (ret, "(%s)", G_OBJECT_TYPE_NAME (address));
407
0
    }
408
409
0
  return g_string_free (ret, FALSE);
410
0
}
411
412
static gboolean
413
check_socket (GSocket *socket,
414
        GError **error)
415
0
{
416
0
  if (!socket->priv->inited)
417
0
    {
418
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
419
0
                           _("Invalid socket, not initialized"));
420
0
      return FALSE;
421
0
    }
422
423
0
  if (socket->priv->construct_error)
424
0
    {
425
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_INITIALIZED,
426
0
       _("Invalid socket, initialization failed due to: %s"),
427
0
       socket->priv->construct_error->message);
428
0
      return FALSE;
429
0
    }
430
431
0
  if (socket->priv->closed)
432
0
    {
433
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
434
0
         _("Socket is already closed"));
435
0
      return FALSE;
436
0
    }
437
438
0
  return TRUE;
439
0
}
440
441
static gboolean
442
check_timeout (GSocket *socket,
443
         GError **error)
444
0
{
445
0
  if (socket->priv->timed_out)
446
0
    {
447
0
      socket->priv->timed_out = FALSE;
448
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
449
0
         _("Socket I/O timed out"));
450
0
      return FALSE;
451
0
    }
452
453
0
  return TRUE;
454
0
}
455
456
static void
457
g_socket_details_from_fd (GSocket *socket)
458
0
{
459
0
  union {
460
0
    struct sockaddr_storage storage;
461
0
    struct sockaddr sa;
462
0
  } address;
463
0
  gint fd;
464
0
  guint addrlen;
465
0
  int value, family;
466
0
  int errsv;
467
468
0
  memset (&address, 0, sizeof (address));
469
470
0
  fd = socket->priv->fd;
471
0
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_TYPE, &value, NULL))
472
0
    {
473
0
      errsv = get_socket_errno ();
474
0
      goto err;
475
0
    }
476
477
0
  switch (value)
478
0
    {
479
0
     case SOCK_STREAM:
480
0
      socket->priv->type = G_SOCKET_TYPE_STREAM;
481
0
      break;
482
483
0
     case SOCK_DGRAM:
484
0
      socket->priv->type = G_SOCKET_TYPE_DATAGRAM;
485
0
      break;
486
487
0
     case SOCK_SEQPACKET:
488
0
      socket->priv->type = G_SOCKET_TYPE_SEQPACKET;
489
0
      break;
490
491
0
     default:
492
0
      socket->priv->type = G_SOCKET_TYPE_INVALID;
493
0
      break;
494
0
    }
495
496
0
  addrlen = sizeof address;
497
0
  if (getsockname (fd, &address.sa, &addrlen) != 0)
498
0
    {
499
0
      errsv = get_socket_errno ();
500
0
      goto err;
501
0
    }
502
503
0
  if (addrlen > 0)
504
0
    {
505
0
      g_assert (G_STRUCT_OFFSET (struct sockaddr, sa_family) +
506
0
    sizeof address.storage.ss_family <= addrlen);
507
0
      family = address.storage.ss_family;
508
0
    }
509
0
  else
510
0
    {
511
      /* On Solaris, this happens if the socket is not yet connected.
512
       * But we can use SO_DOMAIN as a workaround there.
513
       */
514
0
#ifdef SO_DOMAIN
515
0
      if (!g_socket_get_option (socket, SOL_SOCKET, SO_DOMAIN, &family, NULL))
516
0
  {
517
0
    errsv = get_socket_errno ();
518
0
    goto err;
519
0
  }
520
#else
521
      /* This will translate to G_IO_ERROR_FAILED on either unix or windows */
522
      errsv = -1;
523
      goto err;
524
#endif
525
0
    }
526
527
0
  switch (family)
528
0
    {
529
0
     case G_SOCKET_FAMILY_IPV4:
530
0
     case G_SOCKET_FAMILY_IPV6:
531
0
       socket->priv->family = address.storage.ss_family;
532
0
       switch (socket->priv->type)
533
0
   {
534
0
   case G_SOCKET_TYPE_STREAM:
535
0
     socket->priv->protocol = G_SOCKET_PROTOCOL_TCP;
536
0
     break;
537
538
0
   case G_SOCKET_TYPE_DATAGRAM:
539
0
     socket->priv->protocol = G_SOCKET_PROTOCOL_UDP;
540
0
     break;
541
542
0
   case G_SOCKET_TYPE_SEQPACKET:
543
0
     socket->priv->protocol = G_SOCKET_PROTOCOL_SCTP;
544
0
     break;
545
546
0
   default:
547
0
     break;
548
0
   }
549
0
       break;
550
551
0
     case G_SOCKET_FAMILY_UNIX:
552
0
       socket->priv->family = G_SOCKET_FAMILY_UNIX;
553
0
       socket->priv->protocol = G_SOCKET_PROTOCOL_DEFAULT;
554
0
       break;
555
556
0
     default:
557
0
       socket->priv->family = G_SOCKET_FAMILY_INVALID;
558
0
       break;
559
0
    }
560
561
0
  if (socket->priv->family != G_SOCKET_FAMILY_INVALID)
562
0
    {
563
0
      addrlen = sizeof address;
564
0
      if (getpeername (fd, &address.sa, &addrlen) >= 0)
565
0
        {
566
0
          socket->priv->connected_read = TRUE;
567
0
          socket->priv->connected_write = TRUE;
568
0
        }
569
0
    }
570
571
0
  if (g_socket_get_option (socket, SOL_SOCKET, SO_KEEPALIVE, &value, NULL))
572
0
    {
573
0
      socket->priv->keepalive = !!value;
574
0
    }
575
0
  else
576
0
    {
577
      /* Can't read, maybe not supported, assume FALSE */
578
0
      socket->priv->keepalive = FALSE;
579
0
    }
580
581
0
  return;
582
583
0
 err:
584
0
  g_set_error (&socket->priv->construct_error, G_IO_ERROR,
585
0
         socket_io_error_from_errno (errsv),
586
0
         _("creating GSocket from fd: %s"),
587
0
         socket_strerror (errsv));
588
0
}
589
590
/* Wrapper around socket() that is shared with gnetworkmonitornetlink.c */
591
gint
592
g_socket (gint     domain,
593
          gint     type,
594
          gint     protocol,
595
          GError **error)
596
0
{
597
0
  int fd, errsv;
598
599
0
#ifdef SOCK_CLOEXEC
600
0
  fd = socket (domain, type | SOCK_CLOEXEC, protocol);
601
0
  errsv = errno;
602
0
  if (fd != -1)
603
0
    return fd;
604
605
  /* It's possible that libc has SOCK_CLOEXEC but the kernel does not */
606
0
  if (fd < 0 && (errsv == EINVAL || errsv == EPROTOTYPE))
607
0
#endif
608
0
    fd = socket (domain, type, protocol);
609
610
0
  if (fd < 0)
611
0
    {
612
0
      errsv = get_socket_errno ();
613
614
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
615
0
       _("Unable to create socket: %s"), socket_strerror (errsv));
616
0
      errno = errsv;
617
0
      return -1;
618
0
    }
619
620
0
#ifndef G_OS_WIN32
621
0
  {
622
0
    int flags;
623
624
    /* We always want to set close-on-exec to protect users. If you
625
       need to so some weird inheritance to exec you can re-enable this
626
       using lower level hacks with g_socket_get_fd(). */
627
0
    flags = fcntl (fd, F_GETFD, 0);
628
0
    if (flags != -1 &&
629
0
  (flags & FD_CLOEXEC) == 0)
630
0
      {
631
0
  flags |= FD_CLOEXEC;
632
0
  (void) fcntl (fd, F_SETFD, flags);
633
0
      }
634
0
  }
635
#else
636
  if ((domain == AF_INET || domain == AF_INET6) && type == SOCK_DGRAM)
637
    {
638
      BOOL new_behavior = FALSE;
639
      DWORD bytes_returned = 0;
640
641
      /* Disable connection reset error on ICMP port unreachable. */
642
      WSAIoctl (fd, SIO_UDP_CONNRESET, &new_behavior, sizeof (new_behavior),
643
                NULL, 0, &bytes_returned, NULL, NULL);
644
    }
645
#endif
646
647
0
  return fd;
648
0
}
649
650
static gint
651
g_socket_create_socket (GSocketFamily   family,
652
      GSocketType     type,
653
      int             protocol,
654
      GError        **error)
655
0
{
656
0
  gint native_type;
657
658
0
  switch (type)
659
0
    {
660
0
     case G_SOCKET_TYPE_STREAM:
661
0
      native_type = SOCK_STREAM;
662
0
      break;
663
664
0
     case G_SOCKET_TYPE_DATAGRAM:
665
0
      native_type = SOCK_DGRAM;
666
0
      break;
667
668
0
     case G_SOCKET_TYPE_SEQPACKET:
669
0
      native_type = SOCK_SEQPACKET;
670
0
      break;
671
672
0
     default:
673
0
      g_assert_not_reached ();
674
0
    }
675
676
0
  if (family <= 0)
677
0
    {
678
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
679
0
                   _("Unable to create socket: %s"), _("Unknown family was specified"));
680
0
      return -1;
681
0
    }
682
683
0
  if (protocol == -1)
684
0
    {
685
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
686
0
       _("Unable to create socket: %s"), _("Unknown protocol was specified"));
687
0
      return -1;
688
0
    }
689
690
0
  return g_socket (family, native_type, protocol, error);
691
0
}
692
693
static void
694
g_socket_constructed (GObject *object)
695
0
{
696
0
  GSocket *socket = G_SOCKET (object);
697
698
0
  if (socket->priv->fd >= 0)
699
    /* create socket->priv info from the fd */
700
0
    g_socket_details_from_fd (socket);
701
702
0
  else
703
    /* create the fd from socket->priv info */
704
0
    socket->priv->fd = g_socket_create_socket (socket->priv->family,
705
0
                 socket->priv->type,
706
0
                 socket->priv->protocol,
707
0
                 &socket->priv->construct_error);
708
709
0
  if (socket->priv->fd != -1)
710
0
    {
711
0
#ifndef G_OS_WIN32
712
0
      GError *error = NULL;
713
#else
714
      gulong arg;
715
#endif
716
717
      /* Always use native nonblocking sockets, as Windows sets sockets to
718
       * nonblocking automatically in certain operations. This way we make
719
       * things work the same on all platforms.
720
       */
721
0
#ifndef G_OS_WIN32
722
0
      if (!g_unix_set_fd_nonblocking (socket->priv->fd, TRUE, &error))
723
0
        {
724
0
          g_warning ("Error setting socket nonblocking: %s", error->message);
725
0
          g_clear_error (&error);
726
0
        }
727
#else
728
      arg = TRUE;
729
730
      if (ioctlsocket (socket->priv->fd, FIONBIO, &arg) == SOCKET_ERROR)
731
        {
732
          int errsv = get_socket_errno ();
733
          g_warning ("Error setting socket status flags: %s", socket_strerror (errsv));
734
        }
735
#endif
736
737
#ifdef SO_NOSIGPIPE
738
      /* See note about SIGPIPE below. */
739
      g_socket_set_option (socket, SOL_SOCKET, SO_NOSIGPIPE, TRUE, NULL);
740
#endif
741
0
    }
742
0
}
743
744
static void
745
g_socket_get_property (GObject    *object,
746
           guint       prop_id,
747
           GValue     *value,
748
           GParamSpec *pspec)
749
0
{
750
0
  GSocket *socket = G_SOCKET (object);
751
0
  GSocketAddress *address;
752
753
0
  switch (prop_id)
754
0
    {
755
0
      case PROP_FAMILY:
756
0
  g_value_set_enum (value, socket->priv->family);
757
0
  break;
758
759
0
      case PROP_TYPE:
760
0
  g_value_set_enum (value, socket->priv->type);
761
0
  break;
762
763
0
      case PROP_PROTOCOL:
764
0
  g_value_set_enum (value, socket->priv->protocol);
765
0
  break;
766
767
0
      case PROP_FD:
768
0
  g_value_set_int (value, socket->priv->fd);
769
0
  break;
770
771
0
      case PROP_BLOCKING:
772
0
  g_value_set_boolean (value, socket->priv->blocking);
773
0
  break;
774
775
0
      case PROP_LISTEN_BACKLOG:
776
0
  g_value_set_int (value, socket->priv->listen_backlog);
777
0
  break;
778
779
0
      case PROP_KEEPALIVE:
780
0
  g_value_set_boolean (value, socket->priv->keepalive);
781
0
  break;
782
783
0
      case PROP_LOCAL_ADDRESS:
784
0
  address = g_socket_get_local_address (socket, NULL);
785
0
  g_value_take_object (value, address);
786
0
  break;
787
788
0
      case PROP_REMOTE_ADDRESS:
789
0
  address = g_socket_get_remote_address (socket, NULL);
790
0
  g_value_take_object (value, address);
791
0
  break;
792
793
0
      case PROP_TIMEOUT:
794
0
  g_value_set_uint (value, socket->priv->timeout);
795
0
  break;
796
797
0
      case PROP_TTL:
798
0
  g_value_set_uint (value, g_socket_get_ttl (socket));
799
0
  break;
800
801
0
      case PROP_BROADCAST:
802
0
  g_value_set_boolean (value, g_socket_get_broadcast (socket));
803
0
  break;
804
805
0
      case PROP_MULTICAST_LOOPBACK:
806
0
  g_value_set_boolean (value, g_socket_get_multicast_loopback (socket));
807
0
  break;
808
809
0
      case PROP_MULTICAST_TTL:
810
0
  g_value_set_uint (value, g_socket_get_multicast_ttl (socket));
811
0
  break;
812
813
0
      default:
814
0
  G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
815
0
    }
816
0
}
817
818
static void
819
g_socket_set_property (GObject      *object,
820
           guint         prop_id,
821
           const GValue *value,
822
           GParamSpec   *pspec)
823
0
{
824
0
  GSocket *socket = G_SOCKET (object);
825
826
0
  switch (prop_id)
827
0
    {
828
0
      case PROP_FAMILY:
829
0
  socket->priv->family = g_value_get_enum (value);
830
0
  break;
831
832
0
      case PROP_TYPE:
833
0
  socket->priv->type = g_value_get_enum (value);
834
0
  break;
835
836
0
      case PROP_PROTOCOL:
837
0
  socket->priv->protocol = g_value_get_enum (value);
838
0
  break;
839
840
0
      case PROP_FD:
841
0
  socket->priv->fd = g_value_get_int (value);
842
0
  break;
843
844
0
      case PROP_BLOCKING:
845
0
  g_socket_set_blocking (socket, g_value_get_boolean (value));
846
0
  break;
847
848
0
      case PROP_LISTEN_BACKLOG:
849
0
  g_socket_set_listen_backlog (socket, g_value_get_int (value));
850
0
  break;
851
852
0
      case PROP_KEEPALIVE:
853
0
  g_socket_set_keepalive (socket, g_value_get_boolean (value));
854
0
  break;
855
856
0
      case PROP_TIMEOUT:
857
0
  g_socket_set_timeout (socket, g_value_get_uint (value));
858
0
  break;
859
860
0
      case PROP_TTL:
861
0
  g_socket_set_ttl (socket, g_value_get_uint (value));
862
0
  break;
863
864
0
      case PROP_BROADCAST:
865
0
  g_socket_set_broadcast (socket, g_value_get_boolean (value));
866
0
  break;
867
868
0
      case PROP_MULTICAST_LOOPBACK:
869
0
  g_socket_set_multicast_loopback (socket, g_value_get_boolean (value));
870
0
  break;
871
872
0
      case PROP_MULTICAST_TTL:
873
0
  g_socket_set_multicast_ttl (socket, g_value_get_uint (value));
874
0
  break;
875
876
0
      default:
877
0
  G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
878
0
    }
879
0
}
880
881
static void
882
g_socket_finalize (GObject *object)
883
0
{
884
0
  GSocket *socket = G_SOCKET (object);
885
0
  gint i;
886
887
0
  g_clear_error (&socket->priv->construct_error);
888
889
0
  if (socket->priv->fd != -1 &&
890
0
      !socket->priv->closed)
891
0
    g_socket_close (socket, NULL);
892
893
0
  if (socket->priv->remote_address)
894
0
    g_object_unref (socket->priv->remote_address);
895
896
#ifdef G_OS_WIN32
897
  if (socket->priv->event != WSA_INVALID_EVENT)
898
    {
899
      WSACloseEvent (socket->priv->event);
900
      socket->priv->event = WSA_INVALID_EVENT;
901
    }
902
903
  g_assert (socket->priv->requested_conditions == NULL);
904
  g_mutex_clear (&socket->priv->win32_source_lock);
905
  g_cond_clear (&socket->priv->win32_source_cond);
906
#endif
907
908
0
  for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
909
0
    {
910
0
      if (socket->priv->recv_addr_cache[i].addr)
911
0
        {
912
0
          g_object_unref (socket->priv->recv_addr_cache[i].addr);
913
0
          g_free (socket->priv->recv_addr_cache[i].native);
914
0
        }
915
0
    }
916
917
0
  if (G_OBJECT_CLASS (g_socket_parent_class)->finalize)
918
0
    (*G_OBJECT_CLASS (g_socket_parent_class)->finalize) (object);
919
0
}
920
921
static void
922
g_socket_class_init (GSocketClass *klass)
923
0
{
924
0
  GObjectClass *gobject_class G_GNUC_UNUSED = G_OBJECT_CLASS (klass);
925
926
0
#ifdef SIGPIPE
927
  /* There is no portable, thread-safe way to avoid having the process
928
   * be killed by SIGPIPE when calling send() or sendmsg(), so we are
929
   * forced to simply ignore the signal process-wide.
930
   *
931
   * Even if we ignore it though, gdb will still stop if the app
932
   * receives a SIGPIPE, which can be confusing and annoying. So when
933
   * possible, we also use MSG_NOSIGNAL / SO_NOSIGPIPE elsewhere to
934
   * prevent the signal from occurring at all.
935
   */
936
0
  signal (SIGPIPE, SIG_IGN);
937
0
#endif
938
939
0
  gobject_class->finalize = g_socket_finalize;
940
0
  gobject_class->constructed = g_socket_constructed;
941
0
  gobject_class->set_property = g_socket_set_property;
942
0
  gobject_class->get_property = g_socket_get_property;
943
944
0
  g_object_class_install_property (gobject_class, PROP_FAMILY,
945
0
           g_param_spec_enum ("family",
946
0
                  P_("Socket family"),
947
0
                  P_("The sockets address family"),
948
0
                  G_TYPE_SOCKET_FAMILY,
949
0
                  G_SOCKET_FAMILY_INVALID,
950
0
                  G_PARAM_CONSTRUCT_ONLY |
951
0
                                                      G_PARAM_READWRITE |
952
0
                                                      G_PARAM_STATIC_STRINGS));
953
954
0
  g_object_class_install_property (gobject_class, PROP_TYPE,
955
0
           g_param_spec_enum ("type",
956
0
                  P_("Socket type"),
957
0
                  P_("The sockets type"),
958
0
                  G_TYPE_SOCKET_TYPE,
959
0
                  G_SOCKET_TYPE_STREAM,
960
0
                  G_PARAM_CONSTRUCT_ONLY |
961
0
                                                      G_PARAM_READWRITE |
962
0
                                                      G_PARAM_STATIC_STRINGS));
963
964
0
  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
965
0
           g_param_spec_enum ("protocol",
966
0
                  P_("Socket protocol"),
967
0
                  P_("The id of the protocol to use, or -1 for unknown"),
968
0
                  G_TYPE_SOCKET_PROTOCOL,
969
0
                  G_SOCKET_PROTOCOL_UNKNOWN,
970
0
                  G_PARAM_CONSTRUCT_ONLY |
971
0
                                                      G_PARAM_READWRITE |
972
0
                                                      G_PARAM_STATIC_STRINGS));
973
974
0
  g_object_class_install_property (gobject_class, PROP_FD,
975
0
           g_param_spec_int ("fd",
976
0
                 P_("File descriptor"),
977
0
                 P_("The sockets file descriptor"),
978
0
                 G_MININT,
979
0
                 G_MAXINT,
980
0
                 -1,
981
0
                 G_PARAM_CONSTRUCT_ONLY |
982
0
                                                     G_PARAM_READWRITE |
983
0
                                                     G_PARAM_STATIC_STRINGS));
984
985
0
  g_object_class_install_property (gobject_class, PROP_BLOCKING,
986
0
           g_param_spec_boolean ("blocking",
987
0
               P_("blocking"),
988
0
               P_("Whether or not I/O on this socket is blocking"),
989
0
               TRUE,
990
0
               G_PARAM_READWRITE |
991
0
                                                         G_PARAM_STATIC_STRINGS));
992
993
0
  g_object_class_install_property (gobject_class, PROP_LISTEN_BACKLOG,
994
0
           g_param_spec_int ("listen-backlog",
995
0
                 P_("Listen backlog"),
996
0
                 P_("Outstanding connections in the listen queue"),
997
0
                 0,
998
0
                 SOMAXCONN,
999
0
                 10,
1000
0
                 G_PARAM_READWRITE |
1001
0
                                                     G_PARAM_STATIC_STRINGS));
1002
1003
0
  g_object_class_install_property (gobject_class, PROP_KEEPALIVE,
1004
0
           g_param_spec_boolean ("keepalive",
1005
0
               P_("Keep connection alive"),
1006
0
               P_("Keep connection alive by sending periodic pings"),
1007
0
               FALSE,
1008
0
               G_PARAM_READWRITE |
1009
0
                                                         G_PARAM_STATIC_STRINGS));
1010
1011
0
  g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
1012
0
           g_param_spec_object ("local-address",
1013
0
              P_("Local address"),
1014
0
              P_("The local address the socket is bound to"),
1015
0
              G_TYPE_SOCKET_ADDRESS,
1016
0
              G_PARAM_READABLE |
1017
0
                                                        G_PARAM_STATIC_STRINGS));
1018
1019
0
  g_object_class_install_property (gobject_class, PROP_REMOTE_ADDRESS,
1020
0
           g_param_spec_object ("remote-address",
1021
0
              P_("Remote address"),
1022
0
              P_("The remote address the socket is connected to"),
1023
0
              G_TYPE_SOCKET_ADDRESS,
1024
0
              G_PARAM_READABLE |
1025
0
                                                        G_PARAM_STATIC_STRINGS));
1026
1027
  /**
1028
   * GSocket:timeout:
1029
   *
1030
   * The timeout in seconds on socket I/O
1031
   *
1032
   * Since: 2.26
1033
   */
1034
0
  g_object_class_install_property (gobject_class, PROP_TIMEOUT,
1035
0
           g_param_spec_uint ("timeout",
1036
0
                  P_("Timeout"),
1037
0
                  P_("The timeout in seconds on socket I/O"),
1038
0
                  0,
1039
0
                  G_MAXUINT,
1040
0
                  0,
1041
0
                  G_PARAM_READWRITE |
1042
0
                  G_PARAM_STATIC_STRINGS));
1043
1044
  /**
1045
   * GSocket:broadcast:
1046
   *
1047
   * Whether the socket should allow sending to broadcast addresses.
1048
   *
1049
   * Since: 2.32
1050
   */
1051
0
  g_object_class_install_property (gobject_class, PROP_BROADCAST,
1052
0
           g_param_spec_boolean ("broadcast",
1053
0
               P_("Broadcast"),
1054
0
               P_("Whether to allow sending to broadcast addresses"),
1055
0
               FALSE,
1056
0
               G_PARAM_READWRITE |
1057
0
                                                         G_PARAM_STATIC_STRINGS));
1058
1059
  /**
1060
   * GSocket:ttl:
1061
   *
1062
   * Time-to-live for outgoing unicast packets
1063
   *
1064
   * Since: 2.32
1065
   */
1066
0
  g_object_class_install_property (gobject_class, PROP_TTL,
1067
0
           g_param_spec_uint ("ttl",
1068
0
                  P_("TTL"),
1069
0
                  P_("Time-to-live of outgoing unicast packets"),
1070
0
                  0, G_MAXUINT, 0,
1071
0
                  G_PARAM_READWRITE |
1072
0
                  G_PARAM_STATIC_STRINGS));
1073
1074
  /**
1075
   * GSocket:multicast-loopback:
1076
   *
1077
   * Whether outgoing multicast packets loop back to the local host.
1078
   *
1079
   * Since: 2.32
1080
   */
1081
0
  g_object_class_install_property (gobject_class, PROP_MULTICAST_LOOPBACK,
1082
0
           g_param_spec_boolean ("multicast-loopback",
1083
0
               P_("Multicast loopback"),
1084
0
               P_("Whether outgoing multicast packets loop back to the local host"),
1085
0
               TRUE,
1086
0
               G_PARAM_READWRITE |
1087
0
                                                         G_PARAM_STATIC_STRINGS));
1088
1089
  /**
1090
   * GSocket:multicast-ttl:
1091
   *
1092
   * Time-to-live out outgoing multicast packets
1093
   *
1094
   * Since: 2.32
1095
   */
1096
0
  g_object_class_install_property (gobject_class, PROP_MULTICAST_TTL,
1097
0
           g_param_spec_uint ("multicast-ttl",
1098
0
                  P_("Multicast TTL"),
1099
0
                  P_("Time-to-live of outgoing multicast packets"),
1100
0
                  0, G_MAXUINT, 1,
1101
0
                  G_PARAM_READWRITE |
1102
0
                  G_PARAM_STATIC_STRINGS));
1103
0
}
1104
1105
static void
1106
g_socket_initable_iface_init (GInitableIface *iface)
1107
0
{
1108
0
  iface->init = g_socket_initable_init;
1109
0
}
1110
1111
static void
1112
g_socket_datagram_based_iface_init (GDatagramBasedInterface *iface)
1113
0
{
1114
0
  iface->receive_messages = g_socket_datagram_based_receive_messages;
1115
0
  iface->send_messages = g_socket_datagram_based_send_messages;
1116
0
  iface->create_source = g_socket_datagram_based_create_source;
1117
0
  iface->condition_check = g_socket_datagram_based_condition_check;
1118
0
  iface->condition_wait = g_socket_datagram_based_condition_wait;
1119
0
}
1120
1121
static void
1122
g_socket_init (GSocket *socket)
1123
0
{
1124
0
  socket->priv = g_socket_get_instance_private (socket);
1125
1126
0
  socket->priv->fd = -1;
1127
0
  socket->priv->blocking = TRUE;
1128
0
  socket->priv->listen_backlog = 10;
1129
0
  socket->priv->construct_error = NULL;
1130
#ifdef G_OS_WIN32
1131
  socket->priv->event = WSA_INVALID_EVENT;
1132
  g_mutex_init (&socket->priv->win32_source_lock);
1133
  g_cond_init (&socket->priv->win32_source_cond);
1134
#endif
1135
0
}
1136
1137
static gboolean
1138
g_socket_initable_init (GInitable *initable,
1139
      GCancellable *cancellable,
1140
      GError  **error)
1141
0
{
1142
0
  GSocket  *socket;
1143
1144
0
  g_return_val_if_fail (G_IS_SOCKET (initable), FALSE);
1145
1146
0
  socket = G_SOCKET (initable);
1147
1148
0
  if (cancellable != NULL)
1149
0
    {
1150
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1151
0
                           _("Cancellable initialization not supported"));
1152
0
      return FALSE;
1153
0
    }
1154
1155
0
  socket->priv->inited = TRUE;
1156
1157
0
  if (socket->priv->construct_error)
1158
0
    {
1159
0
      if (error)
1160
0
  *error = g_error_copy (socket->priv->construct_error);
1161
0
      return FALSE;
1162
0
    }
1163
1164
1165
0
  return TRUE;
1166
0
}
1167
1168
static gboolean
1169
check_datagram_based (GDatagramBased  *self,
1170
                      GError         **error)
1171
0
{
1172
0
  switch (g_socket_get_socket_type (G_SOCKET (self)))
1173
0
    {
1174
0
    case G_SOCKET_TYPE_INVALID:
1175
0
    case G_SOCKET_TYPE_STREAM:
1176
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1177
0
                   _("Cannot use datagram operations on a non-datagram "
1178
0
                     "socket."));
1179
0
      return FALSE;
1180
0
    case G_SOCKET_TYPE_DATAGRAM:
1181
0
    case G_SOCKET_TYPE_SEQPACKET:
1182
      /* Fall through. */
1183
0
      break;
1184
0
    }
1185
1186
  /* Due to us sharing #GSocketSource with the #GSocket implementation, it is
1187
   * pretty tricky to split out #GSocket:timeout so that it does not affect
1188
   * #GDatagramBased operations (but still affects #GSocket operations). It is
1189
   * not worth that effort — just disallow it and require the user to specify
1190
   * timeouts on a per-operation basis. */
1191
0
  if (g_socket_get_timeout (G_SOCKET (self)) != 0)
1192
0
    {
1193
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1194
0
                   _("Cannot use datagram operations on a socket with a "
1195
0
                     "timeout set."));
1196
0
      return FALSE;
1197
0
    }
1198
1199
0
  return TRUE;
1200
0
}
1201
1202
static gint
1203
g_socket_datagram_based_receive_messages (GDatagramBased  *self,
1204
                                          GInputMessage   *messages,
1205
                                          guint            num_messages,
1206
                                          gint             flags,
1207
                                          gint64           timeout_us,
1208
                                          GCancellable    *cancellable,
1209
                                          GError         **error)
1210
0
{
1211
0
  if (!check_datagram_based (self, error))
1212
0
    return FALSE;
1213
1214
0
  return g_socket_receive_messages_with_timeout (G_SOCKET (self), messages,
1215
0
                                                 num_messages, flags, timeout_us,
1216
0
                                                 cancellable, error);
1217
0
}
1218
1219
static gint
1220
g_socket_datagram_based_send_messages (GDatagramBased  *self,
1221
                                       GOutputMessage  *messages,
1222
                                       guint            num_messages,
1223
                                       gint             flags,
1224
                                       gint64           timeout_us,
1225
                                       GCancellable    *cancellable,
1226
                                       GError         **error)
1227
0
{
1228
0
  if (!check_datagram_based (self, error))
1229
0
    return FALSE;
1230
1231
0
  return g_socket_send_messages_with_timeout (G_SOCKET (self), messages,
1232
0
                                              num_messages, flags, timeout_us,
1233
0
                                              cancellable, error);
1234
0
}
1235
1236
static GSource *
1237
g_socket_datagram_based_create_source (GDatagramBased  *self,
1238
                                       GIOCondition     condition,
1239
                                       GCancellable    *cancellable)
1240
0
{
1241
0
  if (!check_datagram_based (self, NULL))
1242
0
    return NULL;
1243
1244
0
  return g_socket_create_source (G_SOCKET (self), condition, cancellable);
1245
0
}
1246
1247
static GIOCondition
1248
g_socket_datagram_based_condition_check (GDatagramBased  *datagram_based,
1249
                                         GIOCondition     condition)
1250
0
{
1251
0
  if (!check_datagram_based (datagram_based, NULL))
1252
0
    return G_IO_ERR;
1253
1254
0
  return g_socket_condition_check (G_SOCKET (datagram_based), condition);
1255
0
}
1256
1257
static gboolean
1258
g_socket_datagram_based_condition_wait (GDatagramBased  *datagram_based,
1259
                                        GIOCondition     condition,
1260
                                        gint64           timeout_us,
1261
                                        GCancellable    *cancellable,
1262
                                        GError         **error)
1263
0
{
1264
0
  if (!check_datagram_based (datagram_based, error))
1265
0
    return FALSE;
1266
1267
0
  return g_socket_condition_timed_wait (G_SOCKET (datagram_based), condition,
1268
0
                                        timeout_us, cancellable, error);
1269
0
}
1270
1271
/**
1272
 * g_socket_new:
1273
 * @family: the socket family to use, e.g. %G_SOCKET_FAMILY_IPV4.
1274
 * @type: the socket type to use.
1275
 * @protocol: the id of the protocol to use, or 0 for default.
1276
 * @error: #GError for error reporting, or %NULL to ignore.
1277
 *
1278
 * Creates a new #GSocket with the defined family, type and protocol.
1279
 * If @protocol is 0 (%G_SOCKET_PROTOCOL_DEFAULT) the default protocol type
1280
 * for the family and type is used.
1281
 *
1282
 * The @protocol is a family and type specific int that specifies what
1283
 * kind of protocol to use. #GSocketProtocol lists several common ones.
1284
 * Many families only support one protocol, and use 0 for this, others
1285
 * support several and using 0 means to use the default protocol for
1286
 * the family and type.
1287
 *
1288
 * The protocol id is passed directly to the operating
1289
 * system, so you can use protocols not listed in #GSocketProtocol if you
1290
 * know the protocol number used for it.
1291
 *
1292
 * Returns: a #GSocket or %NULL on error.
1293
 *     Free the returned object with g_object_unref().
1294
 *
1295
 * Since: 2.22
1296
 */
1297
GSocket *
1298
g_socket_new (GSocketFamily     family,
1299
        GSocketType       type,
1300
        GSocketProtocol   protocol,
1301
        GError          **error)
1302
0
{
1303
0
  return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1304
0
           NULL, error,
1305
0
           "family", family,
1306
0
           "type", type,
1307
0
           "protocol", protocol,
1308
0
           NULL));
1309
0
}
1310
1311
/**
1312
 * g_socket_new_from_fd:
1313
 * @fd: a native socket file descriptor.
1314
 * @error: #GError for error reporting, or %NULL to ignore.
1315
 *
1316
 * Creates a new #GSocket from a native file descriptor
1317
 * or winsock SOCKET handle.
1318
 *
1319
 * This reads all the settings from the file descriptor so that
1320
 * all properties should work. Note that the file descriptor
1321
 * will be set to non-blocking mode, independent on the blocking
1322
 * mode of the #GSocket.
1323
 *
1324
 * On success, the returned #GSocket takes ownership of @fd. On failure, the
1325
 * caller must close @fd themselves.
1326
 *
1327
 * Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
1328
 * descriptor.  Instead, a GError will be set with code %G_IO_ERROR_FAILED
1329
 *
1330
 * Returns: a #GSocket or %NULL on error.
1331
 *     Free the returned object with g_object_unref().
1332
 *
1333
 * Since: 2.22
1334
 */
1335
GSocket *
1336
g_socket_new_from_fd (gint     fd,
1337
          GError **error)
1338
0
{
1339
0
  return G_SOCKET (g_initable_new (G_TYPE_SOCKET,
1340
0
           NULL, error,
1341
0
           "fd", fd,
1342
0
           NULL));
1343
0
}
1344
1345
/**
1346
 * g_socket_set_blocking:
1347
 * @socket: a #GSocket.
1348
 * @blocking: Whether to use blocking I/O or not.
1349
 *
1350
 * Sets the blocking mode of the socket. In blocking mode
1351
 * all operations (which don’t take an explicit blocking parameter) block until
1352
 * they succeed or there is an error. In
1353
 * non-blocking mode all functions return results immediately or
1354
 * with a %G_IO_ERROR_WOULD_BLOCK error.
1355
 *
1356
 * All sockets are created in blocking mode. However, note that the
1357
 * platform level socket is always non-blocking, and blocking mode
1358
 * is a GSocket level feature.
1359
 *
1360
 * Since: 2.22
1361
 */
1362
void
1363
g_socket_set_blocking (GSocket  *socket,
1364
           gboolean  blocking)
1365
0
{
1366
0
  g_return_if_fail (G_IS_SOCKET (socket));
1367
1368
0
  blocking = !!blocking;
1369
1370
0
  if (socket->priv->blocking == blocking)
1371
0
    return;
1372
1373
0
  socket->priv->blocking = blocking;
1374
0
  g_object_notify (G_OBJECT (socket), "blocking");
1375
0
}
1376
1377
/**
1378
 * g_socket_get_blocking:
1379
 * @socket: a #GSocket.
1380
 *
1381
 * Gets the blocking mode of the socket. For details on blocking I/O,
1382
 * see g_socket_set_blocking().
1383
 *
1384
 * Returns: %TRUE if blocking I/O is used, %FALSE otherwise.
1385
 *
1386
 * Since: 2.22
1387
 */
1388
gboolean
1389
g_socket_get_blocking (GSocket *socket)
1390
0
{
1391
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1392
1393
0
  return socket->priv->blocking;
1394
0
}
1395
1396
/**
1397
 * g_socket_set_keepalive:
1398
 * @socket: a #GSocket.
1399
 * @keepalive: Value for the keepalive flag
1400
 *
1401
 * Sets or unsets the %SO_KEEPALIVE flag on the underlying socket. When
1402
 * this flag is set on a socket, the system will attempt to verify that the
1403
 * remote socket endpoint is still present if a sufficiently long period of
1404
 * time passes with no data being exchanged. If the system is unable to
1405
 * verify the presence of the remote endpoint, it will automatically close
1406
 * the connection.
1407
 *
1408
 * This option is only functional on certain kinds of sockets. (Notably,
1409
 * %G_SOCKET_PROTOCOL_TCP sockets.)
1410
 *
1411
 * The exact time between pings is system- and protocol-dependent, but will
1412
 * normally be at least two hours. Most commonly, you would set this flag
1413
 * on a server socket if you want to allow clients to remain idle for long
1414
 * periods of time, but also want to ensure that connections are eventually
1415
 * garbage-collected if clients crash or become unreachable.
1416
 *
1417
 * Since: 2.22
1418
 */
1419
void
1420
g_socket_set_keepalive (GSocket  *socket,
1421
      gboolean  keepalive)
1422
0
{
1423
0
  GError *error = NULL;
1424
1425
0
  g_return_if_fail (G_IS_SOCKET (socket));
1426
1427
0
  keepalive = !!keepalive;
1428
0
  if (socket->priv->keepalive == keepalive)
1429
0
    return;
1430
1431
0
  if (!g_socket_set_option (socket, SOL_SOCKET, SO_KEEPALIVE,
1432
0
          keepalive, &error))
1433
0
    {
1434
0
      g_warning ("error setting keepalive: %s", error->message);
1435
0
      g_error_free (error);
1436
0
      return;
1437
0
    }
1438
1439
0
  socket->priv->keepalive = keepalive;
1440
0
  g_object_notify (G_OBJECT (socket), "keepalive");
1441
0
}
1442
1443
/**
1444
 * g_socket_get_keepalive:
1445
 * @socket: a #GSocket.
1446
 *
1447
 * Gets the keepalive mode of the socket. For details on this,
1448
 * see g_socket_set_keepalive().
1449
 *
1450
 * Returns: %TRUE if keepalive is active, %FALSE otherwise.
1451
 *
1452
 * Since: 2.22
1453
 */
1454
gboolean
1455
g_socket_get_keepalive (GSocket *socket)
1456
0
{
1457
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1458
1459
0
  return socket->priv->keepalive;
1460
0
}
1461
1462
/**
1463
 * g_socket_get_listen_backlog:
1464
 * @socket: a #GSocket.
1465
 *
1466
 * Gets the listen backlog setting of the socket. For details on this,
1467
 * see g_socket_set_listen_backlog().
1468
 *
1469
 * Returns: the maximum number of pending connections.
1470
 *
1471
 * Since: 2.22
1472
 */
1473
gint
1474
g_socket_get_listen_backlog  (GSocket *socket)
1475
0
{
1476
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1477
1478
0
  return socket->priv->listen_backlog;
1479
0
}
1480
1481
/**
1482
 * g_socket_set_listen_backlog:
1483
 * @socket: a #GSocket.
1484
 * @backlog: the maximum number of pending connections.
1485
 *
1486
 * Sets the maximum number of outstanding connections allowed
1487
 * when listening on this socket. If more clients than this are
1488
 * connecting to the socket and the application is not handling them
1489
 * on time then the new connections will be refused.
1490
 *
1491
 * Note that this must be called before g_socket_listen() and has no
1492
 * effect if called after that.
1493
 *
1494
 * Since: 2.22
1495
 */
1496
void
1497
g_socket_set_listen_backlog (GSocket *socket,
1498
           gint     backlog)
1499
0
{
1500
0
  g_return_if_fail (G_IS_SOCKET (socket));
1501
0
  g_return_if_fail (!socket->priv->listening);
1502
1503
0
  if (backlog != socket->priv->listen_backlog)
1504
0
    {
1505
0
      socket->priv->listen_backlog = backlog;
1506
0
      g_object_notify (G_OBJECT (socket), "listen-backlog");
1507
0
    }
1508
0
}
1509
1510
/**
1511
 * g_socket_get_timeout:
1512
 * @socket: a #GSocket.
1513
 *
1514
 * Gets the timeout setting of the socket. For details on this, see
1515
 * g_socket_set_timeout().
1516
 *
1517
 * Returns: the timeout in seconds
1518
 *
1519
 * Since: 2.26
1520
 */
1521
guint
1522
g_socket_get_timeout (GSocket *socket)
1523
0
{
1524
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1525
1526
0
  return socket->priv->timeout;
1527
0
}
1528
1529
/**
1530
 * g_socket_set_timeout:
1531
 * @socket: a #GSocket.
1532
 * @timeout: the timeout for @socket, in seconds, or 0 for none
1533
 *
1534
 * Sets the time in seconds after which I/O operations on @socket will
1535
 * time out if they have not yet completed.
1536
 *
1537
 * On a blocking socket, this means that any blocking #GSocket
1538
 * operation will time out after @timeout seconds of inactivity,
1539
 * returning %G_IO_ERROR_TIMED_OUT.
1540
 *
1541
 * On a non-blocking socket, calls to g_socket_condition_wait() will
1542
 * also fail with %G_IO_ERROR_TIMED_OUT after the given time. Sources
1543
 * created with g_socket_create_source() will trigger after
1544
 * @timeout seconds of inactivity, with the requested condition
1545
 * set, at which point calling g_socket_receive(), g_socket_send(),
1546
 * g_socket_check_connect_result(), etc, will fail with
1547
 * %G_IO_ERROR_TIMED_OUT.
1548
 *
1549
 * If @timeout is 0 (the default), operations will never time out
1550
 * on their own.
1551
 *
1552
 * Note that if an I/O operation is interrupted by a signal, this may
1553
 * cause the timeout to be reset.
1554
 *
1555
 * Since: 2.26
1556
 */
1557
void
1558
g_socket_set_timeout (GSocket *socket,
1559
          guint    timeout)
1560
0
{
1561
0
  g_return_if_fail (G_IS_SOCKET (socket));
1562
1563
0
  if (timeout != socket->priv->timeout)
1564
0
    {
1565
0
      socket->priv->timeout = timeout;
1566
0
      g_object_notify (G_OBJECT (socket), "timeout");
1567
0
    }
1568
0
}
1569
1570
/**
1571
 * g_socket_get_ttl:
1572
 * @socket: a #GSocket.
1573
 *
1574
 * Gets the unicast time-to-live setting on @socket; see
1575
 * g_socket_set_ttl() for more details.
1576
 *
1577
 * Returns: the time-to-live setting on @socket
1578
 *
1579
 * Since: 2.32
1580
 */
1581
guint
1582
g_socket_get_ttl (GSocket *socket)
1583
0
{
1584
0
  GError *error = NULL;
1585
0
  gint value;
1586
1587
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1588
1589
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1590
0
    {
1591
0
      g_socket_get_option (socket, IPPROTO_IP, IP_TTL,
1592
0
         &value, &error);
1593
0
    }
1594
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1595
0
    {
1596
0
      g_socket_get_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1597
0
         &value, &error);
1598
0
    }
1599
0
  else
1600
0
    g_return_val_if_reached (0);
1601
1602
0
  if (error)
1603
0
    {
1604
0
      g_warning ("error getting unicast ttl: %s", error->message);
1605
0
      g_error_free (error);
1606
0
      return 0;
1607
0
    }
1608
1609
0
  return value;
1610
0
}
1611
1612
/**
1613
 * g_socket_set_ttl:
1614
 * @socket: a #GSocket.
1615
 * @ttl: the time-to-live value for all unicast packets on @socket
1616
 *
1617
 * Sets the time-to-live for outgoing unicast packets on @socket.
1618
 * By default the platform-specific default value is used.
1619
 *
1620
 * Since: 2.32
1621
 */
1622
void
1623
g_socket_set_ttl (GSocket  *socket,
1624
                  guint     ttl)
1625
0
{
1626
0
  GError *error = NULL;
1627
1628
0
  g_return_if_fail (G_IS_SOCKET (socket));
1629
1630
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1631
0
    {
1632
0
      g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1633
0
         ttl, &error);
1634
0
    }
1635
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1636
0
    {
1637
0
      g_socket_set_option (socket, IPPROTO_IP, IP_TTL,
1638
0
         ttl, NULL);
1639
0
      g_socket_set_option (socket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
1640
0
         ttl, &error);
1641
0
    }
1642
0
  else
1643
0
    g_return_if_reached ();
1644
1645
0
  if (error)
1646
0
    {
1647
0
      g_warning ("error setting unicast ttl: %s", error->message);
1648
0
      g_error_free (error);
1649
0
      return;
1650
0
    }
1651
1652
0
  g_object_notify (G_OBJECT (socket), "ttl");
1653
0
}
1654
1655
/**
1656
 * g_socket_get_broadcast:
1657
 * @socket: a #GSocket.
1658
 *
1659
 * Gets the broadcast setting on @socket; if %TRUE,
1660
 * it is possible to send packets to broadcast
1661
 * addresses.
1662
 *
1663
 * Returns: the broadcast setting on @socket
1664
 *
1665
 * Since: 2.32
1666
 */
1667
gboolean
1668
g_socket_get_broadcast (GSocket *socket)
1669
0
{
1670
0
  GError *error = NULL;
1671
0
  gint value;
1672
1673
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1674
1675
0
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_BROADCAST,
1676
0
          &value, &error))
1677
0
    {
1678
0
      g_warning ("error getting broadcast: %s", error->message);
1679
0
      g_error_free (error);
1680
0
      return FALSE;
1681
0
    }
1682
1683
0
  return !!value;
1684
0
}
1685
1686
/**
1687
 * g_socket_set_broadcast:
1688
 * @socket: a #GSocket.
1689
 * @broadcast: whether @socket should allow sending to broadcast
1690
 *     addresses
1691
 *
1692
 * Sets whether @socket should allow sending to broadcast addresses.
1693
 * This is %FALSE by default.
1694
 *
1695
 * Since: 2.32
1696
 */
1697
void
1698
g_socket_set_broadcast (GSocket    *socket,
1699
                        gboolean    broadcast)
1700
0
{
1701
0
  GError *error = NULL;
1702
1703
0
  g_return_if_fail (G_IS_SOCKET (socket));
1704
1705
0
  broadcast = !!broadcast;
1706
1707
0
  if (!g_socket_set_option (socket, SOL_SOCKET, SO_BROADCAST,
1708
0
          broadcast, &error))
1709
0
    {
1710
0
      g_warning ("error setting broadcast: %s", error->message);
1711
0
      g_error_free (error);
1712
0
      return;
1713
0
    }
1714
1715
0
  g_object_notify (G_OBJECT (socket), "broadcast");
1716
0
}
1717
1718
/**
1719
 * g_socket_get_multicast_loopback:
1720
 * @socket: a #GSocket.
1721
 *
1722
 * Gets the multicast loopback setting on @socket; if %TRUE (the
1723
 * default), outgoing multicast packets will be looped back to
1724
 * multicast listeners on the same host.
1725
 *
1726
 * Returns: the multicast loopback setting on @socket
1727
 *
1728
 * Since: 2.32
1729
 */
1730
gboolean
1731
g_socket_get_multicast_loopback (GSocket *socket)
1732
0
{
1733
0
  GError *error = NULL;
1734
0
  gint value;
1735
1736
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
1737
1738
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1739
0
    {
1740
0
      g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1741
0
         &value, &error);
1742
0
    }
1743
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1744
0
    {
1745
0
      g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1746
0
         &value, &error);
1747
0
    }
1748
0
  else
1749
0
    g_return_val_if_reached (FALSE);
1750
1751
0
  if (error)
1752
0
    {
1753
0
      g_warning ("error getting multicast loopback: %s", error->message);
1754
0
      g_error_free (error);
1755
0
      return FALSE;
1756
0
    }
1757
1758
0
  return !!value;
1759
0
}
1760
1761
/**
1762
 * g_socket_set_multicast_loopback:
1763
 * @socket: a #GSocket.
1764
 * @loopback: whether @socket should receive messages sent to its
1765
 *   multicast groups from the local host
1766
 *
1767
 * Sets whether outgoing multicast packets will be received by sockets
1768
 * listening on that multicast address on the same host. This is %TRUE
1769
 * by default.
1770
 *
1771
 * Since: 2.32
1772
 */
1773
void
1774
g_socket_set_multicast_loopback (GSocket    *socket,
1775
         gboolean    loopback)
1776
0
{
1777
0
  GError *error = NULL;
1778
1779
0
  g_return_if_fail (G_IS_SOCKET (socket));
1780
1781
0
  loopback = !!loopback;
1782
1783
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1784
0
    {
1785
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1786
0
         loopback, &error);
1787
0
    }
1788
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1789
0
    {
1790
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_LOOP,
1791
0
         loopback, NULL);
1792
0
      g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
1793
0
         loopback, &error);
1794
0
    }
1795
0
  else
1796
0
    g_return_if_reached ();
1797
1798
0
  if (error)
1799
0
    {
1800
0
      g_warning ("error setting multicast loopback: %s", error->message);
1801
0
      g_error_free (error);
1802
0
      return;
1803
0
    }
1804
1805
0
  g_object_notify (G_OBJECT (socket), "multicast-loopback");
1806
0
}
1807
1808
/**
1809
 * g_socket_get_multicast_ttl:
1810
 * @socket: a #GSocket.
1811
 *
1812
 * Gets the multicast time-to-live setting on @socket; see
1813
 * g_socket_set_multicast_ttl() for more details.
1814
 *
1815
 * Returns: the multicast time-to-live setting on @socket
1816
 *
1817
 * Since: 2.32
1818
 */
1819
guint
1820
g_socket_get_multicast_ttl (GSocket *socket)
1821
0
{
1822
0
  GError *error = NULL;
1823
0
  gint value;
1824
1825
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
1826
1827
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1828
0
    {
1829
0
      g_socket_get_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1830
0
         &value, &error);
1831
0
    }
1832
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1833
0
    {
1834
0
      g_socket_get_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1835
0
         &value, &error);
1836
0
    }
1837
0
  else
1838
0
    g_return_val_if_reached (FALSE);
1839
1840
0
  if (error)
1841
0
    {
1842
0
      g_warning ("error getting multicast ttl: %s", error->message);
1843
0
      g_error_free (error);
1844
0
      return FALSE;
1845
0
    }
1846
1847
0
  return value;
1848
0
}
1849
1850
/**
1851
 * g_socket_set_multicast_ttl:
1852
 * @socket: a #GSocket.
1853
 * @ttl: the time-to-live value for all multicast datagrams on @socket
1854
 *
1855
 * Sets the time-to-live for outgoing multicast datagrams on @socket.
1856
 * By default, this is 1, meaning that multicast packets will not leave
1857
 * the local network.
1858
 *
1859
 * Since: 2.32
1860
 */
1861
void
1862
g_socket_set_multicast_ttl (GSocket  *socket,
1863
                            guint     ttl)
1864
0
{
1865
0
  GError *error = NULL;
1866
1867
0
  g_return_if_fail (G_IS_SOCKET (socket));
1868
1869
0
  if (socket->priv->family == G_SOCKET_FAMILY_IPV4)
1870
0
    {
1871
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1872
0
         ttl, &error);
1873
0
    }
1874
0
  else if (socket->priv->family == G_SOCKET_FAMILY_IPV6)
1875
0
    {
1876
0
      g_socket_set_option (socket, IPPROTO_IP, IP_MULTICAST_TTL,
1877
0
         ttl, NULL);
1878
0
      g_socket_set_option (socket, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
1879
0
         ttl, &error);
1880
0
    }
1881
0
  else
1882
0
    g_return_if_reached ();
1883
1884
0
  if (error)
1885
0
    {
1886
0
      g_warning ("error setting multicast ttl: %s", error->message);
1887
0
      g_error_free (error);
1888
0
      return;
1889
0
    }
1890
1891
0
  g_object_notify (G_OBJECT (socket), "multicast-ttl");
1892
0
}
1893
1894
/**
1895
 * g_socket_get_family:
1896
 * @socket: a #GSocket.
1897
 *
1898
 * Gets the socket family of the socket.
1899
 *
1900
 * Returns: a #GSocketFamily
1901
 *
1902
 * Since: 2.22
1903
 */
1904
GSocketFamily
1905
g_socket_get_family (GSocket *socket)
1906
0
{
1907
0
  g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_FAMILY_INVALID);
1908
1909
0
  return socket->priv->family;
1910
0
}
1911
1912
/**
1913
 * g_socket_get_socket_type:
1914
 * @socket: a #GSocket.
1915
 *
1916
 * Gets the socket type of the socket.
1917
 *
1918
 * Returns: a #GSocketType
1919
 *
1920
 * Since: 2.22
1921
 */
1922
GSocketType
1923
g_socket_get_socket_type (GSocket *socket)
1924
0
{
1925
0
  g_return_val_if_fail (G_IS_SOCKET (socket), G_SOCKET_TYPE_INVALID);
1926
1927
0
  return socket->priv->type;
1928
0
}
1929
1930
/**
1931
 * g_socket_get_protocol:
1932
 * @socket: a #GSocket.
1933
 *
1934
 * Gets the socket protocol id the socket was created with.
1935
 * In case the protocol is unknown, -1 is returned.
1936
 *
1937
 * Returns: a protocol id, or -1 if unknown
1938
 *
1939
 * Since: 2.22
1940
 */
1941
GSocketProtocol
1942
g_socket_get_protocol (GSocket *socket)
1943
0
{
1944
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1945
1946
0
  return socket->priv->protocol;
1947
0
}
1948
1949
/**
1950
 * g_socket_get_fd:
1951
 * @socket: a #GSocket.
1952
 *
1953
 * Returns the underlying OS socket object. On unix this
1954
 * is a socket file descriptor, and on Windows this is
1955
 * a Winsock2 SOCKET handle. This may be useful for
1956
 * doing platform specific or otherwise unusual operations
1957
 * on the socket.
1958
 *
1959
 * Returns: the file descriptor of the socket.
1960
 *
1961
 * Since: 2.22
1962
 */
1963
int
1964
g_socket_get_fd (GSocket *socket)
1965
0
{
1966
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
1967
1968
0
  return socket->priv->fd;
1969
0
}
1970
1971
/**
1972
 * g_socket_get_local_address:
1973
 * @socket: a #GSocket.
1974
 * @error: #GError for error reporting, or %NULL to ignore.
1975
 *
1976
 * Try to get the local address of a bound socket. This is only
1977
 * useful if the socket has been bound to a local address,
1978
 * either explicitly or implicitly when connecting.
1979
 *
1980
 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
1981
 *     Free the returned object with g_object_unref().
1982
 *
1983
 * Since: 2.22
1984
 */
1985
GSocketAddress *
1986
g_socket_get_local_address (GSocket  *socket,
1987
          GError  **error)
1988
0
{
1989
0
  union {
1990
0
    struct sockaddr_storage storage;
1991
0
    struct sockaddr sa;
1992
0
  } buffer;
1993
0
  guint len = sizeof (buffer);
1994
1995
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
1996
1997
0
  if (getsockname (socket->priv->fd, &buffer.sa, &len) < 0)
1998
0
    {
1999
0
      int errsv = get_socket_errno ();
2000
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2001
0
       _("could not get local address: %s"), socket_strerror (errsv));
2002
0
      return NULL;
2003
0
    }
2004
2005
0
  return g_socket_address_new_from_native (&buffer.storage, len);
2006
0
}
2007
2008
/**
2009
 * g_socket_get_remote_address:
2010
 * @socket: a #GSocket.
2011
 * @error: #GError for error reporting, or %NULL to ignore.
2012
 *
2013
 * Try to get the remote address of a connected socket. This is only
2014
 * useful for connection oriented sockets that have been connected.
2015
 *
2016
 * Returns: (transfer full): a #GSocketAddress or %NULL on error.
2017
 *     Free the returned object with g_object_unref().
2018
 *
2019
 * Since: 2.22
2020
 */
2021
GSocketAddress *
2022
g_socket_get_remote_address (GSocket  *socket,
2023
           GError  **error)
2024
0
{
2025
0
  union {
2026
0
    struct sockaddr_storage storage;
2027
0
    struct sockaddr sa;
2028
0
  } buffer;
2029
0
  guint len = sizeof (buffer);
2030
2031
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2032
2033
0
  if (socket->priv->connect_pending)
2034
0
    {
2035
0
      if (!g_socket_check_connect_result (socket, error))
2036
0
        return NULL;
2037
0
      else
2038
0
        socket->priv->connect_pending = FALSE;
2039
0
    }
2040
2041
0
  if (!socket->priv->remote_address)
2042
0
    {
2043
0
      if (getpeername (socket->priv->fd, &buffer.sa, &len) < 0)
2044
0
  {
2045
0
    int errsv = get_socket_errno ();
2046
0
    g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2047
0
           _("could not get remote address: %s"), socket_strerror (errsv));
2048
0
    return NULL;
2049
0
  }
2050
2051
0
      socket->priv->remote_address = g_socket_address_new_from_native (&buffer.storage, len);
2052
0
    }
2053
2054
0
  return g_object_ref (socket->priv->remote_address);
2055
0
}
2056
2057
/**
2058
 * g_socket_is_connected:
2059
 * @socket: a #GSocket.
2060
 *
2061
 * Check whether the socket is connected. This is only useful for
2062
 * connection-oriented sockets.
2063
 *
2064
 * If using g_socket_shutdown(), this function will return %TRUE until the
2065
 * socket has been shut down for reading and writing. If you do a non-blocking
2066
 * connect, this function will not return %TRUE until after you call
2067
 * g_socket_check_connect_result().
2068
 *
2069
 * Returns: %TRUE if socket is connected, %FALSE otherwise.
2070
 *
2071
 * Since: 2.22
2072
 */
2073
gboolean
2074
g_socket_is_connected (GSocket *socket)
2075
0
{
2076
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2077
2078
0
  return (socket->priv->connected_read || socket->priv->connected_write);
2079
0
}
2080
2081
/**
2082
 * g_socket_listen:
2083
 * @socket: a #GSocket.
2084
 * @error: #GError for error reporting, or %NULL to ignore.
2085
 *
2086
 * Marks the socket as a server socket, i.e. a socket that is used
2087
 * to accept incoming requests using g_socket_accept().
2088
 *
2089
 * Before calling this the socket must be bound to a local address using
2090
 * g_socket_bind().
2091
 *
2092
 * To set the maximum amount of outstanding clients, use
2093
 * g_socket_set_listen_backlog().
2094
 *
2095
 * Returns: %TRUE on success, %FALSE on error.
2096
 *
2097
 * Since: 2.22
2098
 */
2099
gboolean
2100
g_socket_listen (GSocket  *socket,
2101
     GError  **error)
2102
0
{
2103
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2104
2105
0
  if (!check_socket (socket, error))
2106
0
    return FALSE;
2107
2108
0
  if (listen (socket->priv->fd, socket->priv->listen_backlog) < 0)
2109
0
    {
2110
0
      int errsv = get_socket_errno ();
2111
2112
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2113
0
       _("could not listen: %s"), socket_strerror (errsv));
2114
0
      return FALSE;
2115
0
    }
2116
2117
0
  socket->priv->listening = TRUE;
2118
2119
0
  return TRUE;
2120
0
}
2121
2122
/**
2123
 * g_socket_bind:
2124
 * @socket: a #GSocket.
2125
 * @address: a #GSocketAddress specifying the local address.
2126
 * @allow_reuse: whether to allow reusing this address
2127
 * @error: #GError for error reporting, or %NULL to ignore.
2128
 *
2129
 * When a socket is created it is attached to an address family, but it
2130
 * doesn't have an address in this family. g_socket_bind() assigns the
2131
 * address (sometimes called name) of the socket.
2132
 *
2133
 * It is generally required to bind to a local address before you can
2134
 * receive connections. (See g_socket_listen() and g_socket_accept() ).
2135
 * In certain situations, you may also want to bind a socket that will be
2136
 * used to initiate connections, though this is not normally required.
2137
 *
2138
 * If @socket is a TCP socket, then @allow_reuse controls the setting
2139
 * of the `SO_REUSEADDR` socket option; normally it should be %TRUE for
2140
 * server sockets (sockets that you will eventually call
2141
 * g_socket_accept() on), and %FALSE for client sockets. (Failing to
2142
 * set this flag on a server socket may cause g_socket_bind() to return
2143
 * %G_IO_ERROR_ADDRESS_IN_USE if the server program is stopped and then
2144
 * immediately restarted.)
2145
 *
2146
 * If @socket is a UDP socket, then @allow_reuse determines whether or
2147
 * not other UDP sockets can be bound to the same address at the same
2148
 * time. In particular, you can have several UDP sockets bound to the
2149
 * same address, and they will all receive all of the multicast and
2150
 * broadcast packets sent to that address. (The behavior of unicast
2151
 * UDP packets to an address with multiple listeners is not defined.)
2152
 *
2153
 * Returns: %TRUE on success, %FALSE on error.
2154
 *
2155
 * Since: 2.22
2156
 */
2157
gboolean
2158
g_socket_bind (GSocket         *socket,
2159
         GSocketAddress  *address,
2160
         gboolean         reuse_address,
2161
         GError         **error)
2162
0
{
2163
0
  union {
2164
0
    struct sockaddr_storage storage;
2165
0
    struct sockaddr sa;
2166
0
  } addr;
2167
0
  gboolean so_reuseaddr;
2168
0
#ifdef SO_REUSEPORT
2169
0
  gboolean so_reuseport;
2170
0
#endif
2171
2172
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2173
2174
0
  if (!check_socket (socket, error))
2175
0
    return FALSE;
2176
2177
0
  if (!g_socket_address_to_native (address, &addr.storage, sizeof addr, error))
2178
0
    return FALSE;
2179
2180
  /* On Windows, SO_REUSEADDR has the semantics we want for UDP
2181
   * sockets, but has nasty side effects we don't want for TCP
2182
   * sockets.
2183
   *
2184
   * On other platforms, we set SO_REUSEPORT, if it exists, for
2185
   * UDP sockets, and SO_REUSEADDR for all sockets, hoping that
2186
   * if SO_REUSEPORT doesn't exist, then SO_REUSEADDR will have
2187
   * the desired semantics on UDP (as it does on Linux, although
2188
   * Linux has SO_REUSEPORT too as of 3.9).
2189
   */
2190
2191
#ifdef G_OS_WIN32
2192
  so_reuseaddr = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2193
#else
2194
0
  so_reuseaddr = !!reuse_address;
2195
0
#endif
2196
2197
0
#ifdef SO_REUSEPORT
2198
0
  so_reuseport = reuse_address && (socket->priv->type == G_SOCKET_TYPE_DATAGRAM);
2199
0
#endif
2200
2201
  /* Ignore errors here, the only likely error is "not supported", and
2202
   * this is a "best effort" thing mainly.
2203
   */
2204
0
  g_socket_set_option (socket, SOL_SOCKET, SO_REUSEADDR, so_reuseaddr, NULL);
2205
0
#ifdef SO_REUSEPORT
2206
0
  g_socket_set_option (socket, SOL_SOCKET, SO_REUSEPORT, so_reuseport, NULL);
2207
0
#endif
2208
2209
0
  if (bind (socket->priv->fd, &addr.sa,
2210
0
      g_socket_address_get_native_size (address)) < 0)
2211
0
    {
2212
0
      int errsv = get_socket_errno ();
2213
0
      gchar *address_string = address_to_string (address);
2214
2215
0
      g_set_error (error,
2216
0
       G_IO_ERROR, socket_io_error_from_errno (errsv),
2217
0
       _("Error binding to address %s: %s"),
2218
0
       address_string, socket_strerror (errsv));
2219
0
      g_free (address_string);
2220
0
      return FALSE;
2221
0
    }
2222
2223
0
  return TRUE;
2224
0
}
2225
2226
#ifdef G_OS_WIN32
2227
static gulong
2228
g_socket_w32_get_adapter_ipv4_addr (const gchar *name_or_ip)
2229
{
2230
  ULONG bufsize = 15000; /* MS-recommended initial bufsize */
2231
  DWORD ret = ERROR_BUFFER_OVERFLOW;
2232
  unsigned int malloc_iterations = 0;
2233
  PIP_ADAPTER_ADDRESSES addr_buf = NULL, eth_adapter;
2234
  wchar_t *wchar_name_or_ip = NULL;
2235
  gulong ip_result = 0;
2236
  NET_IFINDEX if_index;
2237
2238
  /*
2239
   * For Windows OS only - return adapter IPv4 address in network byte order.
2240
   *
2241
   * Input string can be either friendly name of adapter, IP address of adapter,
2242
   * indextoname, or fullname of adapter.
2243
   * Example:
2244
   *    192.168.1.109   ===> IP address given directly,
2245
   *                         convert directly with inet_addr() function
2246
   *    Wi-Fi           ===> Adapter friendly name "Wi-Fi",
2247
   *                         scan with GetAdapterAddresses and adapter->FriendlyName
2248
   *    ethernet_32774  ===> Adapter name as returned by if_indextoname
2249
   *    {33E8F5CD-BAEA-4214-BE13-B79AB8080CAB} ===> Adaptername,
2250
   *                         as returned in GetAdapterAddresses and adapter->AdapterName
2251
   */
2252
2253
  /* Step 1: Check if string is an IP address: */
2254
  if (inet_pton (AF_INET, name_or_ip, &ip_result) == 1)
2255
    return ip_result;  /* Success, IP address string was given directly */
2256
2257
  /*
2258
   *  Step 2: Check if name represents a valid Interface index (e.g. ethernet_75521)
2259
   *  function if_nametoindex will return >=1 if a valid index, or 0=no match
2260
   *  valid index will be used later in GetAdaptersAddress loop for lookup of adapter IP address
2261
   */
2262
  if_index = if_nametoindex (name_or_ip);
2263
2264
  /* Step 3: Prepare wchar string for friendly name comparison */
2265
  if (if_index == 0)
2266
    {
2267
      size_t if_name_len = strlen (name_or_ip);
2268
      if (if_name_len >= MAX_ADAPTER_NAME_LENGTH + 4)
2269
        return INADDR_NONE;
2270
      /* Name-check only needed if index=0... */
2271
      wchar_name_or_ip = (wchar_t *) g_try_malloc ((if_name_len + 1) * sizeof(wchar_t));
2272
      if (wchar_name_or_ip)
2273
        mbstowcs (wchar_name_or_ip, name_or_ip, if_name_len + 1);
2274
      /* NOTE: Even if malloc fails here, some comparisons can still be done later... so no exit here! */
2275
    }
2276
2277
  /*
2278
   *  Step 4: Allocate memory and get adapter addresses.
2279
   *  Buffer allocation loop recommended by MS, since size can be dynamic
2280
   *  https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getadaptersaddresses
2281
   */
2282
  #define MAX_ALLOC_ITERATIONS 3
2283
  do
2284
    {
2285
      malloc_iterations++;
2286
      addr_buf = (PIP_ADAPTER_ADDRESSES) g_try_realloc (addr_buf, bufsize);
2287
      if (addr_buf)
2288
        ret = GetAdaptersAddresses (AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, addr_buf, &bufsize);
2289
    }
2290
  while (addr_buf &&
2291
           ret == ERROR_BUFFER_OVERFLOW &&
2292
           malloc_iterations < MAX_ALLOC_ITERATIONS);
2293
  #undef MAX_ALLOC_ITERATIONS
2294
2295
  if (addr_buf == 0 || ret != NO_ERROR)
2296
    {
2297
      g_free (addr_buf);
2298
      g_free (wchar_name_or_ip);
2299
      return INADDR_NONE;
2300
    }
2301
2302
  /* Step 5: Loop through adapters and check match for index or name */
2303
  for (eth_adapter = addr_buf; eth_adapter != NULL; eth_adapter = eth_adapter->Next)
2304
    {
2305
      /* Check if match for interface index/name: */
2306
      gboolean any_match = (if_index > 0) && (eth_adapter->IfIndex == if_index);
2307
2308
      /* Check if match for friendly name - but only if NO if_index! */
2309
      if (!any_match && if_index == 0 && eth_adapter->FriendlyName &&
2310
          eth_adapter->FriendlyName[0] != 0 && wchar_name_or_ip != NULL)
2311
        any_match = (_wcsicmp (eth_adapter->FriendlyName, wchar_name_or_ip) == 0);
2312
2313
      /* Check if match for adapter low level name - but only if NO if_index: */
2314
      if (!any_match && if_index == 0 && eth_adapter->AdapterName &&
2315
          eth_adapter->AdapterName[0] != 0)
2316
        any_match = (stricmp (eth_adapter->AdapterName, name_or_ip) == 0);
2317
2318
      if (any_match)
2319
        {
2320
          /* We have match for this adapter, lets get its local unicast IP address! */
2321
          PIP_ADAPTER_UNICAST_ADDRESS uni_addr;
2322
          for (uni_addr = eth_adapter->FirstUnicastAddress;
2323
              uni_addr != NULL; uni_addr = uni_addr->Next)
2324
            {
2325
              if (uni_addr->Address.lpSockaddr->sa_family == AF_INET)
2326
                {
2327
                  ip_result = ((PSOCKADDR_IN) uni_addr->Address.lpSockaddr)->sin_addr.S_un.S_addr;
2328
                  break; /* finished, exit unicast addr loop */
2329
                }
2330
            }
2331
        }
2332
    }
2333
2334
  g_free (addr_buf);
2335
  g_free (wchar_name_or_ip);
2336
2337
  return ip_result;
2338
}
2339
#endif
2340
2341
static gboolean
2342
g_socket_multicast_group_operation (GSocket       *socket,
2343
            GInetAddress  *group,
2344
                                    gboolean       source_specific,
2345
                                    const gchar   *iface,
2346
            gboolean       join_group,
2347
            GError       **error)
2348
0
{
2349
0
  const guint8 *native_addr;
2350
0
  gint optname, result;
2351
2352
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2353
0
  g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2354
0
  g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2355
2356
0
  if (!check_socket (socket, error))
2357
0
    return FALSE;
2358
2359
0
  native_addr = g_inet_address_to_bytes (group);
2360
0
  if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV4)
2361
0
    {
2362
0
#ifdef HAVE_IP_MREQN
2363
0
      struct ip_mreqn mc_req;
2364
#else
2365
      struct ip_mreq mc_req;
2366
#endif
2367
2368
0
      memset (&mc_req, 0, sizeof (mc_req));
2369
0
      memcpy (&mc_req.imr_multiaddr, native_addr, sizeof (struct in_addr));
2370
2371
0
#ifdef HAVE_IP_MREQN
2372
0
      if (iface)
2373
0
        mc_req.imr_ifindex = if_nametoindex (iface);
2374
0
      else
2375
0
        mc_req.imr_ifindex = 0;  /* Pick any.  */
2376
#elif defined(G_OS_WIN32)
2377
      if (iface)
2378
        mc_req.imr_interface.s_addr = g_socket_w32_get_adapter_ipv4_addr (iface);
2379
      else
2380
        mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2381
#else
2382
      mc_req.imr_interface.s_addr = g_htonl (INADDR_ANY);
2383
#endif
2384
2385
0
      if (source_specific)
2386
0
  {
2387
0
#ifdef IP_ADD_SOURCE_MEMBERSHIP
2388
0
    optname = join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2389
#else
2390
    g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2391
           join_group ?
2392
           _("Error joining multicast group: %s") :
2393
           _("Error leaving multicast group: %s"),
2394
           _("No support for source-specific multicast"));
2395
    return FALSE;
2396
#endif
2397
0
  }
2398
0
      else
2399
0
        optname = join_group ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
2400
0
      result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2401
0
         &mc_req, sizeof (mc_req));
2402
0
    }
2403
0
  else if (g_inet_address_get_family (group) == G_SOCKET_FAMILY_IPV6)
2404
0
    {
2405
0
      struct ipv6_mreq mc_req_ipv6;
2406
2407
0
      memset (&mc_req_ipv6, 0, sizeof (mc_req_ipv6));
2408
0
      memcpy (&mc_req_ipv6.ipv6mr_multiaddr, native_addr, sizeof (struct in6_addr));
2409
0
#ifdef HAVE_IF_NAMETOINDEX
2410
0
      if (iface)
2411
0
        mc_req_ipv6.ipv6mr_interface = if_nametoindex (iface);
2412
0
      else
2413
0
#endif
2414
0
        mc_req_ipv6.ipv6mr_interface = 0;
2415
2416
0
      optname = join_group ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
2417
0
      result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2418
0
         &mc_req_ipv6, sizeof (mc_req_ipv6));
2419
0
    }
2420
0
  else
2421
0
    g_return_val_if_reached (FALSE);
2422
2423
0
  if (result < 0)
2424
0
    {
2425
0
      int errsv = get_socket_errno ();
2426
2427
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2428
0
       join_group ?
2429
0
       _("Error joining multicast group: %s") :
2430
0
       _("Error leaving multicast group: %s"),
2431
0
       socket_strerror (errsv));
2432
0
      return FALSE;
2433
0
    }
2434
2435
0
  return TRUE;
2436
0
}
2437
2438
/**
2439
 * g_socket_join_multicast_group:
2440
 * @socket: a #GSocket.
2441
 * @group: a #GInetAddress specifying the group address to join.
2442
 * @iface: (nullable): Name of the interface to use, or %NULL
2443
 * @source_specific: %TRUE if source-specific multicast should be used
2444
 * @error: #GError for error reporting, or %NULL to ignore.
2445
 *
2446
 * Registers @socket to receive multicast messages sent to @group.
2447
 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2448
 * been bound to an appropriate interface and port with
2449
 * g_socket_bind().
2450
 *
2451
 * If @iface is %NULL, the system will automatically pick an interface
2452
 * to bind to based on @group.
2453
 *
2454
 * If @source_specific is %TRUE, source-specific multicast as defined
2455
 * in RFC 4604 is used. Note that on older platforms this may fail
2456
 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2457
 *
2458
 * To bind to a given source-specific multicast address, use
2459
 * g_socket_join_multicast_group_ssm() instead.
2460
 *
2461
 * Returns: %TRUE on success, %FALSE on error.
2462
 *
2463
 * Since: 2.32
2464
 */
2465
gboolean
2466
g_socket_join_multicast_group (GSocket       *socket,
2467
             GInetAddress  *group,
2468
                               gboolean       source_specific,
2469
                               const gchar   *iface,
2470
             GError       **error)
2471
0
{
2472
0
  return g_socket_multicast_group_operation (socket, group, source_specific, iface, TRUE, error);
2473
0
}
2474
2475
/**
2476
 * g_socket_leave_multicast_group:
2477
 * @socket: a #GSocket.
2478
 * @group: a #GInetAddress specifying the group address to leave.
2479
 * @iface: (nullable): Interface used
2480
 * @source_specific: %TRUE if source-specific multicast was used
2481
 * @error: #GError for error reporting, or %NULL to ignore.
2482
 *
2483
 * Removes @socket from the multicast group defined by @group, @iface,
2484
 * and @source_specific (which must all have the same values they had
2485
 * when you joined the group).
2486
 *
2487
 * @socket remains bound to its address and port, and can still receive
2488
 * unicast messages after calling this.
2489
 *
2490
 * To unbind to a given source-specific multicast address, use
2491
 * g_socket_leave_multicast_group_ssm() instead.
2492
 *
2493
 * Returns: %TRUE on success, %FALSE on error.
2494
 *
2495
 * Since: 2.32
2496
 */
2497
gboolean
2498
g_socket_leave_multicast_group (GSocket       *socket,
2499
        GInetAddress  *group,
2500
                                gboolean       source_specific,
2501
                                const gchar   *iface,
2502
        GError       **error)
2503
0
{
2504
0
  return g_socket_multicast_group_operation (socket, group, source_specific, iface, FALSE, error);
2505
0
}
2506
2507
static gboolean
2508
g_socket_multicast_group_operation_ssm (GSocket       *socket,
2509
                                        GInetAddress  *group,
2510
                                        GInetAddress  *source_specific,
2511
                                        const gchar   *iface,
2512
                                        gboolean       join_group,
2513
                                        GError       **error)
2514
0
{
2515
0
  gint result;
2516
2517
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
2518
0
  g_return_val_if_fail (socket->priv->type == G_SOCKET_TYPE_DATAGRAM, FALSE);
2519
0
  g_return_val_if_fail (G_IS_INET_ADDRESS (group), FALSE);
2520
0
  g_return_val_if_fail (iface == NULL || *iface != '\0', FALSE);
2521
0
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2522
2523
0
  if (!source_specific)
2524
0
    {
2525
0
      return g_socket_multicast_group_operation (socket, group, FALSE, iface,
2526
0
                                                 join_group, error);
2527
0
    }
2528
2529
0
  if (!check_socket (socket, error))
2530
0
    return FALSE;
2531
2532
0
  switch (g_inet_address_get_family (group))
2533
0
    {
2534
0
    case G_SOCKET_FAMILY_INVALID:
2535
0
    case G_SOCKET_FAMILY_UNIX:
2536
0
      {
2537
0
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2538
0
            join_group ?
2539
0
            _("Error joining multicast group: %s") :
2540
0
            _("Error leaving multicast group: %s"),
2541
0
            _("Unsupported socket family"));
2542
0
        return FALSE;
2543
0
      }
2544
0
      break;
2545
2546
0
    case G_SOCKET_FAMILY_IPV4:
2547
0
      {
2548
0
#ifdef IP_ADD_SOURCE_MEMBERSHIP
2549
2550
#ifdef BROKEN_IP_MREQ_SOURCE_STRUCT
2551
#define S_ADDR_FIELD(src) src.imr_interface
2552
#else
2553
0
#define S_ADDR_FIELD(src) src.imr_interface.s_addr
2554
0
#endif
2555
2556
0
        gint optname;
2557
0
        struct ip_mreq_source mc_req_src;
2558
2559
0
        if (g_inet_address_get_family (source_specific) !=
2560
0
            G_SOCKET_FAMILY_IPV4)
2561
0
          {
2562
0
            g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2563
0
                join_group ?
2564
0
                _("Error joining multicast group: %s") :
2565
0
                _("Error leaving multicast group: %s"),
2566
0
                _("source-specific not an IPv4 address"));
2567
0
            return FALSE;
2568
0
          }
2569
2570
0
        memset (&mc_req_src, 0, sizeof (mc_req_src));
2571
2572
        /* By default use the default IPv4 multicast interface. */
2573
0
        S_ADDR_FIELD(mc_req_src) = g_htonl (INADDR_ANY);
2574
2575
0
        if (iface)
2576
0
          {
2577
#if defined(G_OS_WIN32)
2578
            S_ADDR_FIELD(mc_req_src) = g_socket_w32_get_adapter_ipv4_addr (iface);
2579
#elif defined (HAVE_SIOCGIFADDR)
2580
            int ret;
2581
0
            struct ifreq ifr;
2582
0
            struct sockaddr_in *iface_addr;
2583
0
            size_t if_name_len = strlen (iface);
2584
2585
0
            memset (&ifr, 0, sizeof (ifr));
2586
2587
0
            if (if_name_len >= sizeof (ifr.ifr_name))
2588
0
              {
2589
0
                g_set_error (error, G_IO_ERROR,  G_IO_ERROR_FILENAME_TOO_LONG,
2590
0
                             _("Interface name too long"));
2591
0
                return FALSE;
2592
0
              }
2593
2594
0
            memcpy (ifr.ifr_name, iface, if_name_len);
2595
2596
            /* Get the IPv4 address of the given network interface name. */
2597
0
            ret = ioctl (socket->priv->fd, SIOCGIFADDR, &ifr);
2598
0
            if (ret < 0)
2599
0
              {
2600
0
                int errsv = errno;
2601
2602
0
                g_set_error (error, G_IO_ERROR,  g_io_error_from_errno (errsv),
2603
0
                             _("Interface not found: %s"), g_strerror (errsv));
2604
0
                return FALSE;
2605
0
              }
2606
2607
0
            iface_addr = (struct sockaddr_in *) &ifr.ifr_addr;
2608
0
            S_ADDR_FIELD(mc_req_src) = iface_addr->sin_addr.s_addr;
2609
0
#endif  /* defined(G_OS_WIN32) && defined (HAVE_IF_NAMETOINDEX) */
2610
0
          }
2611
2612
0
        g_assert (g_inet_address_get_native_size (group) == sizeof (mc_req_src.imr_multiaddr));
2613
0
        memcpy (&mc_req_src.imr_multiaddr, g_inet_address_to_bytes (group),
2614
0
                g_inet_address_get_native_size (group));
2615
2616
0
        g_assert (g_inet_address_get_native_size (source_specific) == sizeof (mc_req_src.imr_sourceaddr));
2617
0
        memcpy (&mc_req_src.imr_sourceaddr,
2618
0
                g_inet_address_to_bytes (source_specific),
2619
0
                g_inet_address_get_native_size (source_specific));
2620
2621
0
        optname =
2622
0
            join_group ? IP_ADD_SOURCE_MEMBERSHIP : IP_DROP_SOURCE_MEMBERSHIP;
2623
0
        result = setsockopt (socket->priv->fd, IPPROTO_IP, optname,
2624
0
                             &mc_req_src, sizeof (mc_req_src));
2625
2626
0
#undef S_ADDR_FIELD
2627
2628
#else
2629
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2630
            join_group ?
2631
            _("Error joining multicast group: %s") :
2632
            _("Error leaving multicast group: %s"),
2633
            _("No support for IPv4 source-specific multicast"));
2634
        return FALSE;
2635
#endif  /* IP_ADD_SOURCE_MEMBERSHIP */
2636
0
      }
2637
0
      break;
2638
2639
0
    case G_SOCKET_FAMILY_IPV6:
2640
0
      {
2641
0
#ifdef MCAST_JOIN_SOURCE_GROUP
2642
0
        gboolean res;
2643
0
        gint optname;
2644
0
        struct group_source_req mc_req_src;
2645
0
        GSocketAddress *saddr_group, *saddr_source_specific;
2646
0
        guint iface_index = 0;
2647
2648
0
#if defined (HAVE_IF_NAMETOINDEX)
2649
0
        if (iface)
2650
0
          {
2651
0
            iface_index = if_nametoindex (iface);
2652
0
            if (iface_index == 0)
2653
0
              {
2654
0
                int errsv = errno;
2655
2656
0
                g_set_error (error, G_IO_ERROR,  g_io_error_from_errno (errsv),
2657
0
                             _("Interface not found: %s"), g_strerror (errsv));
2658
0
                return FALSE;
2659
0
              }
2660
0
          }
2661
0
#endif  /* defined (HAVE_IF_NAMETOINDEX) */
2662
0
        mc_req_src.gsr_interface = iface_index;
2663
2664
0
        saddr_group = g_inet_socket_address_new (group, 0);
2665
0
        res = g_socket_address_to_native (saddr_group, &mc_req_src.gsr_group,
2666
0
                                          sizeof (mc_req_src.gsr_group),
2667
0
                                          error);
2668
0
        g_object_unref (saddr_group);
2669
0
        if (!res)
2670
0
          return FALSE;
2671
2672
0
        saddr_source_specific = g_inet_socket_address_new (source_specific, 0);
2673
0
        res = g_socket_address_to_native (saddr_source_specific,
2674
0
                                          &mc_req_src.gsr_source,
2675
0
                                          sizeof (mc_req_src.gsr_source),
2676
0
                                          error);
2677
0
        g_object_unref (saddr_source_specific);
2678
2679
0
        if (!res)
2680
0
          return FALSE;
2681
2682
0
        optname =
2683
0
            join_group ? MCAST_JOIN_SOURCE_GROUP : MCAST_LEAVE_SOURCE_GROUP;
2684
0
        result = setsockopt (socket->priv->fd, IPPROTO_IPV6, optname,
2685
0
                             &mc_req_src, sizeof (mc_req_src));
2686
#else
2687
        g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2688
            join_group ?
2689
            _("Error joining multicast group: %s") :
2690
            _("Error leaving multicast group: %s"),
2691
            _("No support for IPv6 source-specific multicast"));
2692
        return FALSE;
2693
#endif  /* MCAST_JOIN_SOURCE_GROUP */
2694
0
      }
2695
0
      break;
2696
2697
0
    default:
2698
0
      g_return_val_if_reached (FALSE);
2699
0
    }
2700
2701
0
  if (result < 0)
2702
0
    {
2703
0
      int errsv = get_socket_errno ();
2704
2705
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
2706
0
          join_group ?
2707
0
          _("Error joining multicast group: %s") :
2708
0
          _("Error leaving multicast group: %s"),
2709
0
           socket_strerror (errsv));
2710
0
      return FALSE;
2711
0
    }
2712
2713
0
  return TRUE;
2714
0
}
2715
2716
/**
2717
 * g_socket_join_multicast_group_ssm:
2718
 * @socket: a #GSocket.
2719
 * @group: a #GInetAddress specifying the group address to join.
2720
 * @source_specific: (nullable): a #GInetAddress specifying the
2721
 * source-specific multicast address or %NULL to ignore.
2722
 * @iface: (nullable): Name of the interface to use, or %NULL
2723
 * @error: #GError for error reporting, or %NULL to ignore.
2724
 *
2725
 * Registers @socket to receive multicast messages sent to @group.
2726
 * @socket must be a %G_SOCKET_TYPE_DATAGRAM socket, and must have
2727
 * been bound to an appropriate interface and port with
2728
 * g_socket_bind().
2729
 *
2730
 * If @iface is %NULL, the system will automatically pick an interface
2731
 * to bind to based on @group.
2732
 *
2733
 * If @source_specific is not %NULL, use source-specific multicast as
2734
 * defined in RFC 4604. Note that on older platforms this may fail
2735
 * with a %G_IO_ERROR_NOT_SUPPORTED error.
2736
 *
2737
 * Note that this function can be called multiple times for the same
2738
 * @group with different @source_specific in order to receive multicast
2739
 * packets from more than one source.
2740
 *
2741
 * Returns: %TRUE on success, %FALSE on error.
2742
 *
2743
 * Since: 2.56
2744
 */
2745
gboolean
2746
g_socket_join_multicast_group_ssm (GSocket       *socket,
2747
                                   GInetAddress  *group,
2748
                                   GInetAddress  *source_specific,
2749
                                   const gchar   *iface,
2750
                                   GError       **error)
2751
0
{
2752
0
  return g_socket_multicast_group_operation_ssm (socket, group,
2753
0
      source_specific, iface, TRUE, error);
2754
0
}
2755
2756
/**
2757
 * g_socket_leave_multicast_group_ssm:
2758
 * @socket: a #GSocket.
2759
 * @group: a #GInetAddress specifying the group address to leave.
2760
 * @source_specific: (nullable): a #GInetAddress specifying the
2761
 * source-specific multicast address or %NULL to ignore.
2762
 * @iface: (nullable): Name of the interface to use, or %NULL
2763
 * @error: #GError for error reporting, or %NULL to ignore.
2764
 *
2765
 * Removes @socket from the multicast group defined by @group, @iface,
2766
 * and @source_specific (which must all have the same values they had
2767
 * when you joined the group).
2768
 *
2769
 * @socket remains bound to its address and port, and can still receive
2770
 * unicast messages after calling this.
2771
 *
2772
 * Returns: %TRUE on success, %FALSE on error.
2773
 *
2774
 * Since: 2.56
2775
 */
2776
gboolean
2777
g_socket_leave_multicast_group_ssm (GSocket       *socket,
2778
                                    GInetAddress  *group,
2779
                                    GInetAddress  *source_specific,
2780
                                    const gchar   *iface,
2781
                                    GError       **error)
2782
0
{
2783
0
  return g_socket_multicast_group_operation_ssm (socket, group,
2784
0
      source_specific, iface, FALSE, error);
2785
0
}
2786
2787
/**
2788
 * g_socket_speaks_ipv4:
2789
 * @socket: a #GSocket
2790
 *
2791
 * Checks if a socket is capable of speaking IPv4.
2792
 *
2793
 * IPv4 sockets are capable of speaking IPv4.  On some operating systems
2794
 * and under some combinations of circumstances IPv6 sockets are also
2795
 * capable of speaking IPv4.  See RFC 3493 section 3.7 for more
2796
 * information.
2797
 *
2798
 * No other types of sockets are currently considered as being capable
2799
 * of speaking IPv4.
2800
 *
2801
 * Returns: %TRUE if this socket can be used with IPv4.
2802
 *
2803
 * Since: 2.22
2804
 **/
2805
gboolean
2806
g_socket_speaks_ipv4 (GSocket *socket)
2807
0
{
2808
0
  switch (socket->priv->family)
2809
0
    {
2810
0
    case G_SOCKET_FAMILY_IPV4:
2811
0
      return TRUE;
2812
2813
0
    case G_SOCKET_FAMILY_IPV6:
2814
0
#if defined (IPPROTO_IPV6) && defined (IPV6_V6ONLY)
2815
0
      {
2816
0
        gint v6_only;
2817
2818
0
        if (!g_socket_get_option (socket,
2819
0
          IPPROTO_IPV6, IPV6_V6ONLY,
2820
0
          &v6_only, NULL))
2821
0
          return FALSE;
2822
2823
0
        return !v6_only;
2824
0
      }
2825
#else
2826
      return FALSE;
2827
#endif
2828
2829
0
    default:
2830
0
      return FALSE;
2831
0
    }
2832
0
}
2833
2834
/**
2835
 * g_socket_accept:
2836
 * @socket: a #GSocket.
2837
 * @cancellable: (nullable): a %GCancellable or %NULL
2838
 * @error: #GError for error reporting, or %NULL to ignore.
2839
 *
2840
 * Accept incoming connections on a connection-based socket. This removes
2841
 * the first outstanding connection request from the listening socket and
2842
 * creates a #GSocket object for it.
2843
 *
2844
 * The @socket must be bound to a local address with g_socket_bind() and
2845
 * must be listening for incoming connections (g_socket_listen()).
2846
 *
2847
 * If there are no outstanding connections then the operation will block
2848
 * or return %G_IO_ERROR_WOULD_BLOCK if non-blocking I/O is enabled.
2849
 * To be notified of an incoming connection, wait for the %G_IO_IN condition.
2850
 *
2851
 * Returns: (transfer full): a new #GSocket, or %NULL on error.
2852
 *     Free the returned object with g_object_unref().
2853
 *
2854
 * Since: 2.22
2855
 */
2856
GSocket *
2857
g_socket_accept (GSocket       *socket,
2858
     GCancellable  *cancellable,
2859
     GError       **error)
2860
0
{
2861
0
  GSocket *new_socket;
2862
0
  gint ret;
2863
2864
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
2865
2866
0
  if (!check_socket (socket, error))
2867
0
    return NULL;
2868
2869
0
  if (!check_timeout (socket, error))
2870
0
    return NULL;
2871
2872
0
  while (TRUE)
2873
0
    {
2874
0
      if ((ret = accept (socket->priv->fd, NULL, 0)) < 0)
2875
0
  {
2876
0
    int errsv = get_socket_errno ();
2877
2878
0
    if (errsv == EINTR)
2879
0
      continue;
2880
2881
#ifdef WSAEWOULDBLOCK
2882
          if (errsv == WSAEWOULDBLOCK)
2883
#else
2884
0
          if (errsv == EWOULDBLOCK ||
2885
0
              errsv == EAGAIN)
2886
0
#endif
2887
0
            {
2888
0
              win32_unset_event_mask (socket, FD_ACCEPT);
2889
2890
0
              if (socket->priv->blocking)
2891
0
                {
2892
0
                  if (!g_socket_condition_wait (socket,
2893
0
                                                G_IO_IN, cancellable, error))
2894
0
                    return NULL;
2895
2896
0
                  continue;
2897
0
                }
2898
0
            }
2899
2900
0
    socket_set_error_lazy (error, errsv, _("Error accepting connection: %s"));
2901
0
    return NULL;
2902
0
  }
2903
0
      break;
2904
0
    }
2905
2906
0
  win32_unset_event_mask (socket, FD_ACCEPT);
2907
2908
#ifdef G_OS_WIN32
2909
  {
2910
    /* The socket inherits the accepting sockets event mask and even object,
2911
       we need to remove that */
2912
    WSAEventSelect (ret, NULL, 0);
2913
  }
2914
#else
2915
0
  {
2916
0
    int flags;
2917
2918
    /* We always want to set close-on-exec to protect users. If you
2919
       need to so some weird inheritance to exec you can re-enable this
2920
       using lower level hacks with g_socket_get_fd(). */
2921
0
    flags = fcntl (ret, F_GETFD, 0);
2922
0
    if (flags != -1 &&
2923
0
  (flags & FD_CLOEXEC) == 0)
2924
0
      {
2925
0
  flags |= FD_CLOEXEC;
2926
0
  fcntl (ret, F_SETFD, flags);
2927
0
      }
2928
0
  }
2929
0
#endif
2930
2931
0
  new_socket = g_socket_new_from_fd (ret, error);
2932
0
  if (new_socket == NULL)
2933
0
    {
2934
#ifdef G_OS_WIN32
2935
      closesocket (ret);
2936
#else
2937
0
      close (ret);
2938
0
#endif
2939
0
    }
2940
0
  else
2941
0
    new_socket->priv->protocol = socket->priv->protocol;
2942
2943
0
  return new_socket;
2944
0
}
2945
2946
/**
2947
 * g_socket_connect:
2948
 * @socket: a #GSocket.
2949
 * @address: a #GSocketAddress specifying the remote address.
2950
 * @cancellable: (nullable): a %GCancellable or %NULL
2951
 * @error: #GError for error reporting, or %NULL to ignore.
2952
 *
2953
 * Connect the socket to the specified remote address.
2954
 *
2955
 * For connection oriented socket this generally means we attempt to make
2956
 * a connection to the @address. For a connection-less socket it sets
2957
 * the default address for g_socket_send() and discards all incoming datagrams
2958
 * from other sources.
2959
 *
2960
 * Generally connection oriented sockets can only connect once, but
2961
 * connection-less sockets can connect multiple times to change the
2962
 * default address.
2963
 *
2964
 * If the connect call needs to do network I/O it will block, unless
2965
 * non-blocking I/O is enabled. Then %G_IO_ERROR_PENDING is returned
2966
 * and the user can be notified of the connection finishing by waiting
2967
 * for the G_IO_OUT condition. The result of the connection must then be
2968
 * checked with g_socket_check_connect_result().
2969
 *
2970
 * Returns: %TRUE if connected, %FALSE on error.
2971
 *
2972
 * Since: 2.22
2973
 */
2974
gboolean
2975
g_socket_connect (GSocket         *socket,
2976
      GSocketAddress  *address,
2977
      GCancellable    *cancellable,
2978
      GError         **error)
2979
0
{
2980
0
  union {
2981
0
    struct sockaddr_storage storage;
2982
0
    struct sockaddr sa;
2983
0
  } buffer;
2984
2985
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && G_IS_SOCKET_ADDRESS (address), FALSE);
2986
2987
0
  if (!check_socket (socket, error))
2988
0
    return FALSE;
2989
2990
0
  if (!g_socket_address_to_native (address, &buffer.storage, sizeof buffer, error))
2991
0
    return FALSE;
2992
2993
0
  if (socket->priv->remote_address)
2994
0
    g_object_unref (socket->priv->remote_address);
2995
0
  socket->priv->remote_address = g_object_ref (address);
2996
2997
0
  while (1)
2998
0
    {
2999
0
      if (connect (socket->priv->fd, &buffer.sa,
3000
0
       g_socket_address_get_native_size (address)) < 0)
3001
0
  {
3002
0
    int errsv = get_socket_errno ();
3003
3004
0
    if (errsv == EINTR)
3005
0
      continue;
3006
3007
0
#ifndef G_OS_WIN32
3008
0
    if (errsv == EINPROGRESS)
3009
#else
3010
    if (errsv == WSAEWOULDBLOCK)
3011
#endif
3012
0
      {
3013
0
              win32_unset_event_mask (socket, FD_CONNECT);
3014
3015
0
        if (socket->priv->blocking)
3016
0
    {
3017
0
      if (g_socket_condition_wait (socket, G_IO_OUT, cancellable, error))
3018
0
        {
3019
0
          if (g_socket_check_connect_result (socket, error))
3020
0
      break;
3021
0
        }
3022
0
    }
3023
0
        else
3024
0
                {
3025
0
                  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_PENDING,
3026
0
                                       _("Connection in progress"));
3027
0
                  socket->priv->connect_pending = TRUE;
3028
0
                }
3029
0
      }
3030
0
    else
3031
0
      g_set_error_literal (error, G_IO_ERROR,
3032
0
         socket_io_error_from_errno (errsv),
3033
0
         socket_strerror (errsv));
3034
3035
0
    return FALSE;
3036
0
  }
3037
0
      break;
3038
0
    }
3039
3040
0
  win32_unset_event_mask (socket, FD_CONNECT);
3041
3042
0
  socket->priv->connected_read = TRUE;
3043
0
  socket->priv->connected_write = TRUE;
3044
3045
0
  return TRUE;
3046
0
}
3047
3048
/**
3049
 * g_socket_check_connect_result:
3050
 * @socket: a #GSocket
3051
 * @error: #GError for error reporting, or %NULL to ignore.
3052
 *
3053
 * Checks and resets the pending connect error for the socket.
3054
 * This is used to check for errors when g_socket_connect() is
3055
 * used in non-blocking mode.
3056
 *
3057
 * Returns: %TRUE if no error, %FALSE otherwise, setting @error to the error
3058
 *
3059
 * Since: 2.22
3060
 */
3061
gboolean
3062
g_socket_check_connect_result (GSocket  *socket,
3063
             GError  **error)
3064
0
{
3065
0
  int value;
3066
3067
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
3068
3069
0
  if (!check_socket (socket, error))
3070
0
    return FALSE;
3071
3072
0
  if (!check_timeout (socket, error))
3073
0
    return FALSE;
3074
3075
0
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_ERROR, &value, error))
3076
0
    {
3077
0
      g_prefix_error (error, _("Unable to get pending error: "));
3078
0
      return FALSE;
3079
0
    }
3080
3081
0
  if (value != 0)
3082
0
    {
3083
0
      g_set_error_literal (error, G_IO_ERROR, socket_io_error_from_errno (value),
3084
0
                           socket_strerror (value));
3085
0
      if (socket->priv->remote_address)
3086
0
        {
3087
0
          g_object_unref (socket->priv->remote_address);
3088
0
          socket->priv->remote_address = NULL;
3089
0
        }
3090
0
      return FALSE;
3091
0
    }
3092
3093
0
  socket->priv->connected_read = TRUE;
3094
0
  socket->priv->connected_write = TRUE;
3095
3096
0
  return TRUE;
3097
0
}
3098
3099
/**
3100
 * g_socket_get_available_bytes:
3101
 * @socket: a #GSocket
3102
 *
3103
 * Get the amount of data pending in the OS input buffer, without blocking.
3104
 *
3105
 * If @socket is a UDP or SCTP socket, this will return the size of
3106
 * just the next packet, even if additional packets are buffered after
3107
 * that one.
3108
 *
3109
 * Note that on Windows, this function is rather inefficient in the
3110
 * UDP case, and so if you know any plausible upper bound on the size
3111
 * of the incoming packet, it is better to just do a
3112
 * g_socket_receive() with a buffer of that size, rather than calling
3113
 * g_socket_get_available_bytes() first and then doing a receive of
3114
 * exactly the right size.
3115
 *
3116
 * Returns: the number of bytes that can be read from the socket
3117
 * without blocking or truncating, or -1 on error.
3118
 *
3119
 * Since: 2.32
3120
 */
3121
gssize
3122
g_socket_get_available_bytes (GSocket *socket)
3123
0
{
3124
0
#ifndef SO_NREAD
3125
0
  const gint bufsize = 64 * 1024;
3126
0
  static guchar *buf = NULL;
3127
0
#endif
3128
#ifdef G_OS_WIN32
3129
  u_long avail;
3130
#else
3131
0
  gint avail;
3132
0
#endif
3133
3134
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
3135
3136
0
  if (!check_socket (socket, NULL))
3137
0
    return -1;
3138
3139
#ifdef SO_NREAD
3140
  if (!g_socket_get_option (socket, SOL_SOCKET, SO_NREAD, &avail, NULL))
3141
      return -1;
3142
#else
3143
0
  if (socket->priv->type == G_SOCKET_TYPE_DATAGRAM)
3144
0
    {
3145
0
      if (G_UNLIKELY (g_once_init_enter (&buf)))
3146
0
        g_once_init_leave (&buf, g_malloc (bufsize));
3147
3148
      /* On datagram sockets, FIONREAD ioctl is not reliable because many
3149
       * systems add internal header size to the reported size, making it
3150
       * unusable for this function. */
3151
0
      avail = recv (socket->priv->fd, buf, bufsize, MSG_PEEK);
3152
0
      if ((gint) avail == -1)
3153
0
        {
3154
0
          int errsv = get_socket_errno ();
3155
#ifdef G_OS_WIN32
3156
          if (errsv == WSAEWOULDBLOCK)
3157
#else
3158
0
          if (errsv == EWOULDBLOCK || errsv == EAGAIN)
3159
0
#endif
3160
0
            avail = 0;
3161
0
        }
3162
0
    }
3163
0
  else
3164
0
    {
3165
#ifdef G_OS_WIN32
3166
      if (ioctlsocket (socket->priv->fd, FIONREAD, &avail) < 0)
3167
#else
3168
0
      if (ioctl (socket->priv->fd, FIONREAD, &avail) < 0)
3169
0
#endif
3170
0
        avail = -1;
3171
0
    }
3172
0
#endif
3173
3174
0
  return avail;
3175
0
}
3176
3177
/* Block on a timed wait for @condition until (@start_time + @timeout).
3178
 * Return %G_IO_ERROR_TIMED_OUT if the timeout is reached; otherwise %TRUE.
3179
 */
3180
static gboolean
3181
block_on_timeout (GSocket       *socket,
3182
                  GIOCondition   condition,
3183
                  gint64         timeout_us,
3184
                  gint64         start_time,
3185
                  GCancellable  *cancellable,
3186
                  GError       **error)
3187
0
{
3188
0
  gint64 wait_timeout = -1;
3189
3190
0
  g_return_val_if_fail (timeout_us != 0, TRUE);
3191
3192
  /* check if we've timed out or how much time to wait at most */
3193
0
  if (timeout_us >= 0)
3194
0
    {
3195
0
      gint64 elapsed = g_get_monotonic_time () - start_time;
3196
3197
0
      if (elapsed >= timeout_us)
3198
0
        {
3199
0
          g_set_error_literal (error,
3200
0
                               G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
3201
0
                               _("Socket I/O timed out"));
3202
0
          return FALSE;
3203
0
        }
3204
3205
0
      wait_timeout = timeout_us - elapsed;
3206
0
    }
3207
3208
0
  return g_socket_condition_timed_wait (socket, condition, wait_timeout,
3209
0
                                        cancellable, error);
3210
0
}
3211
3212
static gssize
3213
g_socket_receive_with_timeout (GSocket       *socket,
3214
                               guint8        *buffer,
3215
                               gsize          size,
3216
                               gint64         timeout_us,
3217
                               GCancellable  *cancellable,
3218
                               GError       **error)
3219
0
{
3220
0
  gssize ret;
3221
0
  gint64 start_time;
3222
3223
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3224
3225
0
  start_time = g_get_monotonic_time ();
3226
3227
0
  if (!check_socket (socket, error))
3228
0
    return -1;
3229
3230
0
  if (!check_timeout (socket, error))
3231
0
    return -1;
3232
3233
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
3234
0
    return -1;
3235
3236
0
  while (1)
3237
0
    {
3238
0
      if ((ret = recv (socket->priv->fd, buffer, size, 0)) < 0)
3239
0
  {
3240
0
    int errsv = get_socket_errno ();
3241
3242
0
    if (errsv == EINTR)
3243
0
      continue;
3244
3245
#ifdef WSAEWOULDBLOCK
3246
          if (errsv == WSAEWOULDBLOCK)
3247
#else
3248
0
          if (errsv == EWOULDBLOCK ||
3249
0
              errsv == EAGAIN)
3250
0
#endif
3251
0
            {
3252
0
              win32_unset_event_mask (socket, FD_READ);
3253
3254
0
              if (timeout_us != 0)
3255
0
                {
3256
0
                  if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
3257
0
                                         cancellable, error))
3258
0
                    return -1;
3259
3260
0
                  continue;
3261
0
                }
3262
0
            }
3263
3264
0
    win32_unset_event_mask (socket, FD_READ);
3265
3266
0
    socket_set_error_lazy (error, errsv, _("Error receiving data: %s"));
3267
0
    return -1;
3268
0
  }
3269
3270
0
      win32_unset_event_mask (socket, FD_READ);
3271
3272
0
      break;
3273
0
    }
3274
3275
0
  return ret;
3276
0
}
3277
3278
/**
3279
 * g_socket_receive:
3280
 * @socket: a #GSocket
3281
 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3282
 *     a buffer to read data into (which should be at least @size bytes long).
3283
 * @size: the number of bytes you want to read from the socket
3284
 * @cancellable: (nullable): a %GCancellable or %NULL
3285
 * @error: #GError for error reporting, or %NULL to ignore.
3286
 *
3287
 * Receive data (up to @size bytes) from a socket. This is mainly used by
3288
 * connection-oriented sockets; it is identical to g_socket_receive_from()
3289
 * with @address set to %NULL.
3290
 *
3291
 * For %G_SOCKET_TYPE_DATAGRAM and %G_SOCKET_TYPE_SEQPACKET sockets,
3292
 * g_socket_receive() will always read either 0 or 1 complete messages from
3293
 * the socket. If the received message is too large to fit in @buffer, then
3294
 * the data beyond @size bytes will be discarded, without any explicit
3295
 * indication that this has occurred.
3296
 *
3297
 * For %G_SOCKET_TYPE_STREAM sockets, g_socket_receive() can return any
3298
 * number of bytes, up to @size. If more than @size bytes have been
3299
 * received, the additional data will be returned in future calls to
3300
 * g_socket_receive().
3301
 *
3302
 * If the socket is in blocking mode the call will block until there
3303
 * is some data to receive, the connection is closed, or there is an
3304
 * error. If there is no data available and the socket is in
3305
 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
3306
 * returned. To be notified when data is available, wait for the
3307
 * %G_IO_IN condition.
3308
 *
3309
 * On error -1 is returned and @error is set accordingly.
3310
 *
3311
 * Returns: Number of bytes read, or 0 if the connection was closed by
3312
 * the peer, or -1 on error
3313
 *
3314
 * Since: 2.22
3315
 */
3316
gssize
3317
g_socket_receive (GSocket       *socket,
3318
      gchar         *buffer,
3319
      gsize          size,
3320
      GCancellable  *cancellable,
3321
      GError       **error)
3322
0
{
3323
0
  return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3324
0
                                        socket->priv->blocking ? -1 : 0,
3325
0
                                        cancellable, error);
3326
0
}
3327
3328
/**
3329
 * g_socket_receive_with_blocking:
3330
 * @socket: a #GSocket
3331
 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3332
 *     a buffer to read data into (which should be at least @size bytes long).
3333
 * @size: the number of bytes you want to read from the socket
3334
 * @blocking: whether to do blocking or non-blocking I/O
3335
 * @cancellable: (nullable): a %GCancellable or %NULL
3336
 * @error: #GError for error reporting, or %NULL to ignore.
3337
 *
3338
 * This behaves exactly the same as g_socket_receive(), except that
3339
 * the choice of blocking or non-blocking behavior is determined by
3340
 * the @blocking argument rather than by @socket's properties.
3341
 *
3342
 * Returns: Number of bytes read, or 0 if the connection was closed by
3343
 * the peer, or -1 on error
3344
 *
3345
 * Since: 2.26
3346
 */
3347
gssize
3348
g_socket_receive_with_blocking (GSocket       *socket,
3349
        gchar         *buffer,
3350
        gsize          size,
3351
        gboolean       blocking,
3352
        GCancellable  *cancellable,
3353
        GError       **error)
3354
0
{
3355
0
  return g_socket_receive_with_timeout (socket, (guint8 *) buffer, size,
3356
0
                                        blocking ? -1 : 0, cancellable, error);
3357
0
}
3358
3359
/**
3360
 * g_socket_receive_from:
3361
 * @socket: a #GSocket
3362
 * @address: (out) (optional): a pointer to a #GSocketAddress
3363
 *     pointer, or %NULL
3364
 * @buffer: (array length=size) (element-type guint8) (out caller-allocates):
3365
 *     a buffer to read data into (which should be at least @size bytes long).
3366
 * @size: the number of bytes you want to read from the socket
3367
 * @cancellable: (nullable): a %GCancellable or %NULL
3368
 * @error: #GError for error reporting, or %NULL to ignore.
3369
 *
3370
 * Receive data (up to @size bytes) from a socket.
3371
 *
3372
 * If @address is non-%NULL then @address will be set equal to the
3373
 * source address of the received packet.
3374
 * @address is owned by the caller.
3375
 *
3376
 * See g_socket_receive() for additional information.
3377
 *
3378
 * Returns: Number of bytes read, or 0 if the connection was closed by
3379
 * the peer, or -1 on error
3380
 *
3381
 * Since: 2.22
3382
 */
3383
gssize
3384
g_socket_receive_from (GSocket         *socket,
3385
           GSocketAddress **address,
3386
           gchar           *buffer,
3387
           gsize            size,
3388
           GCancellable    *cancellable,
3389
           GError         **error)
3390
0
{
3391
0
  GInputVector v;
3392
3393
0
  v.buffer = buffer;
3394
0
  v.size = size;
3395
3396
0
  return g_socket_receive_message (socket,
3397
0
           address,
3398
0
           &v, 1,
3399
0
           NULL, 0, NULL,
3400
0
           cancellable,
3401
0
           error);
3402
0
}
3403
3404
/* See the comment about SIGPIPE above. */
3405
#ifdef MSG_NOSIGNAL
3406
0
#define G_SOCKET_DEFAULT_SEND_FLAGS MSG_NOSIGNAL
3407
#else
3408
#define G_SOCKET_DEFAULT_SEND_FLAGS 0
3409
#endif
3410
3411
static gssize
3412
g_socket_send_with_timeout (GSocket       *socket,
3413
                            const guint8  *buffer,
3414
                            gsize          size,
3415
                            gint64         timeout_us,
3416
                            GCancellable  *cancellable,
3417
                            GError       **error)
3418
0
{
3419
0
  gssize ret;
3420
0
  gint64 start_time;
3421
3422
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && buffer != NULL, -1);
3423
3424
0
  start_time = g_get_monotonic_time ();
3425
3426
0
  if (!check_socket (socket, error))
3427
0
    return -1;
3428
3429
0
  if (!check_timeout (socket, error))
3430
0
    return -1;
3431
3432
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
3433
0
    return -1;
3434
3435
0
  while (1)
3436
0
    {
3437
0
      if ((ret = send (socket->priv->fd, (const char *)buffer, size, G_SOCKET_DEFAULT_SEND_FLAGS)) < 0)
3438
0
  {
3439
0
    int errsv = get_socket_errno ();
3440
3441
0
    if (errsv == EINTR)
3442
0
      continue;
3443
3444
#ifdef WSAEWOULDBLOCK
3445
          if (errsv == WSAEWOULDBLOCK)
3446
#else
3447
0
          if (errsv == EWOULDBLOCK ||
3448
0
              errsv == EAGAIN)
3449
0
#endif
3450
0
            {
3451
0
              win32_unset_event_mask (socket, FD_WRITE);
3452
3453
0
              if (timeout_us != 0)
3454
0
                {
3455
0
                  if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
3456
0
                                         cancellable, error))
3457
0
                    return -1;
3458
3459
0
                  continue;
3460
0
                }
3461
0
            }
3462
3463
0
    socket_set_error_lazy (error, errsv, _("Error sending data: %s"));
3464
0
    return -1;
3465
0
  }
3466
0
      break;
3467
0
    }
3468
3469
0
  return ret;
3470
0
}
3471
3472
/**
3473
 * g_socket_send:
3474
 * @socket: a #GSocket
3475
 * @buffer: (array length=size) (element-type guint8): the buffer
3476
 *     containing the data to send.
3477
 * @size: the number of bytes to send
3478
 * @cancellable: (nullable): a %GCancellable or %NULL
3479
 * @error: #GError for error reporting, or %NULL to ignore.
3480
 *
3481
 * Tries to send @size bytes from @buffer on the socket. This is
3482
 * mainly used by connection-oriented sockets; it is identical to
3483
 * g_socket_send_to() with @address set to %NULL.
3484
 *
3485
 * If the socket is in blocking mode the call will block until there is
3486
 * space for the data in the socket queue. If there is no space available
3487
 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
3488
 * will be returned. To be notified when space is available, wait for the
3489
 * %G_IO_OUT condition. Note though that you may still receive
3490
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
3491
 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
3492
 * very common due to the way the underlying APIs work.)
3493
 *
3494
 * On error -1 is returned and @error is set accordingly.
3495
 *
3496
 * Returns: Number of bytes written (which may be less than @size), or -1
3497
 * on error
3498
 *
3499
 * Since: 2.22
3500
 */
3501
gssize
3502
g_socket_send (GSocket       *socket,
3503
         const gchar   *buffer,
3504
         gsize          size,
3505
         GCancellable  *cancellable,
3506
         GError       **error)
3507
0
{
3508
0
  return g_socket_send_with_blocking (socket, buffer, size,
3509
0
              socket->priv->blocking,
3510
0
              cancellable, error);
3511
0
}
3512
3513
/**
3514
 * g_socket_send_with_blocking:
3515
 * @socket: a #GSocket
3516
 * @buffer: (array length=size) (element-type guint8): the buffer
3517
 *     containing the data to send.
3518
 * @size: the number of bytes to send
3519
 * @blocking: whether to do blocking or non-blocking I/O
3520
 * @cancellable: (nullable): a %GCancellable or %NULL
3521
 * @error: #GError for error reporting, or %NULL to ignore.
3522
 *
3523
 * This behaves exactly the same as g_socket_send(), except that
3524
 * the choice of blocking or non-blocking behavior is determined by
3525
 * the @blocking argument rather than by @socket's properties.
3526
 *
3527
 * Returns: Number of bytes written (which may be less than @size), or -1
3528
 * on error
3529
 *
3530
 * Since: 2.26
3531
 */
3532
gssize
3533
g_socket_send_with_blocking (GSocket       *socket,
3534
           const gchar   *buffer,
3535
           gsize          size,
3536
           gboolean       blocking,
3537
           GCancellable  *cancellable,
3538
           GError       **error)
3539
0
{
3540
0
  return g_socket_send_with_timeout (socket, (const guint8 *) buffer, size,
3541
0
                                     blocking ? -1 : 0, cancellable, error);
3542
0
}
3543
3544
/**
3545
 * g_socket_send_to:
3546
 * @socket: a #GSocket
3547
 * @address: (nullable): a #GSocketAddress, or %NULL
3548
 * @buffer: (array length=size) (element-type guint8): the buffer
3549
 *     containing the data to send.
3550
 * @size: the number of bytes to send
3551
 * @cancellable: (nullable): a %GCancellable or %NULL
3552
 * @error: #GError for error reporting, or %NULL to ignore.
3553
 *
3554
 * Tries to send @size bytes from @buffer to @address. If @address is
3555
 * %NULL then the message is sent to the default receiver (set by
3556
 * g_socket_connect()).
3557
 *
3558
 * See g_socket_send() for additional information.
3559
 *
3560
 * Returns: Number of bytes written (which may be less than @size), or -1
3561
 * on error
3562
 *
3563
 * Since: 2.22
3564
 */
3565
gssize
3566
g_socket_send_to (GSocket         *socket,
3567
      GSocketAddress  *address,
3568
      const gchar     *buffer,
3569
      gsize            size,
3570
      GCancellable    *cancellable,
3571
      GError         **error)
3572
0
{
3573
0
  GOutputVector v;
3574
3575
0
  v.buffer = buffer;
3576
0
  v.size = size;
3577
3578
0
  return g_socket_send_message (socket,
3579
0
        address,
3580
0
        &v, 1,
3581
0
        NULL, 0,
3582
0
        0,
3583
0
        cancellable,
3584
0
        error);
3585
0
}
3586
3587
/**
3588
 * g_socket_shutdown:
3589
 * @socket: a #GSocket
3590
 * @shutdown_read: whether to shut down the read side
3591
 * @shutdown_write: whether to shut down the write side
3592
 * @error: #GError for error reporting, or %NULL to ignore.
3593
 *
3594
 * Shut down part or all of a full-duplex connection.
3595
 *
3596
 * If @shutdown_read is %TRUE then the receiving side of the connection
3597
 * is shut down, and further reading is disallowed.
3598
 *
3599
 * If @shutdown_write is %TRUE then the sending side of the connection
3600
 * is shut down, and further writing is disallowed.
3601
 *
3602
 * It is allowed for both @shutdown_read and @shutdown_write to be %TRUE.
3603
 *
3604
 * One example where it is useful to shut down only one side of a connection is
3605
 * graceful disconnect for TCP connections where you close the sending side,
3606
 * then wait for the other side to close the connection, thus ensuring that the
3607
 * other side saw all sent data.
3608
 *
3609
 * Returns: %TRUE on success, %FALSE on error
3610
 *
3611
 * Since: 2.22
3612
 */
3613
gboolean
3614
g_socket_shutdown (GSocket   *socket,
3615
       gboolean   shutdown_read,
3616
       gboolean   shutdown_write,
3617
       GError   **error)
3618
0
{
3619
0
  int how;
3620
3621
0
  g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3622
3623
0
  if (!check_socket (socket, error))
3624
0
    return FALSE;
3625
3626
  /* Do nothing? */
3627
0
  if (!shutdown_read && !shutdown_write)
3628
0
    return TRUE;
3629
3630
0
#ifndef G_OS_WIN32
3631
0
  if (shutdown_read && shutdown_write)
3632
0
    how = SHUT_RDWR;
3633
0
  else if (shutdown_read)
3634
0
    how = SHUT_RD;
3635
0
  else
3636
0
    how = SHUT_WR;
3637
#else
3638
  if (shutdown_read && shutdown_write)
3639
    how = SD_BOTH;
3640
  else if (shutdown_read)
3641
    how = SD_RECEIVE;
3642
  else
3643
    how = SD_SEND;
3644
#endif
3645
3646
0
  if (shutdown (socket->priv->fd, how) != 0)
3647
0
    {
3648
0
      int errsv = get_socket_errno ();
3649
0
      g_set_error (error, G_IO_ERROR, socket_io_error_from_errno (errsv),
3650
0
       _("Unable to shutdown socket: %s"), socket_strerror (errsv));
3651
0
      return FALSE;
3652
0
    }
3653
3654
0
  if (shutdown_read)
3655
0
    socket->priv->connected_read = FALSE;
3656
0
  if (shutdown_write)
3657
0
    socket->priv->connected_write = FALSE;
3658
3659
0
  return TRUE;
3660
0
}
3661
3662
/**
3663
 * g_socket_close:
3664
 * @socket: a #GSocket
3665
 * @error: #GError for error reporting, or %NULL to ignore.
3666
 *
3667
 * Closes the socket, shutting down any active connection.
3668
 *
3669
 * Closing a socket does not wait for all outstanding I/O operations
3670
 * to finish, so the caller should not rely on them to be guaranteed
3671
 * to complete even if the close returns with no error.
3672
 *
3673
 * Once the socket is closed, all other operations will return
3674
 * %G_IO_ERROR_CLOSED. Closing a socket multiple times will not
3675
 * return an error.
3676
 *
3677
 * Sockets will be automatically closed when the last reference
3678
 * is dropped, but you might want to call this function to make sure
3679
 * resources are released as early as possible.
3680
 *
3681
 * Beware that due to the way that TCP works, it is possible for
3682
 * recently-sent data to be lost if either you close a socket while the
3683
 * %G_IO_IN condition is set, or else if the remote connection tries to
3684
 * send something to you after you close the socket but before it has
3685
 * finished reading all of the data you sent. There is no easy generic
3686
 * way to avoid this problem; the easiest fix is to design the network
3687
 * protocol such that the client will never send data "out of turn".
3688
 * Another solution is for the server to half-close the connection by
3689
 * calling g_socket_shutdown() with only the @shutdown_write flag set,
3690
 * and then wait for the client to notice this and close its side of the
3691
 * connection, after which the server can safely call g_socket_close().
3692
 * (This is what #GTcpConnection does if you call
3693
 * g_tcp_connection_set_graceful_disconnect(). But of course, this
3694
 * only works if the client will close its connection after the server
3695
 * does.)
3696
 *
3697
 * Returns: %TRUE on success, %FALSE on error
3698
 *
3699
 * Since: 2.22
3700
 */
3701
gboolean
3702
g_socket_close (GSocket  *socket,
3703
    GError  **error)
3704
0
{
3705
0
  int res;
3706
3707
0
  g_return_val_if_fail (G_IS_SOCKET (socket), TRUE);
3708
3709
0
  if (socket->priv->closed)
3710
0
    return TRUE; /* Multiple close not an error */
3711
3712
0
  if (!check_socket (socket, error))
3713
0
    return FALSE;
3714
3715
0
  while (1)
3716
0
    {
3717
#ifdef G_OS_WIN32
3718
      res = closesocket (socket->priv->fd);
3719
#else
3720
0
      res = close (socket->priv->fd);
3721
0
#endif
3722
0
      if (res == -1)
3723
0
  {
3724
0
    int errsv = get_socket_errno ();
3725
3726
0
    if (errsv == EINTR)
3727
0
      continue;
3728
3729
0
    g_set_error (error, G_IO_ERROR,
3730
0
           socket_io_error_from_errno (errsv),
3731
0
           _("Error closing socket: %s"),
3732
0
           socket_strerror (errsv));
3733
0
    return FALSE;
3734
0
  }
3735
0
      break;
3736
0
    }
3737
3738
0
  socket->priv->fd = -1;
3739
0
  socket->priv->connected_read = FALSE;
3740
0
  socket->priv->connected_write = FALSE;
3741
0
  socket->priv->closed = TRUE;
3742
0
  if (socket->priv->remote_address)
3743
0
    {
3744
0
      g_object_unref (socket->priv->remote_address);
3745
0
      socket->priv->remote_address = NULL;
3746
0
    }
3747
3748
0
  return TRUE;
3749
0
}
3750
3751
/**
3752
 * g_socket_is_closed:
3753
 * @socket: a #GSocket
3754
 *
3755
 * Checks whether a socket is closed.
3756
 *
3757
 * Returns: %TRUE if socket is closed, %FALSE otherwise
3758
 *
3759
 * Since: 2.22
3760
 */
3761
gboolean
3762
g_socket_is_closed (GSocket *socket)
3763
0
{
3764
0
  return socket->priv->closed;
3765
0
}
3766
3767
/* Broken source, used on errors */
3768
static gboolean
3769
broken_dispatch (GSource     *source,
3770
     GSourceFunc  callback,
3771
     gpointer     user_data)
3772
0
{
3773
0
  return TRUE;
3774
0
}
3775
3776
static GSourceFuncs broken_funcs =
3777
{
3778
  NULL,
3779
  NULL,
3780
  broken_dispatch,
3781
  NULL,
3782
  NULL,
3783
  NULL,
3784
};
3785
3786
#ifdef G_OS_WIN32
3787
static gint
3788
network_events_for_condition (GIOCondition condition)
3789
{
3790
  int event_mask = 0;
3791
3792
  if (condition & G_IO_IN)
3793
    event_mask |= (FD_READ | FD_ACCEPT);
3794
  if (condition & G_IO_OUT)
3795
    event_mask |= (FD_WRITE | FD_CONNECT);
3796
  event_mask |= FD_CLOSE;
3797
3798
  return event_mask;
3799
}
3800
3801
static void
3802
ensure_event (GSocket *socket)
3803
{
3804
  if (socket->priv->event == WSA_INVALID_EVENT)
3805
    socket->priv->event = WSACreateEvent();
3806
}
3807
3808
static void
3809
update_select_events (GSocket *socket)
3810
{
3811
  int event_mask;
3812
  GIOCondition *ptr;
3813
  GList *l;
3814
  WSAEVENT event;
3815
3816
  if (socket->priv->closed)
3817
    return;
3818
3819
  ensure_event (socket);
3820
3821
  event_mask = 0;
3822
  for (l = socket->priv->requested_conditions; l != NULL; l = l->next)
3823
    {
3824
      ptr = l->data;
3825
      event_mask |= network_events_for_condition (*ptr);
3826
    }
3827
3828
  if (event_mask != socket->priv->selected_events)
3829
    {
3830
      /* If no events selected, disable event so we can unset
3831
   nonblocking mode */
3832
3833
      if (event_mask == 0)
3834
  event = NULL;
3835
      else
3836
  event = socket->priv->event;
3837
3838
      if (WSAEventSelect (socket->priv->fd, event, event_mask) == 0)
3839
  socket->priv->selected_events = event_mask;
3840
    }
3841
}
3842
3843
static void
3844
add_condition_watch (GSocket      *socket,
3845
         GIOCondition *condition)
3846
{
3847
  g_mutex_lock (&socket->priv->win32_source_lock);
3848
  g_assert (g_list_find (socket->priv->requested_conditions, condition) == NULL);
3849
3850
  socket->priv->requested_conditions =
3851
    g_list_prepend (socket->priv->requested_conditions, condition);
3852
3853
  update_select_events (socket);
3854
  g_mutex_unlock (&socket->priv->win32_source_lock);
3855
}
3856
3857
static void
3858
remove_condition_watch (GSocket      *socket,
3859
      GIOCondition *condition)
3860
{
3861
  g_mutex_lock (&socket->priv->win32_source_lock);
3862
  g_assert (g_list_find (socket->priv->requested_conditions, condition) != NULL);
3863
3864
  socket->priv->requested_conditions =
3865
    g_list_remove (socket->priv->requested_conditions, condition);
3866
3867
  update_select_events (socket);
3868
  g_mutex_unlock (&socket->priv->win32_source_lock);
3869
}
3870
3871
static GIOCondition
3872
update_condition_unlocked (GSocket *socket)
3873
{
3874
  WSANETWORKEVENTS events;
3875
  GIOCondition condition;
3876
3877
  if (!socket->priv->closed &&
3878
      WSAEnumNetworkEvents (socket->priv->fd,
3879
          socket->priv->event,
3880
          &events) == 0)
3881
    {
3882
      socket->priv->current_events |= events.lNetworkEvents;
3883
      if (events.lNetworkEvents & FD_WRITE &&
3884
    events.iErrorCode[FD_WRITE_BIT] != 0)
3885
  socket->priv->current_errors |= FD_WRITE;
3886
      if (events.lNetworkEvents & FD_CONNECT &&
3887
    events.iErrorCode[FD_CONNECT_BIT] != 0)
3888
  socket->priv->current_errors |= FD_CONNECT;
3889
    }
3890
3891
  condition = 0;
3892
  if (socket->priv->current_events & (FD_READ | FD_ACCEPT))
3893
    condition |= G_IO_IN;
3894
3895
  if (socket->priv->current_events & FD_CLOSE)
3896
    {
3897
      int r, errsv = NO_ERROR, buffer;
3898
3899
      r = recv (socket->priv->fd, &buffer, sizeof (buffer), MSG_PEEK);
3900
      if (r < 0)
3901
          errsv = get_socket_errno ();
3902
3903
      if (r > 0 ||
3904
          (r < 0 && errsv == WSAENOTCONN))
3905
        condition |= G_IO_IN;
3906
      else if (r == 0 ||
3907
               (r < 0 && (errsv == WSAESHUTDOWN || errsv == WSAECONNRESET ||
3908
                          errsv == WSAECONNABORTED || errsv == WSAENETRESET)))
3909
        condition |= G_IO_HUP;
3910
      else
3911
        condition |= G_IO_ERR;
3912
    }
3913
3914
  if (socket->priv->closed)
3915
    condition |= G_IO_HUP;
3916
3917
  /* Never report both G_IO_OUT and HUP, these are
3918
     mutually exclusive (can't write to a closed socket) */
3919
  if ((condition & G_IO_HUP) == 0 &&
3920
      socket->priv->current_events & FD_WRITE)
3921
    {
3922
      if (socket->priv->current_errors & FD_WRITE)
3923
  condition |= G_IO_ERR;
3924
      else
3925
  condition |= G_IO_OUT;
3926
    }
3927
  else
3928
    {
3929
      if (socket->priv->current_events & FD_CONNECT)
3930
  {
3931
    if (socket->priv->current_errors & FD_CONNECT)
3932
      condition |= (G_IO_HUP | G_IO_ERR);
3933
    else
3934
      condition |= G_IO_OUT;
3935
  }
3936
    }
3937
3938
  return condition;
3939
}
3940
3941
static GIOCondition
3942
update_condition (GSocket *socket)
3943
{
3944
  GIOCondition res;
3945
  g_mutex_lock (&socket->priv->win32_source_lock);
3946
  res = update_condition_unlocked (socket);
3947
  g_mutex_unlock (&socket->priv->win32_source_lock);
3948
  return res;
3949
}
3950
#endif
3951
3952
typedef struct {
3953
  GSource       source;
3954
#ifdef G_OS_WIN32
3955
  GPollFD       pollfd;
3956
#else
3957
  gpointer      fd_tag;
3958
#endif
3959
  GSocket      *socket;
3960
  GIOCondition  condition;
3961
} GSocketSource;
3962
3963
static gboolean
3964
socket_source_prepare (GSource *source,
3965
                       gint    *timeout)
3966
0
{
3967
0
  GSocketSource *socket_source = (GSocketSource *)source;
3968
3969
0
  *timeout = -1;
3970
3971
#ifdef G_OS_WIN32
3972
  if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
3973
    return TRUE;
3974
3975
  if (g_socket_is_closed (socket_source->socket))
3976
    {
3977
      g_source_remove_poll (source, &socket_source->pollfd);
3978
      socket_source->pollfd.revents = G_IO_NVAL;
3979
      return TRUE;
3980
    }
3981
3982
  return (update_condition (socket_source->socket) & socket_source->condition) != 0;
3983
#else
3984
0
  return g_socket_is_closed (socket_source->socket) && socket_source->fd_tag != NULL;
3985
0
#endif
3986
0
}
3987
3988
#ifdef G_OS_WIN32
3989
static gboolean
3990
socket_source_check_win32 (GSource *source)
3991
{
3992
  int timeout;
3993
3994
  return socket_source_prepare (source, &timeout);
3995
}
3996
#endif
3997
3998
static gboolean
3999
socket_source_dispatch (GSource     *source,
4000
      GSourceFunc  callback,
4001
      gpointer     user_data)
4002
0
{
4003
0
  GSocketSourceFunc func = (GSocketSourceFunc)callback;
4004
0
  GSocketSource *socket_source = (GSocketSource *)source;
4005
0
  GSocket *socket = socket_source->socket;
4006
0
  gint64 timeout;
4007
0
  guint events;
4008
0
  gboolean ret;
4009
4010
#ifdef G_OS_WIN32
4011
  if ((socket_source->pollfd.revents & G_IO_NVAL) != 0)
4012
    events = G_IO_NVAL;
4013
  else
4014
    events = update_condition (socket_source->socket);
4015
#else
4016
0
  if (g_socket_is_closed (socket_source->socket))
4017
0
    {
4018
0
      if (socket_source->fd_tag)
4019
0
        g_source_remove_unix_fd (source, socket_source->fd_tag);
4020
0
      socket_source->fd_tag = NULL;
4021
0
      events = G_IO_NVAL;
4022
0
    }
4023
0
  else
4024
0
    {
4025
0
      events = g_source_query_unix_fd (source, socket_source->fd_tag);
4026
0
    }
4027
0
#endif
4028
4029
0
  timeout = g_source_get_ready_time (source);
4030
0
  if (timeout >= 0 && timeout < g_source_get_time (source) &&
4031
0
      !g_socket_is_closed (socket_source->socket))
4032
0
    {
4033
0
      socket->priv->timed_out = TRUE;
4034
0
      events |= (G_IO_IN | G_IO_OUT);
4035
0
    }
4036
4037
0
  ret = (*func) (socket, events & socket_source->condition, user_data);
4038
4039
0
  if (socket->priv->timeout && !g_socket_is_closed (socket_source->socket))
4040
0
    g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4041
0
  else
4042
0
    g_source_set_ready_time (source, -1);
4043
4044
0
  return ret;
4045
0
}
4046
4047
static void
4048
socket_source_finalize (GSource *source)
4049
0
{
4050
0
  GSocketSource *socket_source = (GSocketSource *)source;
4051
0
  GSocket *socket;
4052
4053
0
  socket = socket_source->socket;
4054
4055
#ifdef G_OS_WIN32
4056
  remove_condition_watch (socket, &socket_source->condition);
4057
#endif
4058
4059
0
  g_object_unref (socket);
4060
0
}
4061
4062
static gboolean
4063
socket_source_closure_callback (GSocket      *socket,
4064
        GIOCondition  condition,
4065
        gpointer      data)
4066
0
{
4067
0
  GClosure *closure = data;
4068
4069
0
  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
4070
0
  GValue result_value = G_VALUE_INIT;
4071
0
  gboolean result;
4072
4073
0
  g_value_init (&result_value, G_TYPE_BOOLEAN);
4074
4075
0
  g_value_init (&params[0], G_TYPE_SOCKET);
4076
0
  g_value_set_object (&params[0], socket);
4077
0
  g_value_init (&params[1], G_TYPE_IO_CONDITION);
4078
0
  g_value_set_flags (&params[1], condition);
4079
4080
0
  g_closure_invoke (closure, &result_value, 2, params, NULL);
4081
4082
0
  result = g_value_get_boolean (&result_value);
4083
0
  g_value_unset (&result_value);
4084
0
  g_value_unset (&params[0]);
4085
0
  g_value_unset (&params[1]);
4086
4087
0
  return result;
4088
0
}
4089
4090
static GSourceFuncs socket_source_funcs =
4091
{
4092
  socket_source_prepare,
4093
#ifdef G_OS_WIN32
4094
  socket_source_check_win32,
4095
#else
4096
  NULL,
4097
#endif
4098
  socket_source_dispatch,
4099
  socket_source_finalize,
4100
  (GSourceFunc)socket_source_closure_callback,
4101
  NULL,
4102
};
4103
4104
static GSource *
4105
socket_source_new (GSocket      *socket,
4106
       GIOCondition  condition,
4107
       GCancellable *cancellable)
4108
0
{
4109
0
  GSource *source;
4110
0
  GSocketSource *socket_source;
4111
4112
#ifdef G_OS_WIN32
4113
  ensure_event (socket);
4114
4115
  if (socket->priv->event == WSA_INVALID_EVENT)
4116
    {
4117
      g_warning ("Failed to create WSAEvent");
4118
      return g_source_new (&broken_funcs, sizeof (GSource));
4119
    }
4120
#endif
4121
4122
0
  if (!check_socket (socket, NULL))
4123
0
    {
4124
0
      g_warning ("Socket check failed");
4125
0
      return g_source_new (&broken_funcs, sizeof (GSource));
4126
0
    }
4127
4128
0
  condition |= G_IO_HUP | G_IO_ERR | G_IO_NVAL;
4129
4130
0
  source = g_source_new (&socket_source_funcs, sizeof (GSocketSource));
4131
0
  g_source_set_static_name (source, "GSocket");
4132
0
  socket_source = (GSocketSource *)source;
4133
4134
0
  socket_source->socket = g_object_ref (socket);
4135
0
  socket_source->condition = condition;
4136
4137
0
  if (cancellable)
4138
0
    {
4139
0
      GSource *cancellable_source;
4140
4141
0
      cancellable_source = g_cancellable_source_new (cancellable);
4142
0
      g_source_add_child_source (source, cancellable_source);
4143
0
      g_source_set_dummy_callback (cancellable_source);
4144
0
      g_source_unref (cancellable_source);
4145
0
    }
4146
4147
#ifdef G_OS_WIN32
4148
  add_condition_watch (socket, &socket_source->condition);
4149
  socket_source->pollfd.fd = (gintptr) socket->priv->event;
4150
  socket_source->pollfd.events = condition;
4151
  socket_source->pollfd.revents = 0;
4152
  g_source_add_poll (source, &socket_source->pollfd);
4153
#else
4154
0
  socket_source->fd_tag = g_source_add_unix_fd (source, socket->priv->fd, condition);
4155
0
#endif
4156
4157
0
  if (socket->priv->timeout)
4158
0
    g_source_set_ready_time (source, g_get_monotonic_time () + socket->priv->timeout * 1000000);
4159
0
  else
4160
0
    g_source_set_ready_time (source, -1);
4161
4162
0
  return source;
4163
0
}
4164
4165
/**
4166
 * g_socket_create_source: (skip)
4167
 * @socket: a #GSocket
4168
 * @condition: a #GIOCondition mask to monitor
4169
 * @cancellable: (nullable): a %GCancellable or %NULL
4170
 *
4171
 * Creates a #GSource that can be attached to a %GMainContext to monitor
4172
 * for the availability of the specified @condition on the socket. The #GSource
4173
 * keeps a reference to the @socket.
4174
 *
4175
 * The callback on the source is of the #GSocketSourceFunc type.
4176
 *
4177
 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in @condition;
4178
 * these conditions will always be reported output if they are true.
4179
 *
4180
 * @cancellable if not %NULL can be used to cancel the source, which will
4181
 * cause the source to trigger, reporting the current condition (which
4182
 * is likely 0 unless cancellation happened at the same time as a
4183
 * condition change). You can check for this in the callback using
4184
 * g_cancellable_is_cancelled().
4185
 *
4186
 * If @socket has a timeout set, and it is reached before @condition
4187
 * occurs, the source will then trigger anyway, reporting %G_IO_IN or
4188
 * %G_IO_OUT depending on @condition. However, @socket will have been
4189
 * marked as having had a timeout, and so the next #GSocket I/O method
4190
 * you call will then fail with a %G_IO_ERROR_TIMED_OUT.
4191
 *
4192
 * Returns: (transfer full): a newly allocated %GSource, free with g_source_unref().
4193
 *
4194
 * Since: 2.22
4195
 */
4196
GSource *
4197
g_socket_create_source (GSocket      *socket,
4198
      GIOCondition  condition,
4199
      GCancellable *cancellable)
4200
0
{
4201
0
  g_return_val_if_fail (G_IS_SOCKET (socket) && (cancellable == NULL || G_IS_CANCELLABLE (cancellable)), NULL);
4202
4203
0
  return socket_source_new (socket, condition, cancellable);
4204
0
}
4205
4206
/**
4207
 * g_socket_condition_check:
4208
 * @socket: a #GSocket
4209
 * @condition: a #GIOCondition mask to check
4210
 *
4211
 * Checks on the readiness of @socket to perform operations.
4212
 * The operations specified in @condition are checked for and masked
4213
 * against the currently-satisfied conditions on @socket. The result
4214
 * is returned.
4215
 *
4216
 * Note that on Windows, it is possible for an operation to return
4217
 * %G_IO_ERROR_WOULD_BLOCK even immediately after
4218
 * g_socket_condition_check() has claimed that the socket is ready for
4219
 * writing. Rather than calling g_socket_condition_check() and then
4220
 * writing to the socket if it succeeds, it is generally better to
4221
 * simply try writing to the socket right away, and try again later if
4222
 * the initial attempt returns %G_IO_ERROR_WOULD_BLOCK.
4223
 *
4224
 * It is meaningless to specify %G_IO_ERR or %G_IO_HUP in condition;
4225
 * these conditions will always be set in the output if they are true.
4226
 *
4227
 * This call never blocks.
4228
 *
4229
 * Returns: the @GIOCondition mask of the current state
4230
 *
4231
 * Since: 2.22
4232
 */
4233
GIOCondition
4234
g_socket_condition_check (GSocket      *socket,
4235
        GIOCondition  condition)
4236
0
{
4237
0
  g_return_val_if_fail (G_IS_SOCKET (socket), 0);
4238
4239
0
  if (!check_socket (socket, NULL))
4240
0
    return 0;
4241
4242
#ifdef G_OS_WIN32
4243
  {
4244
    GIOCondition current_condition;
4245
4246
    condition |= G_IO_ERR | G_IO_HUP;
4247
4248
    add_condition_watch (socket, &condition);
4249
    current_condition = update_condition (socket);
4250
    remove_condition_watch (socket, &condition);
4251
    return condition & current_condition;
4252
  }
4253
#else
4254
0
  {
4255
0
    GPollFD poll_fd;
4256
0
    gint result;
4257
0
    poll_fd.fd = socket->priv->fd;
4258
0
    poll_fd.events = condition;
4259
0
    poll_fd.revents = 0;
4260
4261
0
    do
4262
0
      result = g_poll (&poll_fd, 1, 0);
4263
0
    while (result == -1 && get_socket_errno () == EINTR);
4264
4265
0
    return poll_fd.revents;
4266
0
  }
4267
0
#endif
4268
0
}
4269
4270
/**
4271
 * g_socket_condition_wait:
4272
 * @socket: a #GSocket
4273
 * @condition: a #GIOCondition mask to wait for
4274
 * @cancellable: (nullable): a #GCancellable, or %NULL
4275
 * @error: a #GError pointer, or %NULL
4276
 *
4277
 * Waits for @condition to become true on @socket. When the condition
4278
 * is met, %TRUE is returned.
4279
 *
4280
 * If @cancellable is cancelled before the condition is met, or if the
4281
 * socket has a timeout set and it is reached before the condition is
4282
 * met, then %FALSE is returned and @error, if non-%NULL, is set to
4283
 * the appropriate value (%G_IO_ERROR_CANCELLED or
4284
 * %G_IO_ERROR_TIMED_OUT).
4285
 *
4286
 * See also g_socket_condition_timed_wait().
4287
 *
4288
 * Returns: %TRUE if the condition was met, %FALSE otherwise
4289
 *
4290
 * Since: 2.22
4291
 */
4292
gboolean
4293
g_socket_condition_wait (GSocket       *socket,
4294
       GIOCondition   condition,
4295
       GCancellable  *cancellable,
4296
       GError       **error)
4297
0
{
4298
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4299
4300
0
  return g_socket_condition_timed_wait (socket, condition, -1,
4301
0
          cancellable, error);
4302
0
}
4303
4304
/**
4305
 * g_socket_condition_timed_wait:
4306
 * @socket: a #GSocket
4307
 * @condition: a #GIOCondition mask to wait for
4308
 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4309
 * @cancellable: (nullable): a #GCancellable, or %NULL
4310
 * @error: a #GError pointer, or %NULL
4311
 *
4312
 * Waits for up to @timeout_us microseconds for @condition to become true
4313
 * on @socket. If the condition is met, %TRUE is returned.
4314
 *
4315
 * If @cancellable is cancelled before the condition is met, or if
4316
 * @timeout_us (or the socket's #GSocket:timeout) is reached before the
4317
 * condition is met, then %FALSE is returned and @error, if non-%NULL,
4318
 * is set to the appropriate value (%G_IO_ERROR_CANCELLED or
4319
 * %G_IO_ERROR_TIMED_OUT).
4320
 *
4321
 * If you don't want a timeout, use g_socket_condition_wait().
4322
 * (Alternatively, you can pass -1 for @timeout_us.)
4323
 *
4324
 * Note that although @timeout_us is in microseconds for consistency with
4325
 * other GLib APIs, this function actually only has millisecond
4326
 * resolution, and the behavior is undefined if @timeout_us is not an
4327
 * exact number of milliseconds.
4328
 *
4329
 * Returns: %TRUE if the condition was met, %FALSE otherwise
4330
 *
4331
 * Since: 2.32
4332
 */
4333
gboolean
4334
g_socket_condition_timed_wait (GSocket       *socket,
4335
             GIOCondition   condition,
4336
             gint64         timeout_us,
4337
             GCancellable  *cancellable,
4338
             GError       **error)
4339
0
{
4340
0
  gint64 start_time;
4341
0
  gint64 timeout_ms;
4342
4343
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
4344
4345
0
  if (!check_socket (socket, error))
4346
0
    return FALSE;
4347
4348
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
4349
0
    return FALSE;
4350
4351
0
  if (socket->priv->timeout &&
4352
0
      (timeout_us < 0 || socket->priv->timeout < timeout_us / G_USEC_PER_SEC))
4353
0
    timeout_ms = (gint64) socket->priv->timeout * 1000;
4354
0
  else if (timeout_us != -1)
4355
0
    timeout_ms = timeout_us / 1000;
4356
0
  else
4357
0
    timeout_ms = -1;
4358
4359
0
  start_time = g_get_monotonic_time ();
4360
4361
#ifdef G_OS_WIN32
4362
  {
4363
    GIOCondition current_condition;
4364
    WSAEVENT events[2];
4365
    DWORD res;
4366
    GPollFD cancel_fd;
4367
    int num_events;
4368
4369
    /* Always check these */
4370
    condition |=  G_IO_ERR | G_IO_HUP;
4371
4372
    add_condition_watch (socket, &condition);
4373
4374
    num_events = 0;
4375
    events[num_events++] = socket->priv->event;
4376
4377
    if (g_cancellable_make_pollfd (cancellable, &cancel_fd))
4378
      events[num_events++] = (WSAEVENT)cancel_fd.fd;
4379
4380
    if (timeout_ms == -1)
4381
      timeout_ms = WSA_INFINITE;
4382
4383
    g_mutex_lock (&socket->priv->win32_source_lock);
4384
    current_condition = update_condition_unlocked (socket);
4385
    while ((condition & current_condition) == 0)
4386
      {
4387
        if (!socket->priv->waiting)
4388
          {
4389
            socket->priv->waiting = TRUE;
4390
            socket->priv->waiting_result = 0;
4391
            g_mutex_unlock (&socket->priv->win32_source_lock);
4392
4393
            res = WSAWaitForMultipleEvents (num_events, events, FALSE, timeout_ms, FALSE);
4394
4395
            g_mutex_lock (&socket->priv->win32_source_lock);
4396
            socket->priv->waiting = FALSE;
4397
            socket->priv->waiting_result = res;
4398
            g_cond_broadcast (&socket->priv->win32_source_cond);
4399
          }
4400
        else
4401
          {
4402
            if (timeout_ms != WSA_INFINITE)
4403
              {
4404
                if (!g_cond_wait_until (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock, timeout_ms))
4405
                  {
4406
                    res = WSA_WAIT_TIMEOUT;
4407
                    break;
4408
                  }
4409
                else
4410
                  {
4411
                    res = socket->priv->waiting_result;
4412
                  }
4413
              }
4414
            else
4415
              {
4416
                g_cond_wait (&socket->priv->win32_source_cond, &socket->priv->win32_source_lock);
4417
                res = socket->priv->waiting_result;
4418
              }
4419
          }
4420
4421
  if (res == WSA_WAIT_FAILED)
4422
    {
4423
      int errsv = get_socket_errno ();
4424
4425
      g_set_error (error, G_IO_ERROR,
4426
       socket_io_error_from_errno (errsv),
4427
       _("Waiting for socket condition: %s"),
4428
       socket_strerror (errsv));
4429
      break;
4430
    }
4431
  else if (res == WSA_WAIT_TIMEOUT)
4432
    {
4433
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4434
         _("Socket I/O timed out"));
4435
      break;
4436
    }
4437
4438
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
4439
    break;
4440
4441
        current_condition = update_condition_unlocked (socket);
4442
4443
  if (timeout_ms != WSA_INFINITE)
4444
    {
4445
      timeout_ms -= (g_get_monotonic_time () - start_time) * 1000;
4446
      if (timeout_ms < 0)
4447
        timeout_ms = 0;
4448
    }
4449
      }
4450
    g_mutex_unlock (&socket->priv->win32_source_lock);
4451
    remove_condition_watch (socket, &condition);
4452
    if (num_events > 1)
4453
      g_cancellable_release_fd (cancellable);
4454
4455
    return (condition & current_condition) != 0;
4456
  }
4457
#else
4458
0
  {
4459
0
    GPollFD poll_fd[2];
4460
0
    gint result;
4461
0
    gint num;
4462
4463
0
    poll_fd[0].fd = socket->priv->fd;
4464
0
    poll_fd[0].events = condition;
4465
0
    num = 1;
4466
4467
0
    if (g_cancellable_make_pollfd (cancellable, &poll_fd[1]))
4468
0
      num++;
4469
4470
0
    while (TRUE)
4471
0
      {
4472
0
  int errsv;
4473
0
  result = g_poll (poll_fd, num, timeout_ms);
4474
0
  errsv = errno;
4475
0
  if (result != -1 || errsv != EINTR)
4476
0
    break;
4477
4478
0
  if (timeout_ms != -1)
4479
0
    {
4480
0
      timeout_ms -= (g_get_monotonic_time () - start_time) / 1000;
4481
0
      if (timeout_ms < 0)
4482
0
        timeout_ms = 0;
4483
0
    }
4484
0
      }
4485
    
4486
0
    if (num > 1)
4487
0
      g_cancellable_release_fd (cancellable);
4488
4489
0
    if (result == 0)
4490
0
      {
4491
0
  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
4492
0
           _("Socket I/O timed out"));
4493
0
  return FALSE;
4494
0
      }
4495
4496
0
    return !g_cancellable_set_error_if_cancelled (cancellable, error);
4497
0
  }
4498
0
  #endif
4499
0
}
4500
4501
#ifndef G_OS_WIN32
4502
4503
#ifdef HAVE_QNX
4504
/* QNX has this weird upper limit, or at least used to back in the 6.x days.
4505
 * This was discovered empirically and doesn't appear to be mentioned in any
4506
 * of the official documentation. */
4507
# define G_SOCKET_CONTROL_BUFFER_SIZE_BYTES 2016
4508
#else
4509
0
# define G_SOCKET_CONTROL_BUFFER_SIZE_BYTES 2048
4510
#endif
4511
4512
/* Unfortunately these have to be macros rather than inline functions due to
4513
 * using alloca(). */
4514
0
#define output_message_to_msghdr(message, prev_message, msg, prev_msg, error) \
4515
0
G_STMT_START { \
4516
0
  const GOutputMessage  *_message = (message); \
4517
0
  const GOutputMessage *_prev_message = (prev_message); \
4518
0
  struct msghdr *_msg = (msg); \
4519
0
  const struct msghdr *_prev_msg = (prev_msg); \
4520
0
  GError **_error = (error); \
4521
0
 \
4522
0
  _msg->msg_flags = 0; \
4523
0
 \
4524
0
  /* name */ \
4525
0
  if (_prev_message != NULL && _prev_message->address == _message->address) \
4526
0
    { \
4527
0
      _msg->msg_name = _prev_msg->msg_name; \
4528
0
      _msg->msg_namelen = _prev_msg->msg_namelen; \
4529
0
    } \
4530
0
  else if (_message->address != NULL) \
4531
0
    { \
4532
0
      _msg->msg_namelen = g_socket_address_get_native_size (_message->address); \
4533
0
      _msg->msg_name = g_alloca (_msg->msg_namelen); \
4534
0
      if (!g_socket_address_to_native (_message->address, _msg->msg_name, \
4535
0
                                       _msg->msg_namelen, _error)) \
4536
0
        break; \
4537
0
    } \
4538
0
  else \
4539
0
    { \
4540
0
      _msg->msg_name = NULL; \
4541
0
      _msg->msg_namelen = 0; \
4542
0
    } \
4543
0
 \
4544
0
  /* iov */ \
4545
0
  { \
4546
0
    /* this entire expression will be evaluated at compile time */ \
4547
0
    if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4548
0
        sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4549
0
        G_STRUCT_OFFSET (struct iovec, iov_base) == \
4550
0
        G_STRUCT_OFFSET (GOutputVector, buffer) && \
4551
0
        sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4552
0
        G_STRUCT_OFFSET (struct iovec, iov_len) == \
4553
0
        G_STRUCT_OFFSET (GOutputVector, size)) \
4554
0
      /* ABI is compatible */ \
4555
0
      { \
4556
0
        _msg->msg_iov = (struct iovec *) _message->vectors; \
4557
0
        _msg->msg_iovlen = _message->num_vectors; \
4558
0
      } \
4559
0
    else \
4560
0
      /* ABI is incompatible */ \
4561
0
      { \
4562
0
        guint i; \
4563
0
 \
4564
0
        _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4565
0
        for (i = 0; i < _message->num_vectors; i++) \
4566
0
          { \
4567
0
            _msg->msg_iov[i].iov_base = (void *) _message->vectors[i].buffer; \
4568
0
            _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4569
0
          } \
4570
0
        _msg->msg_iovlen = _message->num_vectors; \
4571
0
      } \
4572
0
  } \
4573
0
 \
4574
0
  /* control */ \
4575
0
  { \
4576
0
    struct cmsghdr *cmsg; \
4577
0
    guint i; \
4578
0
 \
4579
0
    _msg->msg_controllen = 0; \
4580
0
    for (i = 0; i < _message->num_control_messages; i++) \
4581
0
      _msg->msg_controllen += CMSG_SPACE (g_socket_control_message_get_size (_message->control_messages[i])); \
4582
0
 \
4583
0
    if (_msg->msg_controllen == 0) \
4584
0
      _msg->msg_control = NULL; \
4585
0
    else \
4586
0
      { \
4587
0
        _msg->msg_control = g_alloca0 (_msg->msg_controllen); \
4588
0
      } \
4589
0
 \
4590
0
    cmsg = CMSG_FIRSTHDR (_msg); \
4591
0
    for (i = 0; i < _message->num_control_messages; i++) \
4592
0
      { \
4593
0
        cmsg->cmsg_level = g_socket_control_message_get_level (_message->control_messages[i]); \
4594
0
        cmsg->cmsg_type = g_socket_control_message_get_msg_type (_message->control_messages[i]); \
4595
0
        cmsg->cmsg_len = CMSG_LEN (g_socket_control_message_get_size (_message->control_messages[i])); \
4596
0
        g_socket_control_message_serialize (_message->control_messages[i], \
4597
0
                                            CMSG_DATA (cmsg)); \
4598
0
        cmsg = CMSG_NXTHDR (_msg, cmsg); \
4599
0
      } \
4600
0
    g_assert (cmsg == NULL); \
4601
0
  } \
4602
0
} G_STMT_END
4603
4604
0
#define input_message_to_msghdr(message, msg) \
4605
0
G_STMT_START { \
4606
0
  const GInputMessage  *_message = (message); \
4607
0
  struct msghdr *_msg = (msg); \
4608
0
 \
4609
0
  /* name */ \
4610
0
  if (_message->address) \
4611
0
    { \
4612
0
      _msg->msg_namelen = sizeof (struct sockaddr_storage); \
4613
0
      _msg->msg_name = g_alloca (_msg->msg_namelen); \
4614
0
    } \
4615
0
  else \
4616
0
    { \
4617
0
      _msg->msg_name = NULL; \
4618
0
      _msg->msg_namelen = 0; \
4619
0
    } \
4620
0
 \
4621
0
  /* iov */ \
4622
0
  /* this entire expression will be evaluated at compile time */ \
4623
0
  if (sizeof *_msg->msg_iov == sizeof *_message->vectors && \
4624
0
      sizeof _msg->msg_iov->iov_base == sizeof _message->vectors->buffer && \
4625
0
      G_STRUCT_OFFSET (struct iovec, iov_base) == \
4626
0
      G_STRUCT_OFFSET (GInputVector, buffer) && \
4627
0
      sizeof _msg->msg_iov->iov_len == sizeof _message->vectors->size && \
4628
0
      G_STRUCT_OFFSET (struct iovec, iov_len) == \
4629
0
      G_STRUCT_OFFSET (GInputVector, size)) \
4630
0
    /* ABI is compatible */ \
4631
0
    { \
4632
0
      _msg->msg_iov = (struct iovec *) _message->vectors; \
4633
0
      _msg->msg_iovlen = _message->num_vectors; \
4634
0
    } \
4635
0
  else \
4636
0
    /* ABI is incompatible */ \
4637
0
    { \
4638
0
      guint i; \
4639
0
 \
4640
0
      _msg->msg_iov = g_newa (struct iovec, _message->num_vectors); \
4641
0
      for (i = 0; i < _message->num_vectors; i++) \
4642
0
        { \
4643
0
          _msg->msg_iov[i].iov_base = _message->vectors[i].buffer; \
4644
0
          _msg->msg_iov[i].iov_len = _message->vectors[i].size; \
4645
0
        } \
4646
0
      _msg->msg_iovlen = _message->num_vectors; \
4647
0
    } \
4648
0
 \
4649
0
  /* control */ \
4650
0
  if (_message->control_messages == NULL) \
4651
0
    { \
4652
0
    _msg->msg_controllen = 0; \
4653
0
    _msg->msg_control = NULL; \
4654
0
    } \
4655
0
  else \
4656
0
    { \
4657
0
      _msg->msg_controllen = G_SOCKET_CONTROL_BUFFER_SIZE_BYTES; \
4658
0
      _msg->msg_control = g_alloca (_msg->msg_controllen); \
4659
0
    } \
4660
0
 \
4661
0
  /* flags */ \
4662
0
  _msg->msg_flags = _message->flags; \
4663
0
} G_STMT_END
4664
4665
static void
4666
input_message_from_msghdr (const struct msghdr  *msg,
4667
                           GInputMessage        *message,
4668
                           GSocket              *socket)
4669
0
{
4670
  /* decode address */
4671
0
  if (message->address != NULL)
4672
0
    {
4673
0
      *message->address = cache_recv_address (socket, msg->msg_name,
4674
0
                                              msg->msg_namelen);
4675
0
    }
4676
4677
  /* decode control messages */
4678
0
  {
4679
0
    GPtrArray *my_messages = NULL;
4680
0
    struct cmsghdr *cmsg;
4681
4682
0
    if (msg->msg_controllen >= sizeof (struct cmsghdr))
4683
0
      {
4684
0
        g_assert (message->control_messages != NULL);
4685
0
        for (cmsg = CMSG_FIRSTHDR (msg);
4686
0
             cmsg != NULL;
4687
0
             cmsg = CMSG_NXTHDR ((struct msghdr *) msg, cmsg))
4688
0
          {
4689
0
            GSocketControlMessage *control_message;
4690
4691
0
            control_message = g_socket_control_message_deserialize (cmsg->cmsg_level,
4692
0
                                                                    cmsg->cmsg_type,
4693
0
                                                                    cmsg->cmsg_len - ((char *)CMSG_DATA (cmsg) - (char *)cmsg),
4694
0
                                                                    CMSG_DATA (cmsg));
4695
0
            if (control_message == NULL)
4696
              /* We've already spewed about the problem in the
4697
                 deserialization code, so just continue */
4698
0
              continue;
4699
4700
0
            if (my_messages == NULL)
4701
0
              my_messages = g_ptr_array_new ();
4702
0
            g_ptr_array_add (my_messages, control_message);
4703
0
           }
4704
0
      }
4705
4706
0
    if (message->num_control_messages)
4707
0
      *message->num_control_messages = my_messages != NULL ? my_messages->len : 0;
4708
4709
0
    if (message->control_messages)
4710
0
      {
4711
0
        if (my_messages == NULL)
4712
0
          {
4713
0
            *message->control_messages = NULL;
4714
0
          }
4715
0
        else
4716
0
          {
4717
0
            g_ptr_array_add (my_messages, NULL);
4718
0
            *message->control_messages = (GSocketControlMessage **) g_ptr_array_free (my_messages, FALSE);
4719
0
          }
4720
0
      }
4721
0
    else
4722
0
      {
4723
0
        g_assert (my_messages == NULL);
4724
0
      }
4725
0
  }
4726
4727
  /* capture the flags */
4728
0
  message->flags = msg->msg_flags;
4729
0
}
4730
#endif
4731
4732
/**
4733
 * g_socket_send_message:
4734
 * @socket: a #GSocket
4735
 * @address: (nullable): a #GSocketAddress, or %NULL
4736
 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4737
 * @num_vectors: the number of elements in @vectors, or -1
4738
 * @messages: (array length=num_messages) (nullable): a pointer to an
4739
 *   array of #GSocketControlMessages, or %NULL.
4740
 * @num_messages: number of elements in @messages, or -1.
4741
 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4742
 *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4743
 * @cancellable: (nullable): a %GCancellable or %NULL
4744
 * @error: #GError for error reporting, or %NULL to ignore.
4745
 *
4746
 * Send data to @address on @socket.  For sending multiple messages see
4747
 * g_socket_send_messages(); for easier use, see
4748
 * g_socket_send() and g_socket_send_to().
4749
 *
4750
 * If @address is %NULL then the message is sent to the default receiver
4751
 * (set by g_socket_connect()).
4752
 *
4753
 * @vectors must point to an array of #GOutputVector structs and
4754
 * @num_vectors must be the length of this array. (If @num_vectors is -1,
4755
 * then @vectors is assumed to be terminated by a #GOutputVector with a
4756
 * %NULL buffer pointer.) The #GOutputVector structs describe the buffers
4757
 * that the sent data will be gathered from. Using multiple
4758
 * #GOutputVectors is more memory-efficient than manually copying
4759
 * data from multiple sources into a single buffer, and more
4760
 * network-efficient than making multiple calls to g_socket_send().
4761
 *
4762
 * @messages, if non-%NULL, is taken to point to an array of @num_messages
4763
 * #GSocketControlMessage instances. These correspond to the control
4764
 * messages to be sent on the socket.
4765
 * If @num_messages is -1 then @messages is treated as a %NULL-terminated
4766
 * array.
4767
 *
4768
 * @flags modify how the message is sent. The commonly available arguments
4769
 * for this are available in the #GSocketMsgFlags enum, but the
4770
 * values there are the same as the system values, and the flags
4771
 * are passed in as-is, so you can pass in system-specific flags too.
4772
 *
4773
 * If the socket is in blocking mode the call will block until there is
4774
 * space for the data in the socket queue. If there is no space available
4775
 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
4776
 * will be returned. To be notified when space is available, wait for the
4777
 * %G_IO_OUT condition. Note though that you may still receive
4778
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
4779
 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
4780
 * very common due to the way the underlying APIs work.)
4781
 *
4782
 * The sum of the sizes of each #GOutputVector in vectors must not be
4783
 * greater than %G_MAXSSIZE. If the message can be larger than this,
4784
 * then it is mandatory to use the g_socket_send_message_with_timeout()
4785
 * function.
4786
 *
4787
 * On error -1 is returned and @error is set accordingly.
4788
 *
4789
 * Returns: Number of bytes written (which may be less than @size), or -1
4790
 * on error
4791
 *
4792
 * Since: 2.22
4793
 */
4794
gssize
4795
g_socket_send_message (GSocket                *socket,
4796
           GSocketAddress         *address,
4797
           GOutputVector          *vectors,
4798
           gint                    num_vectors,
4799
           GSocketControlMessage **messages,
4800
           gint                    num_messages,
4801
           gint                    flags,
4802
           GCancellable           *cancellable,
4803
           GError                **error)
4804
0
{
4805
0
  GPollableReturn res;
4806
0
  gsize bytes_written = 0;
4807
0
  gsize vectors_size = 0;
4808
4809
0
  if (num_vectors != -1)
4810
0
    {
4811
0
      for (gint i = 0; i < num_vectors; i++)
4812
0
        {
4813
          /* No wrap-around for vectors_size */
4814
0
          if (vectors_size > vectors_size + vectors[i].size)
4815
0
            {
4816
0
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4817
0
                           _("Unable to send message: %s"),
4818
0
                           _("Message vectors too large"));
4819
0
              return -1;
4820
0
            }
4821
4822
0
          vectors_size += vectors[i].size;
4823
0
        }
4824
0
    }
4825
0
  else
4826
0
    {
4827
0
      for (gsize i = 0; vectors[i].buffer != NULL; i++)
4828
0
        {
4829
          /* No wrap-around for vectors_size */
4830
0
          if (vectors_size > vectors_size + vectors[i].size)
4831
0
            {
4832
0
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4833
0
                           _("Unable to send message: %s"),
4834
0
                           _("Message vectors too large"));
4835
0
              return -1;
4836
0
            }
4837
4838
0
          vectors_size += vectors[i].size;
4839
0
        }
4840
0
    }
4841
4842
  /* Check if vector's buffers are too big for gssize */
4843
0
  if (vectors_size > G_MAXSSIZE)
4844
0
    {
4845
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
4846
0
                   _("Unable to send message: %s"),
4847
0
                   _("Message vectors too large"));
4848
0
      return -1;
4849
0
    }
4850
4851
0
  res = g_socket_send_message_with_timeout (socket, address,
4852
0
                                            vectors, num_vectors,
4853
0
                                            messages, num_messages, flags,
4854
0
                                            socket->priv->blocking ? -1 : 0,
4855
0
                                            &bytes_written,
4856
0
                                            cancellable, error);
4857
4858
0
  g_assert (res != G_POLLABLE_RETURN_OK || bytes_written <= G_MAXSSIZE);
4859
4860
0
  if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
4861
0
    {
4862
0
#ifndef G_OS_WIN32
4863
0
      socket_set_error_lazy (error, EWOULDBLOCK, _("Error sending message: %s"));
4864
#else
4865
      socket_set_error_lazy (error, WSAEWOULDBLOCK, _("Error sending message: %s"));
4866
#endif
4867
0
    }
4868
4869
0
  return res == G_POLLABLE_RETURN_OK ? (gssize) bytes_written : -1;
4870
0
}
4871
4872
/**
4873
 * g_socket_send_message_with_timeout:
4874
 * @socket: a #GSocket
4875
 * @address: (nullable): a #GSocketAddress, or %NULL
4876
 * @vectors: (array length=num_vectors): an array of #GOutputVector structs
4877
 * @num_vectors: the number of elements in @vectors, or -1
4878
 * @messages: (array length=num_messages) (nullable): a pointer to an
4879
 *   array of #GSocketControlMessages, or %NULL.
4880
 * @num_messages: number of elements in @messages, or -1.
4881
 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
4882
 *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
4883
 * @timeout_us: the maximum time (in microseconds) to wait, or -1
4884
 * @bytes_written: (out) (optional): location to store the number of bytes that were written to the socket
4885
 * @cancellable: (nullable): a %GCancellable or %NULL
4886
 * @error: #GError for error reporting, or %NULL to ignore.
4887
 *
4888
 * This behaves exactly the same as g_socket_send_message(), except that
4889
 * the choice of timeout behavior is determined by the @timeout_us argument
4890
 * rather than by @socket's properties.
4891
 *
4892
 * On error %G_POLLABLE_RETURN_FAILED is returned and @error is set accordingly, or
4893
 * if the socket is currently not writable %G_POLLABLE_RETURN_WOULD_BLOCK is
4894
 * returned. @bytes_written will contain 0 in both cases.
4895
 *
4896
 * Returns: %G_POLLABLE_RETURN_OK if all data was successfully written,
4897
 * %G_POLLABLE_RETURN_WOULD_BLOCK if the socket is currently not writable, or
4898
 * %G_POLLABLE_RETURN_FAILED if an error happened and @error is set.
4899
 *
4900
 * Since: 2.60
4901
 */
4902
GPollableReturn
4903
g_socket_send_message_with_timeout (GSocket                *socket,
4904
                                    GSocketAddress         *address,
4905
                                    const GOutputVector    *vectors,
4906
                                    gint                    num_vectors,
4907
                                    GSocketControlMessage **messages,
4908
                                    gint                    num_messages,
4909
                                    gint                    flags,
4910
                                    gint64                  timeout_us,
4911
                                    gsize                  *bytes_written,
4912
                                    GCancellable           *cancellable,
4913
                                    GError                **error)
4914
0
{
4915
0
  GOutputVector one_vector;
4916
0
  char zero;
4917
0
  gint64 start_time;
4918
4919
0
  if (bytes_written)
4920
0
    *bytes_written = 0;
4921
4922
0
  g_return_val_if_fail (G_IS_SOCKET (socket), G_POLLABLE_RETURN_FAILED);
4923
0
  g_return_val_if_fail (address == NULL || G_IS_SOCKET_ADDRESS (address), G_POLLABLE_RETURN_FAILED);
4924
0
  g_return_val_if_fail (num_vectors == 0 || vectors != NULL, G_POLLABLE_RETURN_FAILED);
4925
0
  g_return_val_if_fail (num_messages == 0 || messages != NULL, G_POLLABLE_RETURN_FAILED);
4926
0
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
4927
0
  g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
4928
4929
0
  start_time = g_get_monotonic_time ();
4930
4931
0
  if (!check_socket (socket, error))
4932
0
    return G_POLLABLE_RETURN_FAILED;
4933
4934
0
  if (!check_timeout (socket, error))
4935
0
    return G_POLLABLE_RETURN_FAILED;
4936
4937
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
4938
0
    return G_POLLABLE_RETURN_FAILED;
4939
4940
0
  if (num_vectors == -1)
4941
0
    {
4942
0
      for (num_vectors = 0;
4943
0
     vectors[num_vectors].buffer != NULL;
4944
0
     num_vectors++)
4945
0
  ;
4946
0
    }
4947
4948
0
  if (num_messages == -1)
4949
0
    {
4950
0
      for (num_messages = 0;
4951
0
     messages != NULL && messages[num_messages] != NULL;
4952
0
     num_messages++)
4953
0
  ;
4954
0
    }
4955
4956
0
  if (num_vectors == 0)
4957
0
    {
4958
0
      zero = '\0';
4959
4960
0
      one_vector.buffer = &zero;
4961
0
      one_vector.size = 1;
4962
0
      num_vectors = 1;
4963
0
      vectors = &one_vector;
4964
0
    }
4965
4966
0
#ifndef G_OS_WIN32
4967
0
  {
4968
0
    GOutputMessage output_message;
4969
0
    struct msghdr msg;
4970
0
    gssize result;
4971
0
    GError *child_error = NULL;
4972
4973
0
    output_message.address = address;
4974
0
    output_message.vectors = (GOutputVector *) vectors;
4975
0
    output_message.num_vectors = num_vectors;
4976
0
    output_message.bytes_sent = 0;
4977
0
    output_message.control_messages = messages;
4978
0
    output_message.num_control_messages = num_messages;
4979
4980
0
    output_message_to_msghdr (&output_message, NULL, &msg, NULL, &child_error);
4981
4982
0
    if (child_error != NULL)
4983
0
      {
4984
0
        g_propagate_error (error, child_error);
4985
0
        return G_POLLABLE_RETURN_FAILED;
4986
0
      }
4987
4988
0
    while (1)
4989
0
      {
4990
0
  result = sendmsg (socket->priv->fd, &msg, flags | G_SOCKET_DEFAULT_SEND_FLAGS);
4991
0
  if (result < 0)
4992
0
    {
4993
0
      int errsv = get_socket_errno ();
4994
4995
0
      if (errsv == EINTR)
4996
0
        continue;
4997
4998
0
      if (errsv == EWOULDBLOCK || errsv == EAGAIN)
4999
0
              {
5000
0
                if (timeout_us != 0)
5001
0
                  {
5002
0
                    if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5003
0
                                           cancellable, error))
5004
0
                      return G_POLLABLE_RETURN_FAILED;
5005
5006
0
                    continue;
5007
0
                  }
5008
5009
0
                return G_POLLABLE_RETURN_WOULD_BLOCK;
5010
0
              }
5011
5012
0
            socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5013
0
            return G_POLLABLE_RETURN_FAILED;
5014
0
    }
5015
0
  break;
5016
0
      }
5017
5018
0
    if (bytes_written)
5019
0
      *bytes_written = result;
5020
5021
0
    return G_POLLABLE_RETURN_OK;
5022
0
  }
5023
#else
5024
  {
5025
    struct sockaddr_storage addr;
5026
    guint addrlen;
5027
    DWORD bytes_sent;
5028
    int result;
5029
    WSABUF *bufs;
5030
    gint i;
5031
5032
    /* Win32 doesn't support control messages.
5033
       Actually this is possible for raw and datagram sockets
5034
       via WSASendMessage on Vista or later, but that doesn't
5035
       seem very useful */
5036
    if (num_messages != 0)
5037
      {
5038
        g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
5039
                             _("GSocketControlMessage not supported on Windows"));
5040
  return G_POLLABLE_RETURN_FAILED;
5041
      }
5042
5043
    /* iov */
5044
    bufs = g_newa (WSABUF, num_vectors);
5045
    for (i = 0; i < num_vectors; i++)
5046
      {
5047
  bufs[i].buf = (char *)vectors[i].buffer;
5048
  bufs[i].len = (gulong)vectors[i].size;
5049
      }
5050
5051
    /* name */
5052
    addrlen = 0; /* Avoid warning */
5053
    if (address)
5054
      {
5055
  addrlen = g_socket_address_get_native_size (address);
5056
  if (!g_socket_address_to_native (address, &addr, sizeof addr, error))
5057
    return G_POLLABLE_RETURN_FAILED;
5058
      }
5059
5060
    while (1)
5061
      {
5062
  if (address)
5063
    result = WSASendTo (socket->priv->fd,
5064
            bufs, num_vectors,
5065
            &bytes_sent, flags,
5066
            (const struct sockaddr *)&addr, addrlen,
5067
            NULL, NULL);
5068
  else
5069
    result = WSASend (socket->priv->fd,
5070
          bufs, num_vectors,
5071
          &bytes_sent, flags,
5072
          NULL, NULL);
5073
5074
  if (result != 0)
5075
    {
5076
      int errsv = get_socket_errno ();
5077
5078
      if (errsv == WSAEINTR)
5079
        continue;
5080
5081
      if (errsv == WSAEWOULDBLOCK)
5082
              {
5083
                win32_unset_event_mask (socket, FD_WRITE);
5084
5085
                if (timeout_us != 0)
5086
                  {
5087
                    if (!block_on_timeout (socket, G_IO_OUT, timeout_us,
5088
                                           start_time, cancellable, error))
5089
                      return G_POLLABLE_RETURN_FAILED;
5090
5091
                    continue;
5092
                  }
5093
5094
                return G_POLLABLE_RETURN_WOULD_BLOCK;
5095
              }
5096
5097
      socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5098
      return G_POLLABLE_RETURN_FAILED;
5099
    }
5100
  break;
5101
      }
5102
5103
    if (bytes_written)
5104
      *bytes_written = bytes_sent;
5105
    return G_POLLABLE_RETURN_OK;
5106
  }
5107
#endif
5108
0
}
5109
5110
/**
5111
 * g_socket_send_messages:
5112
 * @socket: a #GSocket
5113
 * @messages: (array length=num_messages): an array of #GOutputMessage structs
5114
 * @num_messages: the number of elements in @messages
5115
 * @flags: an int containing #GSocketMsgFlags flags, which may additionally
5116
 *    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5117
 * @cancellable: (nullable): a %GCancellable or %NULL
5118
 * @error: #GError for error reporting, or %NULL to ignore.
5119
 *
5120
 * Send multiple data messages from @socket in one go.  This is the most
5121
 * complicated and fully-featured version of this call. For easier use, see
5122
 * g_socket_send(), g_socket_send_to(), and g_socket_send_message().
5123
 *
5124
 * @messages must point to an array of #GOutputMessage structs and
5125
 * @num_messages must be the length of this array. Each #GOutputMessage
5126
 * contains an address to send the data to, and a pointer to an array of
5127
 * #GOutputVector structs to describe the buffers that the data to be sent
5128
 * for each message will be gathered from. Using multiple #GOutputVectors is
5129
 * more memory-efficient than manually copying data from multiple sources
5130
 * into a single buffer, and more network-efficient than making multiple
5131
 * calls to g_socket_send(). Sending multiple messages in one go avoids the
5132
 * overhead of making a lot of syscalls in scenarios where a lot of data
5133
 * packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
5134
 * or where the same data needs to be sent to multiple recipients.
5135
 *
5136
 * @flags modify how the message is sent. The commonly available arguments
5137
 * for this are available in the #GSocketMsgFlags enum, but the
5138
 * values there are the same as the system values, and the flags
5139
 * are passed in as-is, so you can pass in system-specific flags too.
5140
 *
5141
 * If the socket is in blocking mode the call will block until there is
5142
 * space for all the data in the socket queue. If there is no space available
5143
 * and the socket is in non-blocking mode a %G_IO_ERROR_WOULD_BLOCK error
5144
 * will be returned if no data was written at all, otherwise the number of
5145
 * messages sent will be returned. To be notified when space is available,
5146
 * wait for the %G_IO_OUT condition. Note though that you may still receive
5147
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_send() even if you were previously
5148
 * notified of a %G_IO_OUT condition. (On Windows in particular, this is
5149
 * very common due to the way the underlying APIs work.)
5150
 *
5151
 * On error -1 is returned and @error is set accordingly. An error will only
5152
 * be returned if zero messages could be sent; otherwise the number of messages
5153
 * successfully sent before the error will be returned.
5154
 *
5155
 * Returns: number of messages sent, or -1 on error. Note that the number of
5156
 *     messages sent may be smaller than @num_messages if the socket is
5157
 *     non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
5158
 *     in which case the caller may re-try to send the remaining messages.
5159
 *
5160
 * Since: 2.44
5161
 */
5162
gint
5163
g_socket_send_messages (GSocket        *socket,
5164
            GOutputMessage *messages,
5165
            guint           num_messages,
5166
            gint            flags,
5167
            GCancellable   *cancellable,
5168
            GError        **error)
5169
0
{
5170
0
  return g_socket_send_messages_with_timeout (socket, messages, num_messages,
5171
0
                                              flags,
5172
0
                                              socket->priv->blocking ? -1 : 0,
5173
0
                                              cancellable, error);
5174
0
}
5175
5176
static gint
5177
g_socket_send_messages_with_timeout (GSocket        *socket,
5178
                                     GOutputMessage *messages,
5179
                                     guint           num_messages,
5180
                                     gint            flags,
5181
                                     gint64          timeout_us,
5182
                                     GCancellable   *cancellable,
5183
                                     GError        **error)
5184
0
{
5185
0
  gint64 start_time;
5186
5187
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5188
0
  g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5189
0
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
5190
0
  g_return_val_if_fail (error == NULL || *error == NULL, -1);
5191
5192
0
  start_time = g_get_monotonic_time ();
5193
5194
0
  if (!check_socket (socket, error))
5195
0
    return -1;
5196
5197
0
  if (!check_timeout (socket, error))
5198
0
    return -1;
5199
5200
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
5201
0
    return -1;
5202
5203
0
  if (num_messages == 0)
5204
0
    return 0;
5205
5206
0
#if !defined (G_OS_WIN32) && defined (HAVE_SENDMMSG)
5207
0
  {
5208
0
    struct mmsghdr *msgvec;
5209
0
    guint i, num_sent;
5210
5211
    /* Clamp the number of vectors if more given than we can write in one go.
5212
     * The caller has to handle short writes anyway.
5213
     */
5214
0
    if (num_messages > G_IOV_MAX)
5215
0
      num_messages = G_IOV_MAX;
5216
5217
0
    msgvec = g_newa (struct mmsghdr, num_messages);
5218
5219
0
    for (i = 0; i < num_messages; ++i)
5220
0
      {
5221
0
        GOutputMessage *msg = &messages[i];
5222
0
        struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5223
0
        GError *child_error = NULL;
5224
5225
0
        msgvec[i].msg_len = 0;
5226
5227
0
        output_message_to_msghdr (msg, (i > 0) ? &messages[i - 1] : NULL,
5228
0
                                  msg_hdr, (i > 0) ? &msgvec[i - 1].msg_hdr : NULL,
5229
0
                                  &child_error);
5230
5231
0
        if (child_error != NULL)
5232
0
          {
5233
0
            g_propagate_error (error, child_error);
5234
0
            return -1;
5235
0
          }
5236
0
      }
5237
5238
0
    for (num_sent = 0; num_sent < num_messages;)
5239
0
      {
5240
0
        gint ret;
5241
5242
0
        ret = sendmmsg (socket->priv->fd, msgvec + num_sent, num_messages - num_sent,
5243
0
                        flags | G_SOCKET_DEFAULT_SEND_FLAGS);
5244
5245
0
        if (ret < 0)
5246
0
          {
5247
0
            int errsv = get_socket_errno ();
5248
5249
0
            if (errsv == EINTR)
5250
0
              continue;
5251
5252
0
            if (timeout_us != 0 &&
5253
0
                (errsv == EWOULDBLOCK ||
5254
0
                 errsv == EAGAIN))
5255
0
              {
5256
0
                if (!block_on_timeout (socket, G_IO_OUT, timeout_us, start_time,
5257
0
                                       cancellable, error))
5258
0
                  {
5259
0
                    if (num_sent > 0)
5260
0
                      {
5261
0
                        g_clear_error (error);
5262
0
                        break;
5263
0
                      }
5264
5265
0
                    return -1;
5266
0
                  }
5267
5268
0
                continue;
5269
0
              }
5270
5271
            /* If any messages were successfully sent, do not error. */
5272
0
            if (num_sent > 0)
5273
0
              break;
5274
5275
0
            socket_set_error_lazy (error, errsv, _("Error sending message: %s"));
5276
5277
0
            return -1;
5278
0
          }
5279
5280
0
        num_sent += ret;
5281
0
      }
5282
5283
0
    for (i = 0; i < num_sent; ++i)
5284
0
      messages[i].bytes_sent = msgvec[i].msg_len;
5285
5286
0
    return num_sent;
5287
0
  }
5288
#else
5289
  {
5290
    gssize result;
5291
    guint i;
5292
    gint64 wait_timeout;
5293
5294
    wait_timeout = timeout_us;
5295
5296
    for (i = 0; i < num_messages; ++i)
5297
      {
5298
        GOutputMessage *msg = &messages[i];
5299
        GError *msg_error = NULL;
5300
        GPollableReturn pollable_result;
5301
        gsize bytes_written = 0;
5302
5303
        pollable_result = g_socket_send_message_with_timeout (socket, msg->address,
5304
                                                              msg->vectors,
5305
                                                              msg->num_vectors,
5306
                                                              msg->control_messages,
5307
                                                              msg->num_control_messages,
5308
                                                              flags, wait_timeout,
5309
                                                              &bytes_written,
5310
                                                              cancellable, &msg_error);
5311
5312
        if (pollable_result == G_POLLABLE_RETURN_WOULD_BLOCK)
5313
          {
5314
#ifndef G_OS_WIN32
5315
            socket_set_error_lazy (&msg_error, EWOULDBLOCK, _("Error sending message: %s"));
5316
#else
5317
            socket_set_error_lazy (&msg_error, WSAEWOULDBLOCK, _("Error sending message: %s"));
5318
#endif
5319
          }
5320
5321
        if (G_MAXSSIZE > bytes_written &&
5322
            pollable_result == G_POLLABLE_RETURN_OK)
5323
          result = (gssize) bytes_written;
5324
        else
5325
          result = -1;
5326
5327
        /* check if we've timed out or how much time to wait at most */
5328
        if (timeout_us > 0)
5329
          {
5330
            gint64 elapsed = g_get_monotonic_time () - start_time;
5331
            wait_timeout = MAX (timeout_us - elapsed, 1);
5332
          }
5333
5334
        if (result < 0)
5335
          {
5336
            /* if we couldn't send all messages, just return how many we did
5337
             * manage to send, provided we managed to send at least one */
5338
            if (i > 0)
5339
              {
5340
                g_error_free (msg_error);
5341
                return i;
5342
              }
5343
            else
5344
              {
5345
                g_propagate_error (error, msg_error);
5346
                return -1;
5347
              }
5348
          }
5349
5350
        msg->bytes_sent = result;
5351
      }
5352
5353
    return i;
5354
  }
5355
#endif
5356
0
}
5357
5358
static GSocketAddress *
5359
cache_recv_address (GSocket *socket, struct sockaddr *native, size_t native_len)
5360
0
{
5361
0
  GSocketAddress *saddr;
5362
0
  gint i;
5363
0
  guint64 oldest_time = G_MAXUINT64;
5364
0
  gint oldest_index = 0;
5365
5366
0
  if (native_len == 0)
5367
0
    return NULL;
5368
5369
0
  saddr = NULL;
5370
0
  for (i = 0; i < RECV_ADDR_CACHE_SIZE; i++)
5371
0
    {
5372
0
      GSocketAddress *tmp = socket->priv->recv_addr_cache[i].addr;
5373
0
      gpointer tmp_native = socket->priv->recv_addr_cache[i].native;
5374
0
      gsize tmp_native_len = socket->priv->recv_addr_cache[i].native_len;
5375
5376
0
      if (!tmp)
5377
0
        continue;
5378
5379
0
      if (tmp_native_len != native_len)
5380
0
        continue;
5381
5382
0
      if (memcmp (tmp_native, native, native_len) == 0)
5383
0
        {
5384
0
          saddr = g_object_ref (tmp);
5385
0
          socket->priv->recv_addr_cache[i].last_used = g_get_monotonic_time ();
5386
0
          return saddr;
5387
0
        }
5388
5389
0
      if (socket->priv->recv_addr_cache[i].last_used < oldest_time)
5390
0
        {
5391
0
          oldest_time = socket->priv->recv_addr_cache[i].last_used;
5392
0
          oldest_index = i;
5393
0
        }
5394
0
    }
5395
5396
0
  saddr = g_socket_address_new_from_native (native, native_len);
5397
5398
0
  if (socket->priv->recv_addr_cache[oldest_index].addr)
5399
0
    {
5400
0
      g_object_unref (socket->priv->recv_addr_cache[oldest_index].addr);
5401
0
      g_free (socket->priv->recv_addr_cache[oldest_index].native);
5402
0
    }
5403
5404
0
  socket->priv->recv_addr_cache[oldest_index].native = g_memdup2 (native, native_len);
5405
0
  socket->priv->recv_addr_cache[oldest_index].native_len = native_len;
5406
0
  socket->priv->recv_addr_cache[oldest_index].addr = g_object_ref (saddr);
5407
0
  socket->priv->recv_addr_cache[oldest_index].last_used = g_get_monotonic_time ();
5408
5409
0
  return saddr;
5410
0
}
5411
5412
static gssize
5413
g_socket_receive_message_with_timeout (GSocket                 *socket,
5414
                                       GSocketAddress         **address,
5415
                                       GInputVector            *vectors,
5416
                                       gint                     num_vectors,
5417
                                       GSocketControlMessage ***messages,
5418
                                       gint                    *num_messages,
5419
                                       gint                    *flags,
5420
                                       gint64                   timeout_us,
5421
                                       GCancellable            *cancellable,
5422
                                       GError                 **error)
5423
0
{
5424
0
  GInputVector one_vector;
5425
0
  char one_byte;
5426
0
  gint64 start_time;
5427
5428
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5429
5430
0
  start_time = g_get_monotonic_time ();
5431
5432
0
  if (!check_socket (socket, error))
5433
0
    return -1;
5434
5435
0
  if (!check_timeout (socket, error))
5436
0
    return -1;
5437
5438
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
5439
0
    return -1;
5440
5441
0
  if (num_vectors == -1)
5442
0
    {
5443
0
      for (num_vectors = 0;
5444
0
     vectors[num_vectors].buffer != NULL;
5445
0
     num_vectors++)
5446
0
  ;
5447
0
    }
5448
5449
0
  if (num_vectors == 0)
5450
0
    {
5451
0
      one_vector.buffer = &one_byte;
5452
0
      one_vector.size = 1;
5453
0
      num_vectors = 1;
5454
0
      vectors = &one_vector;
5455
0
    }
5456
5457
0
#ifndef G_OS_WIN32
5458
0
  {
5459
0
    GInputMessage input_message;
5460
0
    struct msghdr msg;
5461
0
    gssize result;
5462
5463
0
    input_message.address = address;
5464
0
    input_message.vectors = vectors;
5465
0
    input_message.num_vectors = num_vectors;
5466
0
    input_message.bytes_received = 0;
5467
0
    input_message.flags = (flags != NULL) ? *flags : 0;
5468
0
    input_message.control_messages = messages;
5469
0
    input_message.num_control_messages = (guint *) num_messages;
5470
5471
    /* We always set the close-on-exec flag so we don't leak file
5472
     * descriptors into child processes.  Note that gunixfdmessage.c
5473
     * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5474
     */
5475
0
#ifdef MSG_CMSG_CLOEXEC
5476
0
    input_message.flags |= MSG_CMSG_CLOEXEC;
5477
0
#endif
5478
5479
0
    input_message_to_msghdr (&input_message, &msg);
5480
5481
    /* do it */
5482
0
    while (1)
5483
0
      {
5484
0
  result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5485
0
#ifdef MSG_CMSG_CLOEXEC 
5486
0
  if (result < 0 && get_socket_errno () == EINVAL)
5487
0
    {
5488
      /* We must be running on an old kernel.  Call without the flag. */
5489
0
      msg.msg_flags &= ~(MSG_CMSG_CLOEXEC);
5490
0
      result = recvmsg (socket->priv->fd, &msg, msg.msg_flags);
5491
0
    }
5492
0
#endif
5493
5494
0
  if (result < 0)
5495
0
    {
5496
0
      int errsv = get_socket_errno ();
5497
5498
0
      if (errsv == EINTR)
5499
0
        continue;
5500
5501
0
      if (timeout_us != 0 &&
5502
0
    (errsv == EWOULDBLOCK ||
5503
0
     errsv == EAGAIN))
5504
0
        {
5505
0
                if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5506
0
                                       cancellable, error))
5507
0
                  return -1;
5508
5509
0
                continue;
5510
0
        }
5511
5512
0
      socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5513
0
      return -1;
5514
0
    }
5515
0
  break;
5516
0
      }
5517
5518
0
    input_message_from_msghdr (&msg, &input_message, socket);
5519
5520
0
    if (flags != NULL)
5521
0
      *flags = input_message.flags;
5522
5523
0
    return result;
5524
0
  }
5525
#else
5526
  {
5527
    struct sockaddr_storage addr;
5528
    int addrlen;
5529
    DWORD bytes_received;
5530
    DWORD win_flags;
5531
    int result;
5532
    WSABUF *bufs;
5533
    gint i;
5534
5535
    /* iov */
5536
    bufs = g_newa (WSABUF, num_vectors);
5537
    for (i = 0; i < num_vectors; i++)
5538
      {
5539
  bufs[i].buf = (char *)vectors[i].buffer;
5540
  bufs[i].len = (gulong)vectors[i].size;
5541
      }
5542
5543
    /* flags */
5544
    if (flags != NULL)
5545
      win_flags = *flags;
5546
    else
5547
      win_flags = 0;
5548
5549
    /* do it */
5550
    while (1)
5551
      {
5552
        /* addrlen has to be of type int because that’s how WSARecvFrom() is defined */
5553
        G_STATIC_ASSERT (sizeof addr <= G_MAXINT);
5554
5555
  addrlen = sizeof addr;
5556
  if (address)
5557
    result = WSARecvFrom (socket->priv->fd,
5558
        bufs, num_vectors,
5559
        &bytes_received, &win_flags,
5560
        (struct sockaddr *)&addr, &addrlen,
5561
        NULL, NULL);
5562
  else
5563
    result = WSARecv (socket->priv->fd,
5564
          bufs, num_vectors,
5565
          &bytes_received, &win_flags,
5566
          NULL, NULL);
5567
  if (result != 0)
5568
    {
5569
      int errsv = get_socket_errno ();
5570
5571
      if (errsv == WSAEINTR)
5572
        continue;
5573
5574
      win32_unset_event_mask (socket, FD_READ);
5575
5576
            if (errsv == WSAEWOULDBLOCK)
5577
              {
5578
                if (timeout_us != 0)
5579
                  {
5580
                    if (!block_on_timeout (socket, G_IO_IN, timeout_us,
5581
                                           start_time, cancellable, error))
5582
                      return -1;
5583
5584
                    continue;
5585
                  }
5586
              }
5587
5588
      socket_set_error_lazy (error, errsv, _("Error receiving message: %s"));
5589
      return -1;
5590
    }
5591
        win32_unset_event_mask (socket, FD_READ);
5592
  break;
5593
      }
5594
5595
    /* decode address */
5596
    if (address != NULL)
5597
      {
5598
        *address = cache_recv_address (socket, (struct sockaddr *)&addr, addrlen);
5599
      }
5600
5601
    /* capture the flags */
5602
    if (flags != NULL)
5603
      *flags = win_flags;
5604
5605
    if (messages != NULL)
5606
      *messages = NULL;
5607
    if (num_messages != NULL)
5608
      *num_messages = 0;
5609
5610
    return bytes_received;
5611
  }
5612
#endif
5613
0
}
5614
5615
/**
5616
 * g_socket_receive_messages:
5617
 * @socket: a #GSocket
5618
 * @messages: (array length=num_messages): an array of #GInputMessage structs
5619
 * @num_messages: the number of elements in @messages
5620
 * @flags: an int containing #GSocketMsgFlags flags for the overall operation,
5621
 *    which may additionally contain
5622
 *    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5623
 * @cancellable: (nullable): a %GCancellable or %NULL
5624
 * @error: #GError for error reporting, or %NULL to ignore
5625
 *
5626
 * Receive multiple data messages from @socket in one go.  This is the most
5627
 * complicated and fully-featured version of this call. For easier use, see
5628
 * g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
5629
 *
5630
 * @messages must point to an array of #GInputMessage structs and
5631
 * @num_messages must be the length of this array. Each #GInputMessage
5632
 * contains a pointer to an array of #GInputVector structs describing the
5633
 * buffers that the data received in each message will be written to. Using
5634
 * multiple #GInputVectors is more memory-efficient than manually copying data
5635
 * out of a single buffer to multiple sources, and more system-call-efficient
5636
 * than making multiple calls to g_socket_receive(), such as in scenarios where
5637
 * a lot of data packets need to be received (e.g. high-bandwidth video
5638
 * streaming over RTP/UDP).
5639
 *
5640
 * @flags modify how all messages are received. The commonly available
5641
 * arguments for this are available in the #GSocketMsgFlags enum, but the
5642
 * values there are the same as the system values, and the flags
5643
 * are passed in as-is, so you can pass in system-specific flags too. These
5644
 * flags affect the overall receive operation. Flags affecting individual
5645
 * messages are returned in #GInputMessage.flags.
5646
 *
5647
 * The other members of #GInputMessage are treated as described in its
5648
 * documentation.
5649
 *
5650
 * If #GSocket:blocking is %TRUE the call will block until @num_messages have
5651
 * been received, or the end of the stream is reached.
5652
 *
5653
 * If #GSocket:blocking is %FALSE the call will return up to @num_messages
5654
 * without blocking, or %G_IO_ERROR_WOULD_BLOCK if no messages are queued in the
5655
 * operating system to be received.
5656
 *
5657
 * In blocking mode, if #GSocket:timeout is positive and is reached before any
5658
 * messages are received, %G_IO_ERROR_TIMED_OUT is returned, otherwise up to
5659
 * @num_messages are returned. (Note: This is effectively the
5660
 * behaviour of `MSG_WAITFORONE` with recvmmsg().)
5661
 *
5662
 * To be notified when messages are available, wait for the
5663
 * %G_IO_IN condition. Note though that you may still receive
5664
 * %G_IO_ERROR_WOULD_BLOCK from g_socket_receive_messages() even if you were
5665
 * previously notified of a %G_IO_IN condition.
5666
 *
5667
 * If the remote peer closes the connection, any messages queued in the
5668
 * operating system will be returned, and subsequent calls to
5669
 * g_socket_receive_messages() will return 0 (with no error set).
5670
 *
5671
 * On error -1 is returned and @error is set accordingly. An error will only
5672
 * be returned if zero messages could be received; otherwise the number of
5673
 * messages successfully received before the error will be returned.
5674
 *
5675
 * Returns: number of messages received, or -1 on error. Note that the number
5676
 *     of messages received may be smaller than @num_messages if in non-blocking
5677
 *     mode, if the peer closed the connection, or if @num_messages
5678
 *     was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
5679
 *     to receive the remaining messages.
5680
 *
5681
 * Since: 2.48
5682
 */
5683
gint
5684
g_socket_receive_messages (GSocket        *socket,
5685
                           GInputMessage  *messages,
5686
                           guint           num_messages,
5687
                           gint            flags,
5688
                           GCancellable   *cancellable,
5689
                           GError        **error)
5690
0
{
5691
0
  if (!check_socket (socket, error) ||
5692
0
      !check_timeout (socket, error))
5693
0
    return -1;
5694
5695
0
  return g_socket_receive_messages_with_timeout (socket, messages, num_messages,
5696
0
                                                 flags,
5697
0
                                                 socket->priv->blocking ? -1 : 0,
5698
0
                                                 cancellable, error);
5699
0
}
5700
5701
static gint
5702
g_socket_receive_messages_with_timeout (GSocket        *socket,
5703
                                        GInputMessage  *messages,
5704
                                        guint           num_messages,
5705
                                        gint            flags,
5706
                                        gint64          timeout_us,
5707
                                        GCancellable   *cancellable,
5708
                                        GError        **error)
5709
0
{
5710
0
  gint64 start_time;
5711
5712
0
  g_return_val_if_fail (G_IS_SOCKET (socket), -1);
5713
0
  g_return_val_if_fail (num_messages == 0 || messages != NULL, -1);
5714
0
  g_return_val_if_fail (cancellable == NULL ||
5715
0
                        G_IS_CANCELLABLE (cancellable), -1);
5716
0
  g_return_val_if_fail (error == NULL || *error == NULL, -1);
5717
5718
0
  start_time = g_get_monotonic_time ();
5719
5720
0
  if (!check_socket (socket, error))
5721
0
    return -1;
5722
5723
0
  if (!check_timeout (socket, error))
5724
0
    return -1;
5725
5726
0
  if (g_cancellable_set_error_if_cancelled (cancellable, error))
5727
0
    return -1;
5728
5729
0
  if (num_messages == 0)
5730
0
    return 0;
5731
5732
0
#if !defined (G_OS_WIN32) && defined (HAVE_RECVMMSG)
5733
0
  {
5734
0
    struct mmsghdr *msgvec;
5735
0
    guint i, num_received;
5736
5737
    /* Clamp the number of vectors if more given than we can write in one go.
5738
     * The caller has to handle short writes anyway.
5739
     */
5740
0
    if (num_messages > G_IOV_MAX)
5741
0
      num_messages = G_IOV_MAX;
5742
5743
0
    msgvec = g_newa (struct mmsghdr, num_messages);
5744
5745
0
    for (i = 0; i < num_messages; ++i)
5746
0
      {
5747
0
        GInputMessage *msg = &messages[i];
5748
0
        struct msghdr *msg_hdr = &msgvec[i].msg_hdr;
5749
5750
0
        input_message_to_msghdr (msg, msg_hdr);
5751
0
        msgvec[i].msg_len = 0;
5752
0
      }
5753
5754
    /* We always set the close-on-exec flag so we don't leak file
5755
     * descriptors into child processes.  Note that gunixfdmessage.c
5756
     * will later call fcntl (fd, FD_CLOEXEC), but that isn't atomic.
5757
     */
5758
0
#ifdef MSG_CMSG_CLOEXEC
5759
0
    flags |= MSG_CMSG_CLOEXEC;
5760
0
#endif
5761
5762
0
    for (num_received = 0; num_received < num_messages;)
5763
0
      {
5764
0
        gint ret;
5765
5766
        /* We operate in non-blocking mode and handle the timeout ourselves. */
5767
0
        ret = recvmmsg (socket->priv->fd,
5768
0
                        msgvec + num_received,
5769
0
                        num_messages - num_received,
5770
0
                        flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5771
0
#ifdef MSG_CMSG_CLOEXEC
5772
0
        if (ret < 0 && get_socket_errno () == EINVAL)
5773
0
          {
5774
            /* We must be running on an old kernel. Call without the flag. */
5775
0
            flags &= ~(MSG_CMSG_CLOEXEC);
5776
0
            ret = recvmmsg (socket->priv->fd,
5777
0
                            msgvec + num_received,
5778
0
                            num_messages - num_received,
5779
0
                            flags | G_SOCKET_DEFAULT_SEND_FLAGS, NULL);
5780
0
          }
5781
0
#endif
5782
5783
0
        if (ret < 0)
5784
0
          {
5785
0
            int errsv = get_socket_errno ();
5786
5787
0
            if (errsv == EINTR)
5788
0
              continue;
5789
5790
0
            if (timeout_us != 0 &&
5791
0
                (errsv == EWOULDBLOCK ||
5792
0
                 errsv == EAGAIN))
5793
0
              {
5794
0
                if (!block_on_timeout (socket, G_IO_IN, timeout_us, start_time,
5795
0
                                       cancellable, error))
5796
0
                  {
5797
0
                    if (num_received > 0)
5798
0
                      {
5799
0
                        g_clear_error (error);
5800
0
                        break;
5801
0
                      }
5802
5803
0
                    return -1;
5804
0
                  }
5805
5806
0
                continue;
5807
0
              }
5808
5809
            /* If any messages were successfully received, do not error. */
5810
0
            if (num_received > 0)
5811
0
              break;
5812
5813
0
            socket_set_error_lazy (error, errsv,
5814
0
                                   _("Error receiving message: %s"));
5815
5816
0
            return -1;
5817
0
          }
5818
0
        else if (ret == 0)
5819
0
          {
5820
            /* EOS. */
5821
0
            break;
5822
0
          }
5823
5824
0
        num_received += ret;
5825
0
      }
5826
5827
0
    for (i = 0; i < num_received; ++i)
5828
0
      {
5829
0
        input_message_from_msghdr (&msgvec[i].msg_hdr, &messages[i], socket);
5830
0
        messages[i].bytes_received = msgvec[i].msg_len;
5831
0
      }
5832
5833
0
    return num_received;
5834
0
  }
5835
#else
5836
  {
5837
    guint i;
5838
    gint64 wait_timeout;
5839
5840
    wait_timeout = timeout_us;
5841
5842
    for (i = 0; i < num_messages; i++)
5843
      {
5844
        GInputMessage *msg = &messages[i];
5845
        gssize len;
5846
        GError *msg_error = NULL;
5847
5848
        msg->flags = flags;  /* in-out parameter */
5849
5850
        len = g_socket_receive_message_with_timeout (socket,
5851
                                                     msg->address,
5852
                                                     msg->vectors,
5853
                                                     msg->num_vectors,
5854
                                                     msg->control_messages,
5855
                                                     (gint *) msg->num_control_messages,
5856
                                                     &msg->flags,
5857
                                                     wait_timeout,
5858
                                                     cancellable,
5859
                                                     &msg_error);
5860
5861
        /* check if we've timed out or how much time to wait at most */
5862
        if (timeout_us > 0)
5863
          {
5864
            gint64 elapsed = g_get_monotonic_time () - start_time;
5865
            wait_timeout = MAX (timeout_us - elapsed, 1);
5866
          }
5867
5868
        if (len >= 0)
5869
          msg->bytes_received = len;
5870
5871
        if (i != 0 &&
5872
            (g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
5873
             g_error_matches (msg_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
5874
          {
5875
            g_clear_error (&msg_error);
5876
            break;
5877
          }
5878
5879
        if (msg_error != NULL)
5880
          {
5881
            g_propagate_error (error, msg_error);
5882
            return -1;
5883
          }
5884
5885
        if (len == 0)
5886
          break;
5887
      }
5888
5889
    return i;
5890
  }
5891
#endif
5892
0
}
5893
5894
/**
5895
 * g_socket_receive_message:
5896
 * @socket: a #GSocket
5897
 * @address: (out) (optional): a pointer to a #GSocketAddress
5898
 *     pointer, or %NULL
5899
 * @vectors: (array length=num_vectors): an array of #GInputVector structs
5900
 * @num_vectors: the number of elements in @vectors, or -1
5901
 * @messages: (array length=num_messages) (out) (optional) (nullable): a pointer
5902
 *    which may be filled with an array of #GSocketControlMessages, or %NULL
5903
 * @num_messages: (out): a pointer which will be filled with the number of
5904
 *    elements in @messages, or %NULL
5905
 * @flags: (inout): a pointer to an int containing #GSocketMsgFlags flags,
5906
 *    which may additionally contain
5907
 *    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
5908
 * @cancellable: a %GCancellable or %NULL
5909
 * @error: a #GError pointer, or %NULL
5910
 *
5911
 * Receive data from a socket.  For receiving multiple messages, see
5912
 * g_socket_receive_messages(); for easier use, see
5913
 * g_socket_receive() and g_socket_receive_from().
5914
 *
5915
 * If @address is non-%NULL then @address will be set equal to the
5916
 * source address of the received packet.
5917
 * @address is owned by the caller.
5918
 *
5919
 * @vector must point to an array of #GInputVector structs and
5920
 * @num_vectors must be the length of this array.  These structs
5921
 * describe the buffers that received data will be scattered into.
5922
 * If @num_vectors is -1, then @vectors is assumed to be terminated
5923
 * by a #GInputVector with a %NULL buffer pointer.
5924
 *
5925
 * As a special case, if @num_vectors is 0 (in which case, @vectors
5926
 * may of course be %NULL), then a single byte is received and
5927
 * discarded. This is to facilitate the common practice of sending a
5928
 * single '\0' byte for the purposes of transferring ancillary data.
5929
 *
5930
 * @messages, if non-%NULL, will be set to point to a newly-allocated
5931
 * array of #GSocketControlMessage instances or %NULL if no such
5932
 * messages was received. These correspond to the control messages
5933
 * received from the kernel, one #GSocketControlMessage per message
5934
 * from the kernel. This array is %NULL-terminated and must be freed
5935
 * by the caller using g_free() after calling g_object_unref() on each
5936
 * element. If @messages is %NULL, any control messages received will
5937
 * be discarded.
5938
 *
5939
 * @num_messages, if non-%NULL, will be set to the number of control
5940
 * messages received.
5941
 *
5942
 * If both @messages and @num_messages are non-%NULL, then
5943
 * @num_messages gives the number of #GSocketControlMessage instances
5944
 * in @messages (ie: not including the %NULL terminator).
5945
 *
5946
 * @flags is an in/out parameter. The commonly available arguments
5947
 * for this are available in the #GSocketMsgFlags enum, but the
5948
 * values there are the same as the system values, and the flags
5949
 * are passed in as-is, so you can pass in system-specific flags too
5950
 * (and g_socket_receive_message() may pass system-specific flags out).
5951
 * Flags passed in to the parameter affect the receive operation; flags returned
5952
 * out of it are relevant to the specific returned message.
5953
 *
5954
 * As with g_socket_receive(), data may be discarded if @socket is
5955
 * %G_SOCKET_TYPE_DATAGRAM or %G_SOCKET_TYPE_SEQPACKET and you do not
5956
 * provide enough buffer space to read a complete message. You can pass
5957
 * %G_SOCKET_MSG_PEEK in @flags to peek at the current message without
5958
 * removing it from the receive queue, but there is no portable way to find
5959
 * out the length of the message other than by reading it into a
5960
 * sufficiently-large buffer.
5961
 *
5962
 * If the socket is in blocking mode the call will block until there
5963
 * is some data to receive, the connection is closed, or there is an
5964
 * error. If there is no data available and the socket is in
5965
 * non-blocking mode, a %G_IO_ERROR_WOULD_BLOCK error will be
5966
 * returned. To be notified when data is available, wait for the
5967
 * %G_IO_IN condition.
5968
 *
5969
 * On error -1 is returned and @error is set accordingly.
5970
 *
5971
 * Returns: Number of bytes read, or 0 if the connection was closed by
5972
 * the peer, or -1 on error
5973
 *
5974
 * Since: 2.22
5975
 */
5976
gssize
5977
g_socket_receive_message (GSocket                 *socket,
5978
        GSocketAddress         **address,
5979
        GInputVector            *vectors,
5980
        gint                     num_vectors,
5981
        GSocketControlMessage ***messages,
5982
        gint                    *num_messages,
5983
        gint                    *flags,
5984
        GCancellable            *cancellable,
5985
        GError                 **error)
5986
0
{
5987
0
  return g_socket_receive_message_with_timeout (socket, address, vectors,
5988
0
                                                 num_vectors, messages,
5989
0
                                                 num_messages, flags,
5990
0
                                                 socket->priv->blocking ? -1 : 0,
5991
0
                                                 cancellable, error);
5992
0
}
5993
5994
/**
5995
 * g_socket_get_credentials:
5996
 * @socket: a #GSocket.
5997
 * @error: #GError for error reporting, or %NULL to ignore.
5998
 *
5999
 * Returns the credentials of the foreign process connected to this
6000
 * socket, if any (e.g. it is only supported for %G_SOCKET_FAMILY_UNIX
6001
 * sockets).
6002
 *
6003
 * If this operation isn't supported on the OS, the method fails with
6004
 * the %G_IO_ERROR_NOT_SUPPORTED error. On Linux this is implemented
6005
 * by reading the %SO_PEERCRED option on the underlying socket.
6006
 *
6007
 * This method can be expected to be available on the following platforms:
6008
 *
6009
 * - Linux since GLib 2.26
6010
 * - OpenBSD since GLib 2.30
6011
 * - Solaris, Illumos and OpenSolaris since GLib 2.40
6012
 * - NetBSD since GLib 2.42
6013
 * - macOS, tvOS, iOS since GLib 2.66
6014
 *
6015
 * Other ways to obtain credentials from a foreign peer includes the
6016
 * #GUnixCredentialsMessage type and
6017
 * g_unix_connection_send_credentials() /
6018
 * g_unix_connection_receive_credentials() functions.
6019
 *
6020
 * Returns: (transfer full): %NULL if @error is set, otherwise a #GCredentials object
6021
 * that must be freed with g_object_unref().
6022
 *
6023
 * Since: 2.26
6024
 */
6025
GCredentials *
6026
g_socket_get_credentials (GSocket   *socket,
6027
                          GError   **error)
6028
0
{
6029
0
  GCredentials *ret;
6030
6031
0
  g_return_val_if_fail (G_IS_SOCKET (socket), NULL);
6032
0
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6033
6034
0
  if (!check_socket (socket, error))
6035
0
    return NULL;
6036
6037
0
  ret = NULL;
6038
6039
0
#if G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED
6040
6041
0
#ifdef SO_PEERCRED
6042
0
  {
6043
0
    guint8 native_creds_buf[G_CREDENTIALS_NATIVE_SIZE];
6044
0
    socklen_t optlen = sizeof (native_creds_buf);
6045
6046
0
    if (getsockopt (socket->priv->fd,
6047
0
                    SOL_SOCKET,
6048
0
                    SO_PEERCRED,
6049
0
                    native_creds_buf,
6050
0
                    &optlen) == 0)
6051
0
      {
6052
0
        ret = g_credentials_new ();
6053
0
        g_credentials_set_native (ret,
6054
0
                                  G_CREDENTIALS_NATIVE_TYPE,
6055
0
                                  native_creds_buf);
6056
0
      }
6057
0
  }
6058
#elif G_CREDENTIALS_USE_APPLE_XUCRED
6059
  {
6060
    struct xucred cred;
6061
    socklen_t optlen = sizeof (cred);
6062
6063
    if (getsockopt (socket->priv->fd,
6064
                    SOL_LOCAL,
6065
                    LOCAL_PEERCRED,
6066
                    &cred,
6067
                    &optlen) == 0
6068
        && optlen != 0)
6069
      {
6070
        if (cred.cr_version == XUCRED_VERSION)
6071
          {
6072
            pid_t pid;
6073
            socklen_t optlen = sizeof (pid);
6074
6075
            ret = g_credentials_new ();
6076
            g_credentials_set_native (ret,
6077
                                      G_CREDENTIALS_NATIVE_TYPE,
6078
                                      &cred);
6079
6080
#ifdef LOCAL_PEERPID
6081
            if (getsockopt (socket->priv->fd,
6082
                            SOL_LOCAL,
6083
                            LOCAL_PEERPID,
6084
                            &pid,
6085
                            &optlen) == 0)
6086
              _g_credentials_set_local_peerid (ret, pid);
6087
#endif
6088
          }
6089
        else
6090
          {
6091
            g_set_error (error,
6092
                         G_IO_ERROR,
6093
                         G_IO_ERROR_NOT_SUPPORTED,
6094
                         /* No point in translating this! */
6095
                         "struct xucred cr_version %u != %u",
6096
                         cred.cr_version, XUCRED_VERSION);
6097
            /* Reuse a translatable string we already have */
6098
            g_prefix_error (error,
6099
                            _("Unable to read socket credentials: %s"),
6100
                            "");
6101
6102
            return NULL;
6103
          }
6104
      }
6105
    else if (optlen == 0 || errno == EINVAL)
6106
      {
6107
        g_set_error (error,
6108
                     G_IO_ERROR,
6109
                     G_IO_ERROR_NOT_SUPPORTED,
6110
                     _("Unable to read socket credentials: %s"),
6111
                     "unsupported socket type");
6112
        return NULL;
6113
      }
6114
  }
6115
#elif G_CREDENTIALS_USE_NETBSD_UNPCBID
6116
  {
6117
    struct unpcbid cred;
6118
    socklen_t optlen = sizeof (cred);
6119
6120
    if (getsockopt (socket->priv->fd,
6121
                    0,
6122
                    LOCAL_PEEREID,
6123
                    &cred,
6124
                    &optlen) == 0)
6125
      {
6126
        ret = g_credentials_new ();
6127
        g_credentials_set_native (ret,
6128
                                  G_CREDENTIALS_NATIVE_TYPE,
6129
                                  &cred);
6130
      }
6131
  }
6132
#elif G_CREDENTIALS_USE_SOLARIS_UCRED
6133
  {
6134
    ucred_t *ucred = NULL;
6135
6136
    if (getpeerucred (socket->priv->fd, &ucred) == 0)
6137
      {
6138
        ret = g_credentials_new ();
6139
        g_credentials_set_native (ret,
6140
                                  G_CREDENTIALS_TYPE_SOLARIS_UCRED,
6141
                                  ucred);
6142
        ucred_free (ucred);
6143
      }
6144
  }
6145
#elif G_CREDENTIALS_USE_WIN32_PID
6146
  {
6147
    DWORD peerid, drc;
6148
6149
    if (WSAIoctl (socket->priv->fd, SIO_AF_UNIX_GETPEERPID,
6150
                  NULL, 0U,
6151
                  &peerid, sizeof(peerid),
6152
                  /* Windows bug: always 0 https://github.com/microsoft/WSL/issues/4676 */
6153
                  &drc,
6154
                  NULL, NULL) == 0)
6155
      {
6156
        ret = g_credentials_new ();
6157
        g_credentials_set_native (ret,
6158
                                  G_CREDENTIALS_TYPE_WIN32_PID,
6159
                                  &peerid);
6160
      }
6161
  }
6162
#else
6163
  #error "G_CREDENTIALS_SOCKET_GET_CREDENTIALS_SUPPORTED is set but this is no code for this platform"
6164
#endif
6165
6166
0
  if (!ret)
6167
0
    {
6168
0
      int errsv = get_socket_errno ();
6169
6170
0
      g_set_error (error,
6171
0
                   G_IO_ERROR,
6172
0
                   socket_io_error_from_errno (errsv),
6173
0
                   _("Unable to read socket credentials: %s"),
6174
0
                   socket_strerror (errsv));
6175
0
    }
6176
6177
#else
6178
6179
  g_set_error_literal (error,
6180
                       G_IO_ERROR,
6181
                       G_IO_ERROR_NOT_SUPPORTED,
6182
                       _("g_socket_get_credentials not implemented for this OS"));
6183
#endif
6184
6185
0
  return ret;
6186
0
}
6187
6188
/**
6189
 * g_socket_get_option:
6190
 * @socket: a #GSocket
6191
 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6192
 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6193
 * @value: (out): return location for the option value
6194
 * @error: #GError for error reporting, or %NULL to ignore.
6195
 *
6196
 * Gets the value of an integer-valued option on @socket, as with
6197
 * getsockopt(). (If you need to fetch a  non-integer-valued option,
6198
 * you will need to call getsockopt() directly.)
6199
 *
6200
 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6201
 * header pulls in system headers that will define most of the
6202
 * standard/portable socket options. For unusual socket protocols or
6203
 * platform-dependent options, you may need to include additional
6204
 * headers.
6205
 *
6206
 * Note that even for socket options that are a single byte in size,
6207
 * @value is still a pointer to a #gint variable, not a #guchar;
6208
 * g_socket_get_option() will handle the conversion internally.
6209
 *
6210
 * Returns: success or failure. On failure, @error will be set, and
6211
 *   the system error value (`errno` or WSAGetLastError()) will still
6212
 *   be set to the result of the getsockopt() call.
6213
 *
6214
 * Since: 2.36
6215
 */
6216
gboolean
6217
g_socket_get_option (GSocket  *socket,
6218
         gint      level,
6219
         gint      optname,
6220
         gint     *value,
6221
         GError  **error)
6222
0
{
6223
0
  guint size;
6224
6225
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6226
6227
  /* g_socket_get_option() is called during socket init, so skip the init checks
6228
   * in check_socket() */
6229
0
  if (socket->priv->inited && !check_socket (socket, error))
6230
0
    return FALSE;
6231
6232
0
  *value = 0;
6233
0
  size = sizeof (gint);
6234
0
  if (getsockopt (socket->priv->fd, level, optname, value, &size) != 0)
6235
0
    {
6236
0
      int errsv = get_socket_errno ();
6237
6238
0
      g_set_error_literal (error,
6239
0
         G_IO_ERROR,
6240
0
         socket_io_error_from_errno (errsv),
6241
0
         socket_strerror (errsv));
6242
0
#ifndef G_OS_WIN32
6243
      /* Reset errno in case the caller wants to look at it */
6244
0
      errno = errsv;
6245
0
#endif
6246
0
      return FALSE;
6247
0
    }
6248
6249
#if G_BYTE_ORDER == G_BIG_ENDIAN
6250
  /* If the returned value is smaller than an int then we need to
6251
   * slide it over into the low-order bytes of *value.
6252
   */
6253
  if (size != sizeof (gint))
6254
    *value = *value >> (8 * (sizeof (gint) - size));
6255
#endif
6256
6257
0
  return TRUE;
6258
0
}
6259
6260
/**
6261
 * g_socket_set_option:
6262
 * @socket: a #GSocket
6263
 * @level: the "API level" of the option (eg, `SOL_SOCKET`)
6264
 * @optname: the "name" of the option (eg, `SO_BROADCAST`)
6265
 * @value: the value to set the option to
6266
 * @error: #GError for error reporting, or %NULL to ignore.
6267
 *
6268
 * Sets the value of an integer-valued option on @socket, as with
6269
 * setsockopt(). (If you need to set a non-integer-valued option,
6270
 * you will need to call setsockopt() directly.)
6271
 *
6272
 * The [<gio/gnetworking.h>][gio-gnetworking.h]
6273
 * header pulls in system headers that will define most of the
6274
 * standard/portable socket options. For unusual socket protocols or
6275
 * platform-dependent options, you may need to include additional
6276
 * headers.
6277
 *
6278
 * Returns: success or failure. On failure, @error will be set, and
6279
 *   the system error value (`errno` or WSAGetLastError()) will still
6280
 *   be set to the result of the setsockopt() call.
6281
 *
6282
 * Since: 2.36
6283
 */
6284
gboolean
6285
g_socket_set_option (GSocket  *socket,
6286
         gint      level,
6287
         gint      optname,
6288
         gint      value,
6289
         GError  **error)
6290
0
{
6291
0
  gint errsv;
6292
6293
0
  g_return_val_if_fail (G_IS_SOCKET (socket), FALSE);
6294
6295
  /* g_socket_set_option() is called during socket init, so skip the init checks
6296
   * in check_socket() */
6297
0
  if (socket->priv->inited && !check_socket (socket, error))
6298
0
    return FALSE;
6299
6300
0
  if (setsockopt (socket->priv->fd, level, optname, &value, sizeof (gint)) == 0)
6301
0
    return TRUE;
6302
6303
#if !defined (__linux__) && !defined (G_OS_WIN32)
6304
  /* Linux and Windows let you set a single-byte value from an int,
6305
   * but most other platforms don't.
6306
   */
6307
  if (errno == EINVAL && value >= SCHAR_MIN && value <= CHAR_MAX)
6308
    {
6309
#if G_BYTE_ORDER == G_BIG_ENDIAN
6310
      value = value << (8 * (sizeof (gint) - 1));
6311
#endif
6312
      if (setsockopt (socket->priv->fd, level, optname, &value, 1) == 0)
6313
        return TRUE;
6314
    }
6315
#endif
6316
6317
0
  errsv = get_socket_errno ();
6318
6319
0
  g_set_error_literal (error,
6320
0
                       G_IO_ERROR,
6321
0
                       socket_io_error_from_errno (errsv),
6322
0
                       socket_strerror (errsv));
6323
0
#ifndef G_OS_WIN32
6324
0
  errno = errsv;
6325
0
#endif
6326
0
  return FALSE;
6327
0
}