tport_type_tcp.c 13.6 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_tcp.c TCP Transport
26 27 28 29 30 31 32 33 34 35 36 37 38
 *
 * 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"

39 40 41 42
#if HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif

43 44 45 46 47
#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif

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

54 55 56 57
#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
Kai Vehmanen's avatar
Kai Vehmanen committed
58
static char const __func__[] = "tport_type_tcp";
59 60
#endif

61 62 63
/* ---------------------------------------------------------------------- */
/* TCP */

64
tport_vtable_t const tport_tcp_vtable =
65
{
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  /* vtp_name 		     */ "tcp",
  /* vtp_public              */ tport_type_local,
  /* vtp_pri_size            */ sizeof (tport_primary_t),
  /* vtp_init_primary        */ tport_tcp_init_primary,
  /* vtp_deinit_primary      */ NULL,
  /* vtp_wakeup_pri          */ tport_accept,
  /* vtp_connect             */ NULL,
  /* vtp_secondary_size      */ sizeof (tport_t),
  /* vtp_init_secondary      */ tport_tcp_init_secondary,
  /* vtp_deinit_secondary    */ NULL,
  /* vtp_shutdown            */ NULL,
  /* vtp_set_events          */ NULL,
  /* vtp_wakeup              */ NULL,
  /* vtp_recv                */ tport_recv_stream,
  /* vtp_send                */ tport_send_stream,
  /* vtp_deliver             */ NULL,
  /* vtp_prepare             */ NULL,
  /* vtp_keepalive           */ NULL,
  /* vtp_stun_response       */ NULL,
  /* vtp_next_secondary_timer*/ tport_tcp_next_timer,
  /* vtp_secondary_timer     */ tport_tcp_timer,
87 88
};

89
tport_vtable_t const tport_tcp_client_vtable =
90
{
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  /* vtp_name 		     */ "tcp",
  /* vtp_public              */ tport_type_client,
  /* vtp_pri_size            */ sizeof (tport_primary_t),
  /* vtp_init_primary        */ tport_tcp_init_client,
  /* vtp_deinit_primary      */ NULL,
  /* vtp_wakeup_pri          */ NULL,
  /* vtp_connect             */ NULL,
  /* vtp_secondary_size      */ sizeof (tport_t),
  /* vtp_init_secondary      */ tport_tcp_init_secondary,
  /* vtp_deinit_secondary    */ NULL,
  /* vtp_shutdown            */ NULL,
  /* vtp_set_events          */ NULL,
  /* vtp_wakeup              */ NULL,
  /* vtp_recv                */ tport_recv_stream,
  /* vtp_send                */ tport_send_stream,
  /* vtp_deliver             */ NULL,
  /* vtp_prepare             */ NULL,
  /* vtp_keepalive           */ NULL,
  /* vtp_stun_response       */ NULL,
  /* vtp_next_secondary_timer*/ tport_tcp_next_timer,
  /* vtp_secondary_timer     */ tport_tcp_timer,
112 113
};

114 115
static int tport_tcp_setsndbuf(int socket, int atleast);

116
int tport_tcp_init_primary(tport_primary_t *pri,
117
			   tp_name_t tpn[1],
118 119 120 121
			   su_addrinfo_t *ai,
			   tagi_t const *tags,
			   char const **return_culprit)
{
122
  int socket;
123

124
  socket = su_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
125

126
  if (socket == INVALID_SOCKET)
127 128
    return *return_culprit = "socket", -1;

129 130
  tport_tcp_setsndbuf(socket, 64 * 1024);

131 132 133
  return tport_stream_init_primary(pri, socket, tpn, ai, tags, return_culprit);
}

134
int tport_stream_init_primary(tport_primary_t *pri,
135 136 137 138 139 140 141
			      su_socket_t socket,
			      tp_name_t tpn[1],
			      su_addrinfo_t *ai,
			      tagi_t const *tags,
			      char const **return_culprit)
{
  pri->pri_primary->tp_socket = socket;
142

143 144 145
  /* Set IP TOS if set */
  tport_set_tos(socket, ai, pri->pri_params->tpp_tos);

146 147 148
#if defined(__linux__)
  /* Linux does not allow reusing TCP port while this one is open,
     so we can safely call su_setreuseaddr() before bind(). */
149
  su_setreuseaddr(socket, 1);
150 151
#endif

152
  if (tport_bind_socket(socket, ai, return_culprit) == -1)
153
    return -1;
154

155
  if (listen(socket, pri->pri_params->tpp_qsize) == SOCKET_ERROR)
156
    return *return_culprit = "listen", -1;
157 158 159 160 161 162 163

#if !defined(__linux__)
  /* Allow reusing TCP sockets
   *
   * On Solaris & BSD, call setreuseaddr() after bind in order to avoid
   * binding to a port owned by an existing server.
   */
164
  su_setreuseaddr(socket, 1);
165 166 167 168 169 170 171 172
#endif

  pri->pri_primary->tp_events = SU_WAIT_ACCEPT;
  pri->pri_primary->tp_conn_orient = 1;

  return 0;
}

173
int tport_tcp_init_client(tport_primary_t *pri,
174
			  tp_name_t tpn[1],
175 176 177 178 179 180 181 182 183
			  su_addrinfo_t *ai,
			  tagi_t const *tags,
			  char const **return_culprit)
{
  pri->pri_primary->tp_conn_orient = 1;

  return 0;
}

184 185
int tport_tcp_init_secondary(tport_t *self, int socket, int accepted,
			     char const **return_reason)
186 187 188
{
  int one = 1;

189
  self->tp_has_connection = 1;
190 191

  if (setsockopt(socket, SOL_TCP, TCP_NODELAY, (void *)&one, sizeof one) == -1)
192
    return *return_reason = "TCP_NODELAY", -1;
193

194 195 196
  if (!accepted)
    tport_tcp_setsndbuf(socket, 64 * 1024);

197 198 199
  return 0;
}

200 201 202 203 204 205 206
static int tport_tcp_setsndbuf(int socket, int atleast)
{
#if SU_HAVE_WINSOCK2
  /* Set send buffer size to something reasonable on windows */
  int size = 0;
  socklen_t sizelen = sizeof size;

207
  if (getsockopt(socket, SOL_SOCKET, SO_SNDBUF, (void *)&size, &sizelen) < 0)
208 209 210 211 212 213 214 215
    return -1;

  if (sizelen != sizeof size)
    return su_seterrno(EINVAL);

  if (size >= atleast)
    return 0;			/* OK */

216 217
  return setsockopt(socket, SOL_SOCKET, SO_SNDBUF,
		    (void *)&atleast, sizeof atleast);
218 219 220 221 222
#else
  return 0;
#endif
}

223 224 225 226 227
/** Return span of whitespace from buffer */
static inline size_t ws_span(void *buffer, size_t len)
{
  size_t i;
  char const *b = buffer;
228

229 230 231 232 233 234 235 236
  for (i = 0; i < len; i++) {
    if (b[i] != '\r' && b[i] != '\n' && b[i] != ' ' && b[i] != '\t')
      break;
  }

  return i;
}

237 238 239
/** Receive from stream.
 *
 * @retval -1 error
240
 * @retval 0  end-of-stream
241 242
 * @retval 1  normal receive
 * @retval 2  incomplete recv, recv again
243
 *
244 245 246 247
 */
int tport_recv_stream(tport_t *self)
{
  msg_t *msg;
248
  ssize_t n, N, veclen;
249
  int err, initial;
250 251 252 253 254 255 256 257 258 259
  msg_iovec_t iovec[msg_n_fragments] = {{ 0 }};

  N = su_getmsgsize(self->tp_socket);
  if (N == 0) {
    if (self->tp_msg)
      msg_recv_commit(self->tp_msg, 0, 1);
    return 0;    /* End of stream */
  }
  if (N == -1) {
    err = su_errno();
260
    SU_DEBUG_1(("%s(%p): su_getmsgsize(): %s (%d)\n", __func__, (void *)self,
261 262 263 264
		su_strerror(err), err));
    return -1;
  }

265 266 267 268 269 270 271 272
  initial = self->tp_msg == NULL;
  memset(&self->tp_ptime, 0, sizeof self->tp_ptime);

  while (initial && N <= 8) {	/* Check for whitespace */
    char crlf[9];
    size_t i;

    n = su_recv(self->tp_socket, crlf, N, MSG_PEEK);
273 274
    if (n <= 0)
      return (int)n;
275 276 277 278 279 280 281 282 283

    i = ws_span(crlf, n);
    if (i == 0)
      break;

    n = su_recv(self->tp_socket, crlf, i, 0);
    if (n <= 0)
      return (int)n;

284 285
    SU_DEBUG_7(("%s(%p): received keepalive (total %u)\n", __func__,
		(void *)self, self->tp_ping));
286 287 288

    N -= n, self->tp_ping += n;

Pekka Pessi's avatar
Pekka Pessi committed
289 290
    tport_recv_bytes(self, n, n);

291 292 293 294 295 296 297 298 299
    if (N == 0) {
      /* outbound-10 section 3.5.1  - send pong */
      if (self->tp_ping >= 4)
	tport_tcp_pong(self);

      return 1;
    }
  }

300
  veclen = tport_recv_iovec(self, &self->tp_msg, iovec, N, 0);
301
  if (veclen == -1)
302 303 304 305
    return -1;

  msg = self->tp_msg;

306
  msg_set_address(msg, self->tp_addr, (socklen_t)(self->tp_addrlen));
307 308

  n = su_vrecv(self->tp_socket, iovec, veclen, 0, NULL, NULL);
309

310 311 312 313 314
  if (n == SOCKET_ERROR)
    return tport_recv_error_report(self);

  assert(n <= N);

Pekka Pessi's avatar
Pekka Pessi committed
315 316
  tport_recv_bytes(self, n, n);

317 318 319 320 321 322 323 324
  /* Check if message contains only whitespace */
  /* This can happen if multiple PINGs are received at once */
  if (initial) {
    size_t i = ws_span(iovec->siv_base, iovec->siv_len);

    if (i + self->tp_ping >= 4)
      tport_tcp_pong(self);
    else
Michael Jerris's avatar
Michael Jerris committed
325

326
      self->tp_ping += (unsigned short)i;
327 328 329 330 331 332 333 334 335

    if (i == iovec->siv_len && veclen == 1) {
      SU_DEBUG_7(("%s(%p): received %u bytes of keepalive\n",
		  __func__, (void *)self, (unsigned)i));
      msg_destroy(self->tp_msg), self->tp_msg = NULL;
      return 1;
    }
  }

336 337 338 339 340
  /* Write the received data to the message dump file */
  if (self->tp_master->mr_dump_file)
    tport_dump_iovec(self, msg, n, iovec, veclen, "recv", "from");

  /* Mark buffer as used */
341
  msg_recv_commit(msg, n, n == 0);
342

343 344 345
  if (n > 0)
    self->tp_ping = 0;

346
  return n != 0;
347 348
}

349
/** Send to stream */
350 351
ssize_t tport_send_stream(tport_t const *self, msg_t *msg,
			  msg_iovec_t iov[],
352
			  size_t iovused)
353
{
354
#if __sun__			/* XXX - there must be a better way... */
355 356 357 358 359
  if (iovused > 16)
    iovused = 16;
#endif
  return su_vsend(self->tp_socket, iov, iovused, MSG_NOSIGNAL, NULL, 0);
}
360 361 362

/** Calculate timeout if receive is incomplete. */
int tport_next_recv_timeout(tport_t *self,
363
			    su_time_t *return_target,
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
			    char const **return_why)
{
  unsigned timeout = self->tp_params->tpp_timeout;

  if (timeout < INT_MAX) {
    /* Recv timeout */
    if (self->tp_msg) {
      su_time_t ntime = su_time_add(self->tp_rtime, timeout);
      if (su_time_cmp(ntime, *return_target) < 0)
	*return_target = ntime, *return_why = "recv timeout";
    }

#if 0
    /* Send timeout */
    if (tport_has_queued(self)) {
      su_time_t ntime = su_time_add(self->tp_stime, timeout);
      if (su_time_cmp(ntime, *return_target) < 0)
	*return_target = ntime, *return_why = "send timeout";
    }
#endif
  }

  return 0;
}

/** Timeout timer if receive is incomplete */
void tport_recv_timeout_timer(tport_t *self, su_time_t now)
{
  unsigned timeout = self->tp_params->tpp_timeout;

  if (timeout < INT_MAX) {
395
    if (self->tp_msg &&
396 397
	su_time_cmp(su_time_add(self->tp_rtime, timeout), now) < 0) {
      msg_t *msg = self->tp_msg;
Kai Samposalo's avatar
Kai Samposalo committed
398
      msg_set_streaming(msg, (enum msg_streaming_status)0);
399 400 401 402 403 404 405
      msg_set_flags(msg, MSG_FLG_ERROR | MSG_FLG_TRUNC | MSG_FLG_TIMEOUT);
      tport_deliver(self, msg, NULL, NULL, now);
      self->tp_msg = NULL;
    }

#if 0
    /* Send timeout */
406
    if (tport_has_queued(self) &&
407 408 409 410 411 412 413 414 415 416 417
	su_time_cmp(su_time_add(self->tp_stime, timeout), now) < 0) {
      stime = su_time_add(self->tp_stime, self->tp_params->tpp_timeout);
      if (su_time_cmp(stime, target) < 0)
	target = stime;
    }
#endif
  }
}

/** Calculate next timeout for keepalive */
int tport_next_keepalive(tport_t *self,
418
			 su_time_t *return_target,
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 451 452
			 char const **return_why)
{
  /* Keepalive timer */
  unsigned timeout = self->tp_params->tpp_keepalive;

  if (timeout != 0 && timeout != UINT_MAX) {
    if (!tport_has_queued(self)) {
      su_time_t ntime = su_time_add(self->tp_ktime, timeout);
      if (su_time_cmp(ntime, *return_target) < 0)
	*return_target = ntime, *return_why = "keepalive";
    }
  }

  timeout = self->tp_params->tpp_pingpong;
  if (timeout != 0) {
    if (self->tp_ptime.tv_sec && !self->tp_recv_close) {
      su_time_t ntime = su_time_add(self->tp_ptime, timeout);
      if (su_time_cmp(ntime, *return_target) < 0)
	*return_target = ntime, *return_why = "waiting for pong";
    }
  }

  return 0;
}


/** Keepalive timer. */
void tport_keepalive_timer(tport_t *self, su_time_t now)
{
  unsigned timeout = self->tp_params->tpp_pingpong;

  if (timeout != 0) {
    if (self->tp_ptime.tv_sec && !self->tp_recv_close &&
	su_time_cmp(su_time_add(self->tp_ptime, timeout), now) < 0) {
453
      SU_DEBUG_3(("%s(%p): %s to " TPN_FORMAT "%s\n",
454
		  __func__, (void *)self,
455
		  "closing connection", TPN_ARGS(self->tp_name),
456
		  " because of PONG timeout"));
457 458 459
      tport_error_report(self, EPIPE, NULL);
      if (!self->tp_closed)
	tport_close(self);
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
      return;
    }
  }

  timeout = self->tp_params->tpp_keepalive;

  if (timeout != 0 && timeout != UINT_MAX) {
    if (su_time_cmp(su_time_add(self->tp_ktime, timeout), now) < 0) {
      tport_tcp_ping(self, now);
    }
  }
}

/** Send PING */
int tport_tcp_ping(tport_t *self, su_time_t now)
{
  ssize_t n;
  char *why = "";

  if (tport_has_queued(self))
    return 0;

  n = send(self->tp_socket, "\r\n\r\n", 4, 0);
483
  if (n == -1) {
484 485 486
    int error = su_errno();

    why = " failed";
487 488

    if (!su_is_blocking(error))
489 490 491 492 493 494 495
      tport_error_report(self, error, NULL);
    else
      why = " blocking";

    return -1;
  }

496 497 498 499 500 501 502 503
  if (n > 0)
    self->tp_ktime = now;

  if (n == 4) {
    if (self->tp_ptime.tv_sec == 0)
      self->tp_ptime = now;
  }

504
  SU_DEBUG_7(("%s(%p): %s to " TPN_FORMAT "%s\n",
505 506 507
	      __func__, (void *)self,
	      "sending PING", TPN_ARGS(self->tp_name), why));

508
  return 0;
509 510 511 512 513 514 515 516 517 518
}

/** Send pong */
int tport_tcp_pong(tport_t *self)
{
  self->tp_ping = 0;

  if (tport_has_queued(self) || !self->tp_params->tpp_pong2ping)
    return 0;

519
  SU_DEBUG_7(("%s(%p): %s to " TPN_FORMAT "%s\n",
520 521 522 523 524 525 526 527
	      __func__, (void *)self,
	      "sending PONG", TPN_ARGS(self->tp_name), ""));

  return send(self->tp_socket, "\r\n", 2, 0);
}

/** Calculate next timer for TCP. */
int tport_tcp_next_timer(tport_t *self,
528
			 su_time_t *return_target,
529 530
			 char const **return_why)
{
531
  return
532 533 534 535 536 537 538 539 540 541 542
    tport_next_recv_timeout(self, return_target, return_why) |
    tport_next_keepalive(self, return_target, return_why);
}

/** TCP timer. */
void tport_tcp_timer(tport_t *self, su_time_t now)
{
  tport_recv_timeout_timer(self, now);
  tport_keepalive_timer(self, now);
  tport_base_timer(self, now);
}