tcp-bsd.c 12.3 KB
Newer Older
1 2 3
/*
 * This file is part of the Nice GLib ICE library.
 *
4 5 6
 * (C) 2008-2009 Collabora Ltd.
 *  Contact: Youness Alaoui
 * (C) 2008-2009 Nokia Corporation. All rights reserved.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
24
 *   Youness Alaoui, Collabora Ltd.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

/*
 * Implementation of TCP relay socket interface using TCP Berkeley sockets. (See
 * http://en.wikipedia.org/wiki/Berkeley_sockets.)
 */
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "tcp-bsd.h"
#include "agent-priv.h"
47
#include "socket-priv.h"
48 49 50 51 52 53 54 55 56

#include <string.h>
#include <errno.h>
#include <fcntl.h>

#ifndef G_OS_WIN32
#include <unistd.h>
#endif

57 58 59 60 61
/* FIXME: This should be defined in gio/gnetworking.h, which we should include;
 * but we cannot do that without refactoring.
 * (See: https://phabricator.freedesktop.org/D230). */
#define TCP_NODELAY 1

62
typedef struct {
63
  NiceAddress remote_addr;
64 65 66
  GQueue send_queue;
  GMainContext *context;
  GSource *io_source;
67
  gboolean error;
68
  gboolean reliable;
69 70
  NiceSocketWritableCb writable_cb;
  gpointer writable_data;
71 72
} TcpPriv;

73
#define MAX_QUEUE_LENGTH 20
74 75

static void socket_close (NiceSocket *sock);
76 77
static gint socket_recv_messages (NiceSocket *sock,
    NiceInputMessage *recv_messages, guint n_recv_messages);
78
static gint socket_send_messages (NiceSocket *sock, const NiceAddress *to,
79
    const NiceOutputMessage *messages, guint n_messages);
80 81
static gint socket_send_messages_reliable (NiceSocket *sock,
    const NiceAddress *to, const NiceOutputMessage *messages, guint n_messages);
82
static gboolean socket_is_reliable (NiceSocket *sock);
83 84 85
static gboolean socket_can_send (NiceSocket *sock, NiceAddress *addr);
static void socket_set_writable_callback (NiceSocket *sock,
    NiceSocketWritableCb callback, gpointer user_data);
86

87
static gboolean socket_send_more (GSocket *gsocket, GIOCondition condition,
88 89
    gpointer data);

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
NiceSocket *
nice_tcp_bsd_socket_new_from_gsock (GMainContext *ctx, GSocket *gsock,
    NiceAddress *local_addr, NiceAddress *remote_addr, gboolean reliable)
{
  NiceSocket *sock;
  TcpPriv *priv;

  g_return_val_if_fail (G_IS_SOCKET (gsock), NULL);

  sock = g_slice_new0 (NiceSocket);
  sock->priv = priv = g_slice_new0 (TcpPriv);

  if (ctx == NULL)
    ctx = g_main_context_default ();
  priv->context = g_main_context_ref (ctx);
  priv->remote_addr = *remote_addr;
  priv->error = FALSE;
  priv->reliable = reliable;
108 109
  priv->writable_cb = NULL;
  priv->writable_data = NULL;
110 111 112 113 114 115 116 117

  sock->type = NICE_SOCKET_TYPE_TCP_BSD;
  sock->fileno = g_object_ref (gsock);
  sock->addr = *local_addr;
  sock->send_messages = socket_send_messages;
  sock->send_messages_reliable = socket_send_messages_reliable;
  sock->recv_messages = socket_recv_messages;
  sock->is_reliable = socket_is_reliable;
118 119
  sock->can_send = socket_can_send;
  sock->set_writable_callback = socket_set_writable_callback;
120 121 122 123 124
  sock->close = socket_close;

  return sock;
}

125
NiceSocket *
126 127
nice_tcp_bsd_socket_new (GMainContext *ctx, NiceAddress *local_addr,
    NiceAddress *remote_addr, gboolean reliable)
128
{
129 130 131 132
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } name;
133
  NiceSocket *sock;
134 135
  GSocket *gsock = NULL;
  GError *gerr = NULL;
136
  gboolean gret = FALSE;
137
  GSocketAddress *gaddr;
138

139
  if (remote_addr == NULL) {
140 141
    /* We can't connect a tcp socket with no destination address */
    return NULL;
142 143
  }

144
  nice_address_copy_to_sockaddr (remote_addr, &name.addr);
145

146 147 148
  if (name.storage.ss_family == AF_UNSPEC || name.storage.ss_family == AF_INET) {
    gsock = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,
        G_SOCKET_PROTOCOL_TCP, NULL);
149

150
    name.storage.ss_family = AF_INET;
151
#ifdef HAVE_SA_LEN
152
    name.storage.ss_len = sizeof (struct sockaddr_in);
153
#endif
154 155 156 157
  } else if (name.storage.ss_family == AF_INET6) {
    gsock = g_socket_new (G_SOCKET_FAMILY_IPV6, G_SOCKET_TYPE_STREAM,
        G_SOCKET_PROTOCOL_TCP, NULL);
    name.storage.ss_family = AF_INET6;
158
#ifdef HAVE_SA_LEN
159
    name.storage.ss_len = sizeof (struct sockaddr_in6);
160 161 162
#endif
  }

Youness Alaoui's avatar
Youness Alaoui committed
163
  if (gsock == NULL) {
164
    return NULL;
Youness Alaoui's avatar
Youness Alaoui committed
165
  }
166

167 168 169 170 171 172
  gaddr = g_socket_address_new_from_native (&name.addr, sizeof (name));
  if (gaddr == NULL) {
    g_object_unref (gsock);
    return NULL;
  }

173
  /* GSocket: All socket file descriptors are set to be close-on-exec. */
174 175
  g_socket_set_blocking (gsock, false);

176 177 178
  /* setting TCP_NODELAY to TRUE in order to avoid packet batching */
  g_socket_set_option (gsock, IPPROTO_TCP, TCP_NODELAY, TRUE, NULL);

179 180
  gret = g_socket_connect (gsock, gaddr, NULL, &gerr);
  g_object_unref (gaddr);
181

182 183
  if (gret == FALSE) {
    if (g_error_matches (gerr, G_IO_ERROR, G_IO_ERROR_PENDING) == FALSE) {
184
      g_error_free (gerr);
185 186 187 188
      g_socket_close (gsock, NULL);
      g_object_unref (gsock);
      return NULL;
    }
189
    g_error_free (gerr);
190
  }
191

192 193 194
  nice_address_copy_to_sockaddr (local_addr, &name.addr);
  gaddr = g_socket_address_new_from_native (&name.addr, sizeof (name));
  if (gaddr == NULL) {
Youness Alaoui's avatar
Youness Alaoui committed
195 196
    g_socket_close (gsock, NULL);
    g_object_unref (gsock);
197 198
    return NULL;
  }
199
  g_socket_bind (gsock, gaddr, FALSE, NULL);
200
  g_object_unref (gaddr);
201

202
  sock = nice_tcp_bsd_socket_new_from_gsock (ctx, gsock, local_addr, remote_addr,
203 204
      reliable);
  g_object_unref (gsock);
205 206 207 208 209 210 211 212 213 214

  return sock;
}


static void
socket_close (NiceSocket *sock)
{
  TcpPriv *priv = sock->priv;

Youness Alaoui's avatar
Youness Alaoui committed
215 216 217
  if (sock->fileno) {
    g_socket_close (sock->fileno, NULL);
    g_object_unref (sock->fileno);
218 219
    sock->fileno = NULL;
  }
220 221 222 223
  if (priv->io_source) {
    g_source_destroy (priv->io_source);
    g_source_unref (priv->io_source);
  }
224 225

  nice_socket_free_send_queue (&priv->send_queue);
226

227 228 229
  if (priv->context)
    g_main_context_unref (priv->context);

230 231 232 233
  g_slice_free(TcpPriv, sock->priv);
}

static gint
234 235
socket_recv_messages (NiceSocket *sock,
    NiceInputMessage *recv_messages, guint n_recv_messages)
236 237
{
  TcpPriv *priv = sock->priv;
238
  guint i;
239

240 241
  /* Make sure socket has not been freed: */
  g_assert (sock->priv != NULL);
242

243 244 245 246
  /* Don't try to access the socket if it had an error */
  if (priv->error)
    return -1;

247 248 249 250
  for (i = 0; i < n_recv_messages; i++) {
    gint flags = G_SOCKET_MSG_NONE;
    GError *gerr = NULL;
    gssize len;
251

252 253 254 255 256 257 258 259 260 261 262 263
    len = g_socket_receive_message (sock->fileno, NULL,
        recv_messages[i].buffers, recv_messages[i].n_buffers,
        NULL, NULL, &flags, NULL, &gerr);

    recv_messages[i].length = MAX (len, 0);

    /* recv returns 0 when the peer performed a shutdown.. we must return -1
     * here so that the agent destroys the g_source */
    if (len == 0) {
      priv->error = TRUE;
      break;
    }
264

265 266 267
    if (len < 0) {
      if (g_error_matches (gerr, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
        len = 0;
268

269 270 271 272 273
      g_error_free (gerr);
      return len;
    }

    if (recv_messages[i].from)
274
      *recv_messages[i].from = priv->remote_addr;
275 276
  }

277 278 279 280 281
  /* Was there an error processing the first message? */
  if (priv->error && i == 0)
    return -1;

  return i;
282 283
}

284
static gssize
285 286
socket_send_message (NiceSocket *sock,
    const NiceOutputMessage *message, gboolean reliable)
287 288
{
  TcpPriv *priv = sock->priv;
289
  gssize ret;
290
  GError *gerr = NULL;
291
  gsize message_len;
292

293 294
  /* Make sure socket has not been freed: */
  g_assert (sock->priv != NULL);
295

296
  /* Don't try to access the socket if it had an error, otherwise we risk a
297
   * crash with SIGPIPE (Broken pipe) */
298 299 300
  if (priv->error)
    return -1;

301 302
  message_len = output_message_get_size (message);

303
  /* First try to send the data, don't send it later if it can be sent now
304
   * this way we avoid allocating memory on every send */
305
  if (g_queue_is_empty (&priv->send_queue)) {
306 307 308
    ret = g_socket_send_message (sock->fileno, NULL, message->buffers,
        message->n_buffers, NULL, 0, G_SOCKET_MSG_NONE, NULL, &gerr);

309
    if (ret < 0) {
310 311 312
      if (g_error_matches (gerr, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
          g_error_matches (gerr, G_IO_ERROR, G_IO_ERROR_FAILED)) {
        /* Queue the message and send it later. */
313 314 315
        nice_socket_queue_send_with_callback (&priv->send_queue,
            message, 0, message_len, FALSE, sock->fileno, &priv->io_source,
            priv->context, (GSourceFunc) socket_send_more, sock);
316
        ret = message_len;
317
      }
318 319

      g_error_free (gerr);
320
    } else if ((gsize) ret < message_len) {
321
      /* Partial send. */
322 323 324
      nice_socket_queue_send_with_callback (&priv->send_queue,
          message, ret, message_len, TRUE, sock->fileno, &priv->io_source,
          priv->context, (GSourceFunc) socket_send_more, sock);
325
      ret = message_len;
326 327
    }
  } else {
328 329 330
    /* Only queue if we're sending reliably  */
    if (reliable) {
      /* Queue the message and send it later. */
331 332 333
      nice_socket_queue_send_with_callback (&priv->send_queue,
          message, 0, message_len, FALSE, sock->fileno, &priv->io_source,
          priv->context, (GSourceFunc) socket_send_more, sock);
334 335 336 337
      ret = message_len;
    } else {
      /* non reliable send, so we shouldn't queue the message */
      ret = 0;
338
    }
339 340
  }

341 342 343 344 345 346 347
  return ret;
}

/* Data sent to this function must be a single entity because buffers can be
 * dropped if the bandwidth isn't fast enough. So do not send a message in
 * multiple chunks. */
static gint
348 349
socket_send_messages (NiceSocket *sock, const NiceAddress *to,
    const NiceOutputMessage *messages, guint n_messages)
350 351 352
{
  guint i;

353 354
  /* Make sure socket has not been freed: */
  g_assert (sock->priv != NULL);
355

356 357 358 359
  for (i = 0; i < n_messages; i++) {
    const NiceOutputMessage *message = &messages[i];
    gssize len;

360
    len = socket_send_message (sock, message, FALSE);
361 362 363

    if (len < 0) {
      /* Error. */
364 365
      if (i > 0)
        break;
366 367 368 369 370 371 372 373
      return len;
    } else if (len == 0) {
      /* EWOULDBLOCK. */
      break;
    }
  }

  return i;
374 375
}

376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
static gint
socket_send_messages_reliable (NiceSocket *sock, const NiceAddress *to,
    const NiceOutputMessage *messages, guint n_messages)
{
  guint i;

  for (i = 0; i < n_messages; i++) {
    if (socket_send_message (sock, &messages[i], TRUE) < 0) {
      /* Error. */
      return -1;
    }
  }

  return i;
}

392 393 394
static gboolean
socket_is_reliable (NiceSocket *sock)
{
395 396 397
  TcpPriv *priv = sock->priv;

  return priv->reliable;
398 399
}

400 401 402 403
static gboolean
socket_can_send (NiceSocket *sock, NiceAddress *addr)
{
  TcpPriv *priv = sock->priv;
404

405 406 407 408 409 410 411 412 413 414 415 416
  return g_queue_is_empty (&priv->send_queue);
}

static void
socket_set_writable_callback (NiceSocket *sock,
    NiceSocketWritableCb callback, gpointer user_data)
{
  TcpPriv *priv = sock->priv;

  priv->writable_cb = callback;
  priv->writable_data = user_data;
}
417 418 419

static gboolean
socket_send_more (
420
  GSocket *gsocket,
421 422 423 424 425 426
  GIOCondition condition,
  gpointer data)
{
  NiceSocket *sock = (NiceSocket *) data;
  TcpPriv *priv = sock->priv;

427 428 429 430 431 432 433 434
  agent_lock ();

  if (g_source_is_destroyed (g_main_current_source ())) {
    nice_debug ("Source was destroyed. "
        "Avoided race condition in tcp-bsd.c:socket_send_more");
    agent_unlock ();
    return FALSE;
  }
435

436 437 438 439
  /* connection hangs up or queue was emptied */
  if (condition & G_IO_HUP ||
      nice_socket_flush_send_queue_to_socket (sock->fileno,
          &priv->send_queue)) {
440 441 442 443
    g_source_destroy (priv->io_source);
    g_source_unref (priv->io_source);
    priv->io_source = NULL;

444
    agent_unlock ();
445 446 447 448

    if (priv->writable_cb)
      priv->writable_cb (sock, priv->writable_data);

449 450 451
    return FALSE;
  }

452
  agent_unlock ();
453 454
  return TRUE;
}