tport_type_udp.c 14.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2006 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

25
/**@CFILE tport_type_udp.c UDP Transport
26 27 28 29 30 31 32 33 34 35 36 37
 *
 * See tport.docs for more detailed description of tport interface.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Martti Mela <Martti.Mela@nokia.com>
 *
 * @date Created: Fri Mar 24 08:45:49 EET 2006 ppessi
 */

#include "config.h"

#include "tport_internal.h"
38
#include "sofia-sip/hostdomain.h"
39 40 41 42 43 44 45 46

#if HAVE_IP_RECVERR || HAVE_IPV6_RECVERR
#include <linux/types.h>
#include <linux/errqueue.h>
#include <sys/uio.h>
#endif

#include <stdlib.h>
47
#include <string.h>
48 49 50 51 52 53 54 55
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>

/* ---------------------------------------------------------------------- */
/* UDP */

56 57 58 59 60 61 62
static
int tport_udp_init_client(tport_primary_t *pri,
			  tp_name_t tpn[1],
			  su_addrinfo_t *ai,
			  tagi_t const *tags,
			  char const **return_culprit);

63 64 65 66 67 68 69
#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "tport_type_udp";
#endif

70
tport_vtable_t const tport_udp_client_vtable =
71
{
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  /* vtp_name 		     */ "udp",
  /* vtp_public              */ tport_type_client,
  /* vtp_pri_size            */ sizeof (tport_primary_t),
  /* vtp_init_primary        */ tport_udp_init_client,
  /* vtp_deinit_primary      */ NULL,
  /* vtp_wakeup_pri          */ NULL,
  /* vtp_connect             */ NULL,
  /* vtp_secondary_size      */ sizeof (tport_t),
  /* vtp_init_secondary      */ NULL,
  /* vtp_deinit_secondary    */ NULL,
  /* vtp_shutdown            */ NULL,
  /* vtp_set_events          */ NULL,
  /* vtp_wakeup              */ NULL,
  /* vtp_recv                */ tport_recv_dgram,
  /* vtp_send                */ tport_send_dgram,
  /* vtp_deliver             */ NULL,
  /* vtp_prepare             */ NULL,
  /* vtp_keepalive           */ NULL,
  /* vtp_stun_response       */ NULL,
  /* vtp_next_secondary_timer*/ NULL,
  /* vtp_secondary_timer     */ NULL,
93 94
};

95
tport_vtable_t const tport_udp_vtable =
96
{
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  /* vtp_name 		     */ "udp",
  /* vtp_public              */ tport_type_local,
  /* vtp_pri_size            */ sizeof (tport_primary_t),
  /* vtp_init_primary        */ tport_udp_init_primary,
  /* vtp_deinit_primary      */ NULL,
  /* vtp_wakeup_pri          */ NULL,
  /* vtp_connect             */ NULL,
  /* vtp_secondary_size      */ sizeof (tport_t),
  /* vtp_init_secondary      */ NULL,
  /* vtp_deinit_secondary    */ NULL,
  /* vtp_shutdown            */ NULL,
  /* vtp_set_events          */ NULL,
  /* vtp_wakeup              */ NULL,
  /* vtp_recv                */ tport_recv_dgram,
  /* vtp_send                */ tport_send_dgram,
  /* vtp_deliver             */ NULL,
  /* vtp_prepare             */ NULL,
  /* vtp_keepalive           */ NULL,
  /* vtp_stun_response       */ NULL,
  /* vtp_next_secondary_timer*/ NULL,
  /* vtp_secondary_timer     */ NULL,
118 119
};

120 121
static void tport_check_trunc(tport_t *tp, su_addrinfo_t *ai);

122
int tport_udp_init_primary(tport_primary_t *pri,
123
			   tp_name_t tpn[1],
124 125 126 127 128 129 130
			   su_addrinfo_t *ai,
			   tagi_t const *tags,
			   char const **return_culprit)
{
  unsigned rmem = 0, wmem = 0;
  int events = SU_WAIT_IN;
  int s;
131
#if HAVE_IP_ADD_MEMBERSHIP
132
  su_sockaddr_t *su = (su_sockaddr_t *)ai->ai_addr;
133
#endif
134
  int const one = 1; (void)one;
135 136

  s = su_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
137
  if (s == INVALID_SOCKET)
138 139 140 141 142 143 144
    return *return_culprit = "socket", -1;

  pri->pri_primary->tp_socket = s;

  if (tport_bind_socket(s, ai, return_culprit) < 0)
    return -1;

145 146
  tport_set_tos(s, ai, pri->pri_params->tpp_tos);

147
#if HAVE_IP_ADD_MEMBERSHIP
148
  if (ai->ai_family == AF_INET &&
149 150
      IN_MULTICAST(ntohl(su->su_sin.sin_addr.s_addr))) {
    /* Try to join to the multicast group */
151
    /* Bind to the SIP address like
152
       <sip:88.77.66.55:5060;maddr=224.0.1.75;transport=udp> */
153 154
    struct ip_mreq imr[1];
    struct in_addr iface;
155 156

    memset(imr, 0, sizeof imr);
157

158 159 160
    imr->imr_multiaddr = su->su_sin.sin_addr;

    if (host_is_ip4_address(tpn->tpn_canon) &&
161
	su_inet_pton(AF_INET, tpn->tpn_canon, &iface) > 0) {
162
      imr->imr_interface = iface;
163 164
    }

165
    if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, imr, (sizeof imr)) < 0) {
166 167 168 169
      SU_DEBUG_3(("setsockopt(%s): %s\n",
		  "IP_ADD_MEMBERSHIP", su_strerror(su_errno())));
    }
#if HAVE_IP_MULTICAST_LOOP
170
    else
171
      if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &one, sizeof one) < 0) {
172 173 174 175 176 177 178
	SU_DEBUG_3(("setsockopt(%s): %s\n",
		    "IP_MULTICAST_LOOP", su_strerror(su_errno())));
    }
#endif
  }
#endif

179 180 181 182 183 184 185 186 187 188 189
#if HAVE_IP_MTU_DISCOVER
  {
    /* Turn off DF flag on Linux */
    int dont = IP_PMTUDISC_DONT;
    if (setsockopt(s, IPPROTO_IP, IP_MTU_DISCOVER, &dont, sizeof(dont)) < 0) {
	SU_DEBUG_3(("setsockopt(%s): %s\n",
		    "IP_MTU_DISCOVER", su_strerror(su_errno())));
    }
  }
#endif

190 191
#if HAVE_IP_RECVERR
  if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
192
    if (setsockopt(s, IPPROTO_IP, IP_RECVERR, &one, sizeof(one)) < 0) {
193
      if (ai->ai_family == AF_INET)
194 195
	SU_DEBUG_3(("setsockopt(%s): %s\n",
		    "IPVRECVERR", su_strerror(su_errno())));
196 197 198 199 200 201
    }
    events |= SU_WAIT_ERR;
  }
#endif
#if HAVE_IPV6_RECVERR
  if (ai->ai_family == AF_INET6) {
202
    if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVERR, &one, sizeof(one)) < 0)
203 204 205 206 207
      SU_DEBUG_3(("setsockopt(IPV6_RECVERR): %s\n", su_strerror(su_errno())));
    events |= SU_WAIT_ERR;
  }
#endif

208
  tl_gets(tags,
209 210 211 212
	  TPTAG_UDP_RMEM_REF(rmem),
	  TPTAG_UDP_WMEM_REF(wmem),
	  TAG_END());

213
  if (rmem != 0 &&
214 215 216
#if HAVE_SO_RCVBUFFORCE
      setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, (void *)&rmem, sizeof rmem) < 0 &&
#endif
217
      setsockopt(s, SOL_SOCKET, SO_RCVBUF, (void *)&rmem, sizeof rmem) < 0) {
218
    SU_DEBUG_3(("setsockopt(SO_RCVBUF): %s\n",
219 220 221
		su_strerror(su_errno())));
  }

222
  if (wmem != 0 &&
223 224 225
#if HAVE_SO_SNDBUFFORCE
      setsockopt(s, SOL_SOCKET, SO_SNDBUFFORCE, (void *)&wmem, sizeof wmem) < 0 &&
#endif
226
      setsockopt(s, SOL_SOCKET, SO_SNDBUF, (void *)&wmem, sizeof wmem) < 0) {
227
    SU_DEBUG_3(("setsockopt(SO_SNDBUF): %s\n",
228 229 230 231 232
		su_strerror(su_errno())));
  }

  pri->pri_primary->tp_events = events;

233 234
  tport_init_compressor(pri->pri_primary, tpn->tpn_comp, tags);

235 236
  tport_check_trunc(pri->pri_primary, ai);

237
#if HAVE_SOFIA_STUN
238
  tport_stun_server_add_socket(pri->pri_primary);
239
#endif
240

241 242 243
  return 0;
}

244 245 246 247 248 249 250 251 252 253 254
static
int tport_udp_init_client(tport_primary_t *pri,
			  tp_name_t tpn[1],
			  su_addrinfo_t *ai,
			  tagi_t const *tags,
			  char const **return_culprit)
{
  pri->pri_primary->tp_conn_orient = 1;
  return 0;
}

255 256 257 258
/** Runtime test making sure MSG_TRUNC work as expected */
static void tport_check_trunc(tport_t *tp, su_addrinfo_t *ai)
{
#if HAVE_MSG_TRUNC
259
  ssize_t n;
260 261 262 263
  char buffer[2];
  su_sockaddr_t su[1];
  socklen_t sulen = sizeof su;

264 265
  n = su_sendto(tp->tp_socket,
		"TEST", 4, 0,
Michael Jerris's avatar
Michael Jerris committed
266
		(void *)ai->ai_addr, (socklen_t)ai->ai_addrlen);
267

268 269 270
  if (n != 4)
    return;

271 272
  n = su_recvfrom(tp->tp_socket, buffer, sizeof buffer, MSG_TRUNC,
		  (void *)&su, &sulen);
273

274 275
  if (n > (ssize_t)sizeof buffer) {
    tp->tp_trunc = 1;
276 277
    return;
  }
278 279

  /* XXX - check that su and tp->tp_addrinfo->ai_addr match */
280 281 282
#endif
}

283 284 285
/** Receive datagram.
 *
 * @retval -1 error
286
 * @retval 0  end-of-stream
287 288 289
 * @retval 1  normal receive (should never happen)
 * @retval 2  incomplete recv, call me again (should never happen)
 * @retval 3  STUN keepalive, ignore
290 291 292
 */
int tport_recv_dgram(tport_t *self)
{
293
  msg_t *msg;
294
  ssize_t n, veclen, N;
Pekka Pessi's avatar
Pekka Pessi committed
295
  su_addrinfo_t *ai;
296
  su_sockaddr_t *from;
Pekka Pessi's avatar
Pekka Pessi committed
297
  socklen_t fromlen;
298 299
  msg_iovec_t iovec[msg_n_fragments] = {{ 0 }};
  uint8_t sample[1];
300 301

  /* Simulate packet loss */
302
  if (self->tp_params->tpp_drop &&
303
      (unsigned)su_randint(0, 1000) < self->tp_params->tpp_drop) {
304
    su_recv(self->tp_socket, sample, 1, 0);
305
    SU_DEBUG_3(("tport(%p): simulated packet loss!\n", (void *)self));
306 307 308
    return 0;
  }

309
  assert(self->tp_msg == NULL);
310

311 312 313 314 315 316 317
#if nomore
  /* We used to resize the buffer, but it fragments the memory */
  N = 65535;
#else
  N = (ssize_t)su_getmsgsize(self->tp_socket);
  if (N == -1) {
    int err = su_errno();
318
    SU_DEBUG_1(("%s(%p): su_getmsgsize(): %s (%d)\n", __func__, (void *)self,
319 320 321
		su_strerror(err), err));
    return -1;
  }
322 323 324 325 326
  if (N == 0) {
    su_recv(self->tp_socket, sample, 1, 0);
    SU_DEBUG_3(("tport(%p): zero length packet", (void *)self));
    return 0;
  }
327 328 329 330
#endif

  veclen = tport_recv_iovec(self, &self->tp_msg, iovec, N, 1);
  if (veclen == -1)
331 332
    return -1;

333
  msg = self->tp_msg;
334

Pekka Pessi's avatar
Pekka Pessi committed
335
  ai = msg_addrinfo(msg);
336
  from = (su_sockaddr_t *)ai->ai_addr, fromlen = (socklen_t)(ai->ai_addrlen);
337

Pekka Pessi's avatar
Pekka Pessi committed
338
  n = su_vrecv(self->tp_socket, iovec, veclen, 0, from, &fromlen);
339

Pekka Pessi's avatar
Pekka Pessi committed
340
  ai->ai_addrlen = fromlen;
341

342 343
  if (n == SOCKET_ERROR) {
    int error = su_errno();
344
    msg_destroy(msg); self->tp_msg = NULL;
345
    su_seterrno(error);
346

347
    if (su_is_blocking(error))
348 349 350 351 352
      return 0;
    else
      return -1;
  }
  else if (n <= 1) {
353 354
    SU_DEBUG_1(("%s(%p): runt of "MOD_ZD" bytes\n",
		"tport_recv_dgram", (void *)self, n));
355 356
    msg_destroy(msg), self->tp_msg = NULL;
    return 0;
357 358
  }

359 360
  tport_recv_bytes(self, n, n);

361 362
  SU_CANONIZE_SOCKADDR(from);

363
  if (self->tp_master->mr_dump_file)
364 365
    tport_dump_iovec(self, msg, n, iovec, veclen, "recv", "from");

366
  *sample = *((uint8_t *)iovec[0].mv_base);
367

368 369 370 371 372
  /* Commit received data into buffer. This may relocate iovec contents */
  msg_recv_commit(msg, n, 1);

  if ((sample[0] & 0xf8) == 0xf8)
    /* SigComp */
373
    return tport_recv_comp_dgram(self, self->tp_comp, &self->tp_msg,
374
				 from, fromlen);
375
#if HAVE_SOFIA_STUN
376 377
  else if (sample[0] == 0 || sample[0] == 1)
    /* STUN request or response */
378
    return tport_recv_stun_dgram(self, &self->tp_msg, from, fromlen);
379
#endif
380 381
  else
    return 0;
382 383 384
}

/** Send using su_vsend(). Map IPv4 addresses as IPv6 addresses, if needed. */
385 386
ssize_t tport_send_dgram(tport_t const *self, msg_t *msg,
			 msg_iovec_t iov[],
387
			 size_t iovused)
388
{
389 390
  su_sockaddr_t su[1];
  socklen_t sulen = sizeof su;
391 392 393 394

  if (tport_is_connection_oriented(self))
    return su_vsend(self->tp_socket, iov, iovused, MSG_NOSIGNAL, NULL, 0);

395
  msg_get_address(msg, su, &sulen);
396 397 398

#if SU_HAVE_IN6 && defined(IN6_INADDR_TO_V4MAPPED)
  if (su->su_family == AF_INET && self->tp_addrinfo->ai_family == AF_INET6) {
399 400
    su_sockaddr_t su0[1];

401 402 403 404 405 406 407
    memset(su0, 0, sizeof su0);

    su0->su_family = self->tp_addrinfo->ai_family;
    su0->su_port = su->su_port;

    IN6_INADDR_TO_V4MAPPED(&su->su_sin.sin_addr, &su0->su_sin6.sin6_addr);

408
    memcpy(su, su0, sulen = sizeof(su0->su_sin6));
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  }
#endif

  su_soerror(self->tp_socket); /* XXX - we *still* have a race condition */

  return su_vsend(self->tp_socket, iov, iovused, MSG_NOSIGNAL, su, sulen);
}


#if !HAVE_IP_RECVERR && !HAVE_IPV6_RECVERR

/** Process UDP error event. */
int tport_udp_error(tport_t const *self, su_sockaddr_t name[1])
{
  if (tport_is_connection_oriented(self))
    name[0] = self->tp_addr[0];
  return su_soerror(self->tp_socket);
}

#else

/** Process UDP error event. */
int tport_udp_error(tport_t const *self, su_sockaddr_t name[1])
{
  struct cmsghdr *c;
  struct sock_extended_err *ee;
  su_sockaddr_t *from;
  char control[512];
  char errmsg[64 + 768];
  struct iovec iov[1];
  struct msghdr msg[1] = {{ 0 }};
  int n;

  msg->msg_name = name, msg->msg_namelen = sizeof(*name);
  msg->msg_iov = iov, msg->msg_iovlen = 1;
  iov->iov_base = errmsg, iov->iov_len = sizeof(errmsg);
  msg->msg_control = control, msg->msg_controllen = sizeof(control);

  n = recvmsg(self->tp_socket, msg, MSG_ERRQUEUE);

  if (n < 0) {
    int err = su_errno();
451
    if (!su_is_blocking(err))
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
      SU_DEBUG_1(("%s: recvmsg: %s\n", __func__, su_strerror(err)));
    return 0;
  }

  if ((msg->msg_flags & MSG_ERRQUEUE) != MSG_ERRQUEUE) {
    SU_DEBUG_1(("%s: recvmsg: no errqueue\n", __func__));
    return 0;
  }

  if (msg->msg_flags & MSG_CTRUNC) {
    SU_DEBUG_1(("%s: extended error was truncated\n", __func__));
    return 0;
  }

  if (msg->msg_flags & MSG_TRUNC) {
    /* ICMP message may contain original message... */
    SU_DEBUG_3(("%s: icmp(6) message was truncated (at %d)\n", __func__, n));
  }

  /* Go through the ancillary data */
  for (c = CMSG_FIRSTHDR(msg); c; c = CMSG_NXTHDR(msg, c)) {
    if (0
#if HAVE_IP_RECVERR
475
	|| (c->cmsg_level == IPPROTO_IP && c->cmsg_type == IP_RECVERR)
476 477
#endif
#if HAVE_IPV6_RECVERR
478
	|| (c->cmsg_level == IPPROTO_IPV6 && c->cmsg_type == IPV6_RECVERR)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
#endif
	) {
      char info[128];
      char const *origin;

      ee = (struct sock_extended_err *)CMSG_DATA(c);
      from = (su_sockaddr_t *)SO_EE_OFFENDER(ee);
      info[0] = '\0';

      switch (ee->ee_origin) {
      case SO_EE_ORIGIN_LOCAL:
	origin = "local";
	break;
      case SO_EE_ORIGIN_ICMP:
	origin = "icmp";
494
	snprintf(info, sizeof(info), " type=%u code=%u",
495 496 497 498
		 ee->ee_type, ee->ee_code);
	break;
      case SO_EE_ORIGIN_ICMP6:
	origin = "icmp6";
499
	snprintf(info, sizeof(info), " type=%u code=%u",
500 501 502 503 504 505 506 507 508 509 510
		ee->ee_type, ee->ee_code);
	break;
      case SO_EE_ORIGIN_NONE:
	origin = "none";
	break;
      default:
	origin = "unknown";
	break;
      }

      if (ee->ee_info)
511
	snprintf(info + strlen(info), sizeof(info) - strlen(info),
512 513 514
		 " info=%08x", ee->ee_info);

      SU_DEBUG_3(("%s: %s (%d) [%s%s]\n",
515
		  __func__, su_strerror(ee->ee_errno), ee->ee_errno,
516 517 518
		  origin, info));
      if (from->su_family != AF_UNSPEC)
	SU_DEBUG_3(("\treported by [%s]:%u\n",
519 520
		    su_inet_ntop(from->su_family, SU_ADDR(from),
				 info, sizeof(info)),
521 522 523 524 525 526 527 528 529 530 531 532 533 534
		    ntohs(from->su_port)));

      if (msg->msg_namelen == 0)
	name->su_family = AF_UNSPEC;

      SU_CANONIZE_SOCKADDR(name);

      return ee->ee_errno;
    }
  }

  return 0;
}
#endif