Coverage Report

Created: 2025-09-27 07:50

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