msg_parser.c 72.5 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 * 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
 *
 */

/**@ingroup msg_parser
 * @CFILE msg_parser.c
 *
 * HTTP-like message parser engine.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 *
 * @date Created: Thu Oct  5 14:01:24 2000 ppessi
 *
 */

/*#define NDEBUG*/

#include "config.h"

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <limits.h>
Pekka Pessi's avatar
Pekka Pessi committed
46
#include <errno.h>
Pekka Pessi's avatar
Pekka Pessi committed
47 48

#include <stdarg.h>
49
#include <sofia-sip/su_tagarg.h>
Pekka Pessi's avatar
Pekka Pessi committed
50

51 52
#include <sofia-sip/su.h>
#include <sofia-sip/su_alloc.h>
Pekka Pessi's avatar
Pekka Pessi committed
53 54

#include "msg_internal.h"
55 56 57 58 59 60
#include "sofia-sip/msg_header.h"
#include "sofia-sip/bnf.h"
#include "sofia-sip/msg_parser.h"
#include "sofia-sip/msg_mclass.h"
#include "sofia-sip/msg_mclass_hash.h"
#include "sofia-sip/msg_mime.h"
Pekka Pessi's avatar
Pekka Pessi committed
61 62 63 64 65 66 67 68 69 70 71 72 73

#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "msg_parser";
#endif

static int _msg_header_add_dup_as(msg_t *msg,
				  msg_pub_t *pub,
				  msg_hclass_t *hc,
				  msg_header_t const *src);

74
static void msg_insert_chain(msg_t *msg, msg_pub_t *pub, int prepend,
Pekka Pessi's avatar
Pekka Pessi committed
75
			     msg_header_t **head, msg_header_t *h);
76
static void msg_insert_here_in_chain(msg_t *msg,
Pekka Pessi's avatar
Pekka Pessi committed
77 78
				     msg_header_t **prev,
				     msg_header_t *h);
79
su_inline msg_header_t *msg_chain_remove(msg_t *msg, msg_header_t *h);
Pekka Pessi's avatar
Pekka Pessi committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

#ifndef NDEBUG
static int msg_chain_loop(msg_header_t const *h);
static int msg_chain_errors(msg_header_t const *h);
#endif

/* ====================================================================== */
/* Message properties */

/** Get message flags. */
unsigned msg_get_flags(msg_t const *msg, unsigned mask)
{
  return msg ? msg->m_object->msg_flags & mask : 0;
}

/** Set message flags. */
unsigned msg_set_flags(msg_t *msg, unsigned mask)
{
  return msg ? msg->m_object->msg_flags |= mask : 0;
}

/** Clear message flags. */
unsigned msg_zap_flags(msg_t *msg, unsigned mask)
{
  return msg ? msg->m_object->msg_flags &= ~mask : 0;
}

/** Test if streaming is in progress. */
int msg_is_streaming(msg_t const *msg)
{
  return msg && msg->m_streaming != 0;
}

/** Enable/disable streaming */
void msg_set_streaming(msg_t *msg, enum msg_streaming_status what)
{
  if (msg)
    msg->m_streaming = what != 0;
}

120 121
/* ---------------------------------------------------------------------- */

Pekka Pessi's avatar
Pekka Pessi committed
122 123 124
/** Test if header is not in the chain */
#define msg_header_is_removed(h) ((h)->sh_prev == NULL)

125
su_inline int msg_is_request(msg_header_t const *h)
Pekka Pessi's avatar
Pekka Pessi committed
126 127 128 129
{
  return h->sh_class->hc_hash == msg_request_hash;
}

130
su_inline int msg_is_status(msg_header_t const *h)
Pekka Pessi's avatar
Pekka Pessi committed
131 132 133 134 135 136 137 138
{
  return h->sh_class->hc_hash == msg_status_hash;
}

/* ====================================================================== */
/* Message buffer management */

/** Allocate a buffer of @a size octets, with slack of #msg_min_size. */
139
void *msg_buf_alloc(msg_t *msg, usize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
140 141
{
  struct msg_mbuffer_s *mb = msg->m_buffer;
142 143
  size_t room = mb->mb_size - mb->mb_commit - mb->mb_used;
  size_t target_size;
Pekka Pessi's avatar
Pekka Pessi committed
144 145 146 147

  if (mb->mb_data && room >= (unsigned)size)
    return mb->mb_data + mb->mb_used + mb->mb_commit;

148
  target_size =
Pekka Pessi's avatar
Pekka Pessi committed
149 150 151 152 153 154
    msg_min_size * ((size + mb->mb_commit) / msg_min_size + 1) - mb->mb_commit;

  return msg_buf_exact(msg, target_size);
}

/** Allocate a buffer exactly of @a size octets, without any slack. */
155
void *msg_buf_exact(msg_t *msg, usize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
156 157
{
  struct msg_mbuffer_s *mb = msg->m_buffer;
158
  size_t room = mb->mb_size - mb->mb_commit - mb->mb_used;
Pekka Pessi's avatar
Pekka Pessi committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  char *buffer;
  int realloc;

  if (mb->mb_data && room >= (unsigned)size)
    return mb->mb_data + mb->mb_used + mb->mb_commit;

  size += mb->mb_commit;

  if (msg->m_maxsize && msg->m_size + size > msg->m_maxsize + 1) {
    msg->m_object->msg_flags |= MSG_FLG_TOOLARGE;
    errno = msg->m_errno = ENOBUFS;
    return NULL;
  }

  realloc = !mb->mb_used && !msg->m_set_buffer;

  if (realloc)
    buffer = su_realloc(msg->m_home, mb->mb_data, size);
177
  else
Pekka Pessi's avatar
Pekka Pessi committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    buffer = su_alloc(msg->m_home, size);

  if (!buffer)
    return NULL;

  if (!realloc && mb->mb_commit && mb->mb_data)
    memcpy(buffer, mb->mb_data + mb->mb_used, mb->mb_commit);

  msg->m_set_buffer = 0;

  mb->mb_data = buffer;
  mb->mb_size = size;
  mb->mb_used = 0;

  return buffer + mb->mb_commit;
}

/** Commit data into buffer. */
196
usize_t msg_buf_commit(msg_t *msg, usize_t size, int eos)
Pekka Pessi's avatar
Pekka Pessi committed
197 198
{
  if (msg) {
199 200 201 202 203 204 205 206 207 208 209 210 211
    struct msg_mbuffer_s *mb = msg->m_buffer;
    assert(mb->mb_used + mb->mb_commit + size <= mb->mb_size);

    mb->mb_commit += size;
    mb->mb_eos = eos;

    if (mb->mb_used == 0 && !msg->m_chunk && !msg->m_set_buffer) {
      size_t slack = mb->mb_size - mb->mb_commit;

      if (eos || slack >= msg_min_size) {
	/* realloc and cut down buffer */
	size_t new_size;
	void *new_data;
212

213 214 215 216 217 218 219 220 221 222 223
	if (eos)
	  new_size = mb->mb_commit + 1;
	else
	  new_size = mb->mb_commit + msg_min_size;

	new_data = su_realloc(msg->m_home, mb->mb_data, new_size);
	if (new_data) {
	  mb->mb_data = new_data, mb->mb_size = new_size;
	}
      }
    }
Pekka Pessi's avatar
Pekka Pessi committed
224 225 226 227 228
  }
  return 0;
}

/** Get length of committed data */
229
usize_t msg_buf_committed(msg_t const *msg)
Pekka Pessi's avatar
Pekka Pessi committed
230 231 232 233 234 235 236 237 238 239
{
  if (msg)
    return msg->m_buffer->mb_commit;
  else
    return 0;
}

/** Get committed data */
void *msg_buf_committed_data(msg_t const *msg)
{
240 241
  return msg && msg->m_buffer->mb_data ?
    msg->m_buffer->mb_data + msg->m_buffer->mb_used
Pekka Pessi's avatar
Pekka Pessi committed
242 243 244
    : NULL;
}

245
usize_t msg_buf_size(msg_t const *msg)
Pekka Pessi's avatar
Pekka Pessi committed
246 247 248
{
  assert(msg);
  if (msg) {
249
    struct msg_mbuffer_s const *mb = msg->m_buffer;
Pekka Pessi's avatar
Pekka Pessi committed
250 251 252 253 254 255
    return mb->mb_size - mb->mb_commit - mb->mb_used;
  }
  else
    return 0;
}

256
su_inline
257
void msg_buf_used(msg_t *msg, usize_t used)
Pekka Pessi's avatar
Pekka Pessi committed
258 259 260 261 262 263 264 265 266 267
{
  msg->m_size += used;
  msg->m_buffer->mb_used += used;
  if (msg->m_buffer->mb_commit > used)
    msg->m_buffer->mb_commit -= used;
  else
    msg->m_buffer->mb_commit = 0;
}

/** Set buffer. */
268
void msg_buf_set(msg_t *msg, void *b, usize_t size)
Pekka Pessi's avatar
Pekka Pessi committed
269 270 271
{
  if (msg) {
    struct msg_mbuffer_s *mb = msg->m_buffer;
272

Pekka Pessi's avatar
Pekka Pessi committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    assert(!msg->m_set_buffer);	/* This can be set only once */

    mb->mb_data = b;
    mb->mb_size = size;
    mb->mb_used = 0;
    mb->mb_commit = 0;
    mb->mb_eos  = 0;

    msg->m_set_buffer = 1;
  }
}

/** Move unparsed data from src to dst */
void *msg_buf_move(msg_t *dst, msg_t const *src)
{
  void *retval;
  struct msg_mbuffer_s *db = dst->m_buffer;
  struct msg_mbuffer_s const *sb = src->m_buffer;
291 292

  if (!dst || !src)
Pekka Pessi's avatar
Pekka Pessi committed
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    return NULL;

  if (sb->mb_eos)
    retval = msg_buf_exact(dst, sb->mb_commit + 1);
  else
    retval = msg_buf_alloc(dst, sb->mb_commit + 1);

  if (retval == NULL)
    return NULL;

  memcpy(retval, sb->mb_data + sb->mb_used, sb->mb_commit);

  db->mb_commit += sb->mb_commit;
  db->mb_eos = sb->mb_eos;

  return retval;
}

311
/**Obtain I/O vector for receiving the data.
Pekka Pessi's avatar
Pekka Pessi committed
312
 *
313
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
314
 *
315 316
 * Allocate buffers for receiving @a n bytes
 * of data available from network. Function returns the buffers in the I/O vector
Pekka Pessi's avatar
Pekka Pessi committed
317 318 319 320 321 322
 * @a vec. The @a vec is allocated by the caller, the available length is
 * given as @a veclen. If the protocol is message-oriented like UDP or SCTP
 * and the available data ends at message boundary, the caller should set
 * the @a exact as 1. Otherwise some extra buffer (known as @em slack) is
 * allocated).
 *
323 324 325
 * Currently, the msg_recv_iovec() allocates receive buffers in at most two
 * blocks, so the caller should allocate at least two elements for the I/O
 * vector @a vec.
Pekka Pessi's avatar
Pekka Pessi committed
326
 *
327 328 329
 * @param[in]  msg     message object
 * @param[out] vec     I/O vector
 * @param[in]  veclen  available length of @a vec
330
 * @param[in]  n       number of possibly available bytes
331
 * @param[in]  exact   true if data ends at message boundary
Pekka Pessi's avatar
Pekka Pessi committed
332 333
 *
 * @return
334
 * The length of I/O vector to
Pekka Pessi's avatar
Pekka Pessi committed
335
 * receive data, 0 if there are not enough buffers, or -1 upon an error.
336 337
 *
 * @sa msg_iovec(), su_vrecv()
Pekka Pessi's avatar
Pekka Pessi committed
338
 */
339 340
issize_t msg_recv_iovec(msg_t *msg, msg_iovec_t vec[], isize_t veclen,
			usize_t n, int exact)
Pekka Pessi's avatar
Pekka Pessi committed
341
{
342 343
  size_t i = 0;
  size_t len = 0;
Pekka Pessi's avatar
Pekka Pessi committed
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  msg_payload_t *chunk;
  char *buf;

  if (n == 0)
    return 0;

  if (veclen == 0)
    vec = NULL;

  for (chunk = msg->m_chunk; chunk; chunk = MSG_CHUNK_NEXT(chunk)) {
    buf = MSG_CHUNK_BUFFER(chunk);
    len = MSG_CHUNK_AVAIL(chunk);

    if (len == 0)
      continue;
    if (!buf)
      break;
361

362 363 364 365 366
#if SU_HAVE_WINSOCK
    /* WSABUF has u_long */
    if (len > SU_IOVECLEN_MAX)
      len = SU_IOVECLEN_MAX;
#endif
Pekka Pessi's avatar
Pekka Pessi committed
367 368 369
    if (len > n)
      len = n;
    if (vec)
370
      vec[i].mv_base = buf, vec[i].mv_len = (su_ioveclen_t)len;
Pekka Pessi's avatar
Pekka Pessi committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    i++;
    if (len == n)
      return i;
    if (i == veclen)
      vec = NULL;
    n -= len;
  }

  if (!chunk && msg->m_chunk && msg_get_flags(msg, MSG_FLG_FRAGS)) {
    /*
     * If the m_chunk is the last fragment for this message,
     * receive rest of the data to the next message
     */
    if (msg->m_next == NULL)
      msg->m_next = msg_create(msg->m_class, msg->m_oflags);
    if (msg->m_next) {
      msg->m_next->m_maxsize = msg->m_maxsize;
      msg_addr_copy(msg->m_next, msg);
    }
    msg = msg->m_next;
    if (msg == NULL)
      return 0;
  }

  if (exact)
    buf = msg_buf_exact(msg, n + 1), len = n;
  else if (chunk && len > n && !msg_get_flags(msg, MSG_FLG_CHUNKING))
    buf = msg_buf_exact(msg, len + 1);
  else
    buf = msg_buf_alloc(msg, n + 1), len = msg_buf_size(msg);

  if (buf == NULL)
    return -1;

  if (vec)
406
    vec[i].mv_base = buf, vec[i].mv_len = (su_ioveclen_t)n;
Pekka Pessi's avatar
Pekka Pessi committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

  if (chunk) {
    assert(chunk->pl_data == NULL); assert(chunk->pl_common->h_len == 0);

    chunk->pl_common->h_data = chunk->pl_data = buf;

    if (len < MSG_CHUNK_AVAIL(chunk)) {
      msg_header_t *h = (void*)chunk;
      h->sh_succ = msg_header_alloc(msg_home(msg), h->sh_class, 0);
      if (!h->sh_succ)
	return -1;
      h->sh_succ->sh_prev = &h->sh_succ;
      chunk->pl_next = (msg_payload_t *)h->sh_succ;
      chunk->pl_next->pl_len = chunk->pl_len - len;
      chunk->pl_len = len;
422 423
    }
    else if (len > MSG_CHUNK_AVAIL(chunk)) {
Pekka Pessi's avatar
Pekka Pessi committed
424 425 426 427 428 429 430 431 432 433 434 435 436
      len = MSG_CHUNK_AVAIL(chunk);
    }

    msg_buf_used(msg, len);
  }

  return i + 1;

#if 0
  if ((msg->m_ssize || msg->m_stream)
      /* && msg_get_flags(msg, MSG_FLG_BODY) */) {
    /* Streaming */
    msg_buffer_t *b, *b0;
437

Pekka Pessi's avatar
Pekka Pessi committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
    /* Calculate available size of current buffers */
    for (b = msg->m_stream, len = 0; b && n > len; b = b->b_next)
      len += b->b_avail - b->b_size;

    /* Allocate new buffers */
    if (n > len && msg_buf_external(msg, n, 0) < 0)
      return -1;

    for (b0 = msg->m_stream; b0; b0 = b0->b_next)
      if (b0->b_avail != b0->b_size)
	break;

    for (b = b0; b && n > 0; i++, b = b->b_next) {
      len = b->b_size - b->b_avail;
      len = n < len ? n : len;
      if (vec && i < veclen)
	vec[i].mv_base = b->b_data + b->b_avail, vec[i].mv_len = len;
      else
	vec = NULL;
      n -= len;
    }

    return i + 1;
  }
#endif
}

465

466 467 468 469
/** Obtain a buffer for receiving data.
 *
 * @relatesalso msg_s
 */
470
issize_t msg_recv_buffer(msg_t *msg, void **return_buffer)
Pekka Pessi's avatar
Pekka Pessi committed
471 472 473 474 475 476 477 478 479 480 481 482 483
{
  void *buffer;

  if (!msg)
    return -1;

  if (return_buffer == NULL)
    return_buffer = &buffer;

  if (msg->m_chunk) {
    msg_payload_t *pl;

    for (pl = msg->m_chunk; pl; pl = pl->pl_next) {
484
      size_t n = MSG_CHUNK_AVAIL(pl);
Pekka Pessi's avatar
Pekka Pessi committed
485 486 487 488 489 490 491
      if (n) {
	*return_buffer = MSG_CHUNK_BUFFER(pl);
	return n;
      }
    }

    return 0;
492
  }
Pekka Pessi's avatar
Pekka Pessi committed
493 494 495 496

  if (msg_get_flags(msg, MSG_FLG_FRAGS)) {
    /* Message is complete */
    return 0;
497 498
  }
  else if ((*return_buffer = msg_buf_alloc(msg, 2))) {
Pekka Pessi's avatar
Pekka Pessi committed
499
    return msg_buf_size(msg) - 1;
500 501
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
502
    return -1;
503
  }
Pekka Pessi's avatar
Pekka Pessi committed
504 505 506 507 508 509
}



/**Commit @a n bytes of buffers.
 *
510
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
511 512 513 514 515 516 517
 *
 * The function msg_recv_commit() is called after @a n bytes of data has
 * been received to the message buffers and the parser can extract the
 * received data.
 *
 * @param msg pointer to message object
 * @param n   number of bytes received
518
 * @param eos true if stream is complete
Pekka Pessi's avatar
Pekka Pessi committed
519 520
 *
 * @note The @a eos should be always true for message-based transports. It
521 522
 * should also be true when a stram oin stream-based transport ends, for
 * instance, when TCP FIN is received.
523
 *
524 525
 * @retval 0 when successful
 * @retval -1 upon an error.
Pekka Pessi's avatar
Pekka Pessi committed
526
 */
527
isize_t msg_recv_commit(msg_t *msg, usize_t n, int eos)
Pekka Pessi's avatar
Pekka Pessi committed
528 529 530 531 532 533 534
{
  msg_payload_t *pl;

  if (eos)
    msg->m_buffer->mb_eos = 1;

  for (pl = msg->m_chunk; pl; pl = pl->pl_next) {
535
    size_t len = MSG_CHUNK_AVAIL(pl);
Pekka Pessi's avatar
Pekka Pessi committed
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

    if (n <= len)
      len = n;

    pl->pl_common->h_len += len;

    n -= len;

    if (n == 0)
      return 0;
  }

  if (msg->m_chunk && msg->m_next)
    msg = msg->m_next;

  return msg_buf_commit(msg, n, eos);
}

554
/**Get a next message of the stream.
Pekka Pessi's avatar
Pekka Pessi committed
555
 *
556
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
557 558 559 560 561 562 563 564 565 566
 *
 * When parsing a transport stream, only the first message in the stream is
 * created with msg_create(). The rest of the messages should be created
 * with msg_next() after previous message has been completely received and
 * parsed.
 *
 */
msg_t *msg_next(msg_t *msg)
{
  msg_t *next;
567
  usize_t n;
Pekka Pessi's avatar
Pekka Pessi committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586

  if (msg && msg->m_next) {
    next = msg->m_next;
    msg->m_next = NULL;
    return next;
  }

  if ((n = msg_buf_committed(msg))) {
    if (msg_buf_move(next = msg_create(msg->m_class, msg->m_oflags), msg)) {
      msg_addr_copy(next, msg);
      return next;
    }
    /* How to indicate error? */
    msg_destroy(next);
  }

  return NULL;
}

587 588 589 590
/** Set next message of the stream.
 *
 * @relatesalso msg_s
 */
Pekka Pessi's avatar
Pekka Pessi committed
591 592 593 594 595
int msg_set_next(msg_t *msg, msg_t *next)
{
  if (!msg || (next && next->m_next))
    return -1;

596
  if (msg->m_next && next)
Pekka Pessi's avatar
Pekka Pessi committed
597 598 599
    next->m_next = msg->m_next;

  msg->m_next = next;
600

Pekka Pessi's avatar
Pekka Pessi committed
601 602 603
  return 0;
}

604 605 606 607
/** Clear committed data.
 *
 * @relatesalso msg_s
 */
Pekka Pessi's avatar
Pekka Pessi committed
608 609 610
void msg_clear_committed(msg_t *msg)
{
  if (msg) {
611
    usize_t n = msg_buf_committed(msg);
Pekka Pessi's avatar
Pekka Pessi committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646

    if (n)
      msg_buf_used(msg, n);
  }
}

#if 0
struct sigcomp_udvm;

struct sigcomp_udvm *msg_get_udvm(msg_t *msg);
struct sigcomp_udvm *msg_set_udvm(msg_t *msg, struct sigcomp_udvm *);

/** Save UDVM. */
struct sigcomp_udvm *msg_set_udvm(msg_t *msg, struct sigcomp_udvm *udvm)
{
  struct sigcomp_udvm *prev = NULL;

  if (msg) {
    prev = msg->m_udvm;
    msg->m_udvm = udvm;
  }

  return prev;
}

/** Get saved UDVM */
struct sigcomp_udvm *msg_get_udvm(msg_t *msg)
{
  return msg ? msg->m_udvm : NULL;
}

#endif

/** Mark message as complete.
 *
647
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
648 649 650 651 652 653
 */
unsigned msg_mark_as_complete(msg_t *msg, unsigned mask)
{
  if (msg) {
    msg->m_streaming = 0;
    return msg->m_object->msg_flags |= mask | MSG_FLG_COMPLETE;
654 655
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
656 657 658 659 660 661
    return 0;
  }
}

/** Return true if message is complete.
 *
662
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
663 664 665 666 667 668
 */
int msg_is_complete(msg_t const *msg)
{
  return msg && MSG_IS_COMPLETE(msg->m_object);
}

669
/** Return true if message has parsing errors.
Pekka Pessi's avatar
Pekka Pessi committed
670
 *
671
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
672 673 674 675 676 677 678 679
*/
int msg_has_error(msg_t const *msg)
{
  return msg->m_object->msg_flags & MSG_FLG_ERROR;
}

/**Total size of message.
 *
680
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
681
 */
682
usize_t msg_size(msg_t const *msg)
Pekka Pessi's avatar
Pekka Pessi committed
683 684 685 686 687 688
{
  return msg ? msg->m_size : 0;
}

/** Set the maximum size of a message.
 *
689
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
690 691 692 693 694 695 696 697
 *
 * The function msg_maxsize() sets the maximum buffer size of a message. It
 * returns the previous maximum size. If the @a maxsize is 0, maximum size
 * is not set, but the current maximum size is returned.
 *
 * If the message size exceeds maxsize, msg_errno() returns ENOBUFS,
 * MSG_FLG_TOOLARGE and MSG_FLG_ERROR flags are set.
 */
698
usize_t msg_maxsize(msg_t *msg, usize_t maxsize)
Pekka Pessi's avatar
Pekka Pessi committed
699
{
700
  usize_t retval = 0;
Pekka Pessi's avatar
Pekka Pessi committed
701 702 703 704 705 706 707 708 709 710 711 712

  if (msg) {
    retval = msg->m_maxsize;
    if (maxsize)
      msg->m_maxsize = maxsize;
  }

  return retval;
}

/**Set the size of next fragment.
 *
713
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
714 715
 *
 * The function msg_streaming_size() sets the size of the message body for
716
 * streaming.
Pekka Pessi's avatar
Pekka Pessi committed
717
 */
718
int msg_streaming_size(msg_t *msg, usize_t ssize)
Pekka Pessi's avatar
Pekka Pessi committed
719 720 721
{
  if (!msg)
    return -1;
722

Pekka Pessi's avatar
Pekka Pessi committed
723 724 725 726 727 728 729
  msg->m_ssize = ssize;

  return 0;
}

/**Allocate a list of external buffers.
 *
730
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
731 732 733 734 735 736 737
 *
 * The function msg_buf_external() allocates at most msg_n_fragments
 * external buffers for the message body.
 *
 * @return The function msg_buf_external() returns number of allocated
 * buffers, or -1 upon an error.
 */
738 739 740
issize_t msg_buf_external(msg_t *msg,
			  usize_t N,
			  usize_t blocksize)
Pekka Pessi's avatar
Pekka Pessi committed
741 742
{
  msg_buffer_t *ext, *b, **bb;
743
  size_t i, I;
Pekka Pessi's avatar
Pekka Pessi committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

  assert(N <= 128 * 1024);

  if (msg == NULL)
    return -1;
  if (blocksize == 0)
    blocksize = msg_min_block;
  if (N == 0)
    N = blocksize;
  if (N > blocksize * msg_n_fragments)
    N = blocksize * msg_n_fragments;
  if (N > msg->m_ssize)
    N = msg->m_ssize;

  I = (N + blocksize - 1) / blocksize; assert(I <= msg_n_fragments);
759

Pekka Pessi's avatar
Pekka Pessi committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
  for (i = 0, bb = &ext; i < I; i++) {
    *bb = su_zalloc(msg_home(msg), sizeof **bb);
    if (!*bb)
      break;
    bb = &(*bb)->b_next;
  }

  if (i == I)
    for (b = ext, i = 0; b; b = b->b_next, i++) {
      b->b_data = su_alloc(msg_home(msg), b->b_size = blocksize);
      if (!b->b_data)
	break;
    }

  if (i == I) {
    /* Successful return */
    for (bb = &msg->m_stream; *bb; bb = &(*bb)->b_next)
      ;

    *bb = ext;

    if (msg->m_ssize != MSG_SSIZE_MAX)
      for (b = ext; b; b = b->b_next) {
	if (msg->m_ssize < b->b_size) {
	  b->b_size = msg->m_ssize;
785
	}
Pekka Pessi's avatar
Pekka Pessi committed
786 787
	msg->m_ssize -= b->b_size;
      }
788

Pekka Pessi's avatar
Pekka Pessi committed
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    return i;
  }

  for (b = ext; b; b = ext) {
    ext = b->b_next;
    su_free(msg_home(msg), b->b_data);
    su_free(msg_home(msg), b);
  }

  return -1;
}

int msg_unref_external(msg_t *msg, msg_buffer_t *b)
{
  if (msg && b) {
    su_free(msg_home(msg), b->b_data);
    su_free(msg_home(msg), b);
    return 0;
  }
  errno = EINVAL;
  return -1;
}

/* ====================================================================== */
/* Parsing messages */

815
su_inline int extract_incomplete_chunks(msg_t *, int eos);
816 817
static issize_t extract_first(msg_t *, msg_pub_t *,
			    char b[], isize_t bsiz, int eos);
818
su_inline issize_t extract_next(msg_t *, msg_pub_t *, char *, isize_t bsiz,
819 820 821
				  int eos, int copy);
static issize_t extract_header(msg_t *, msg_pub_t*,
			     char b[], isize_t bsiz, int eos, int copy);
822
static msg_header_t *header_parse(msg_t *, msg_pub_t *, msg_href_t const *,
823
				  char s[], isize_t slen, int copy_buffer);
824 825
static msg_header_t *error_header_parse(msg_t *msg, msg_pub_t *mo,
					msg_href_t const *hr);
826
su_inline issize_t
Pekka Pessi's avatar
Pekka Pessi committed
827
extract_trailers(msg_t *msg, msg_pub_t *mo,
828
		 char *b, isize_t bsiz, int eos, int copy);
Pekka Pessi's avatar
Pekka Pessi committed
829

830
/** Calculate length of line ending (0, 1 or 2). @internal */
Pekka Pessi's avatar
Pekka Pessi committed
831 832
#define CRLF_TEST(b) ((b)[0] == '\r' ? ((b)[1] == '\n') + 1 : (b)[0] =='\n')

833
su_inline void
834
append_parsed(msg_t *msg, msg_pub_t *mo, msg_href_t const *hr, msg_header_t *h,
Pekka Pessi's avatar
Pekka Pessi committed
835 836 837 838
	      int always_into_chain);

/**Extract and parse a message from internal buffer.
 *
839
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
 *
 * This function parses the internal buffer and adds the parsed fragments to
 * the message object. It marks the successfully parsed data as extracted.
 *
 * @param msg message to be parsed
 *
 * @retval positive if a complete message was parsed
 * @retval 0 if message was incomplete
 * @retval negative if an error occurred
 */
int msg_extract(msg_t *msg)
{
  msg_pub_t *mo = msg_object(msg);
  msg_mclass_t const *mc;
  char *b;
855 856 857
  ssize_t m;
  size_t bsiz;
  int eos;
Pekka Pessi's avatar
Pekka Pessi committed
858 859 860 861 862 863 864 865 866 867 868

  if (!msg || !msg->m_buffer->mb_data)
    return -1;

  assert(mo);

  mc = msg->m_class;
  mo = msg->m_object;
  eos = msg->m_buffer->mb_eos;

  if (msg->m_chunk) {
869 870 871
    int incomplete = extract_incomplete_chunks(msg, eos);
    if (incomplete < 1 || MSG_IS_COMPLETE(mo))
      return incomplete;
Pekka Pessi's avatar
Pekka Pessi committed
872 873 874 875 876
  }

  if (mo->msg_flags & MSG_FLG_TRAILERS)
    msg_set_streaming(msg, 0);

877
  if (msg->m_buffer->mb_used + msg->m_buffer->mb_commit ==
Pekka Pessi's avatar
Pekka Pessi committed
878 879 880 881
      msg->m_buffer->mb_size)
    /* Why? When? */
    return 0;

882
  assert(msg->m_buffer->mb_used + msg->m_buffer->mb_commit <
Pekka Pessi's avatar
Pekka Pessi committed
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
	 msg->m_buffer->mb_size);

  m = 0;

  b = msg->m_buffer->mb_data + msg->m_buffer->mb_used;
  bsiz = msg->m_buffer->mb_commit;
  b[bsiz] = '\0';

  while (msg->m_buffer->mb_commit > 0) {
    int flags = mo->msg_flags;
    int copy = MSG_IS_EXTRACT_COPY(flags);

    if (flags & MSG_FLG_COMPLETE)
      break;

    if (flags & MSG_FLG_TRAILERS)
      m = extract_trailers(msg, mo, b, bsiz, eos, copy);
    else if (flags & MSG_FLG_BODY)
      m = mc->mc_extract_body(msg, mo, b, bsiz, eos);
    else if (flags & MSG_FLG_HEADERS)
      m = extract_next(msg, mo, b, bsiz, eos, copy);
904
    else
Pekka Pessi's avatar
Pekka Pessi committed
905 906 907 908 909 910 911 912
      m = extract_first(msg, mo, b, bsiz, eos);

    if (m <= 0 || msg->m_chunk)
      break;

    b += m;
    bsiz -= m;

913
    msg_buf_used(msg, (size_t)m);
Pekka Pessi's avatar
Pekka Pessi committed
914 915 916 917
  }

  if (eos && bsiz == 0)
    msg_mark_as_complete(msg, 0);
918

Pekka Pessi's avatar
Pekka Pessi committed
919 920 921 922 923 924 925 926 927 928 929 930 931 932
  if (m < 0 || (mo->msg_flags & MSG_FLG_ERROR)) {
    msg_mark_as_complete(msg, MSG_FLG_ERROR);
    return -1;
  }
  else if (!MSG_IS_COMPLETE(mo))
    return 0;
  else if (!(mo->msg_flags & MSG_FLG_HEADERS)) {
    msg_mark_as_complete(msg, MSG_FLG_ERROR);
    return -1;
  }
  else
    return 1;
}

933
static
934
issize_t extract_first(msg_t *msg, msg_pub_t *mo, char b[], isize_t bsiz, int eos)
Pekka Pessi's avatar
Pekka Pessi committed
935 936
{
  /* First line */
937 938
  size_t k, l, m, n, xtra;
  int crlf;
939
  msg_header_t *h;
940
  msg_href_t const *hr;
Pekka Pessi's avatar
Pekka Pessi committed
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
  msg_mclass_t const *mc = msg->m_class;

  for (k = 0; IS_LWS(b[k]); k++) /* Skip whitespace */
    ;
  if (!b[k]) return k;

  /* If first token contains no /, this is request, otherwise status line */
  l = span_token(b + k) + k;
  if (b[l] != '/')
    hr = mc->mc_request;
  else
    hr = mc->mc_status;

  n = span_non_crlf(b + l) + l;
  if (!b[n])
    return eos ? -1 : 0;
  crlf = CRLF_TEST(b + n);
958

Pekka Pessi's avatar
Pekka Pessi committed
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
  for (m = n + crlf; IS_WS(b[m]); m++)
    ;
  /* In order to skip possible whitespace after first line, we don't parse
     first line until first non-ws char from next one has been received */
  if (!b[m] && !eos)
    return 0;

  xtra = MSG_IS_EXTRACT_COPY(mo->msg_flags) ? n + 1 - k : 0;
  if (!(h = msg_header_alloc(msg_home(msg), hr->hr_class, xtra)))
    return -1;

  if (xtra) {
    char *bb = memcpy(MSG_HEADER_DATA(h), b, xtra - 1);
    h->sh_data = b, h->sh_len = n + crlf;
    b = bb; n = xtra - 1;
  }
  else {
    b = b + k; n = n - k;
  }

979
  b[n] = 0;
Pekka Pessi's avatar
Pekka Pessi committed
980 981 982 983 984 985

  if (hr->hr_class->hc_parse(msg_home(msg), h, b, n) < 0)
    return -1;

  assert(hr->hr_offset);

986
  append_parsed(msg, mo, hr, h, 1);
Pekka Pessi's avatar
Pekka Pessi committed
987 988 989 990 991 992 993

  mo->msg_flags |= MSG_FLG_HEADERS;

  return m;
}

/* Extract header or message body */
994
su_inline issize_t
995
extract_next(msg_t *msg, msg_pub_t *mo, char *b, isize_t bsiz,
996
	     int eos, int copy)
Pekka Pessi's avatar
Pekka Pessi committed
997 998 999 1000 1001 1002 1003 1004
{
  if (IS_CRLF(b[0]))
    return msg->m_class->mc_extract_body(msg, mo, b, bsiz, eos);
  else
    return extract_header(msg, mo, b, bsiz, eos, copy);
}

/** Extract a header. */
1005
issize_t msg_extract_header(msg_t *msg, msg_pub_t *mo,
1006
			   char b[], isize_t bsiz, int eos)
Pekka Pessi's avatar
Pekka Pessi committed
1007 1008 1009 1010 1011 1012
{
  return extract_header(msg, mo, b, bsiz, eos, 0);
}

/** Extract a header from buffer @a b.
 */
1013
static
1014 1015
issize_t
extract_header(msg_t *msg, msg_pub_t *mo, char *b, isize_t bsiz, int eos,
Pekka Pessi's avatar
Pekka Pessi committed
1016 1017
	       int copy_buffer)
{
1018 1019 1020 1021 1022
  size_t len, m;
  size_t name_len = 0, xtra;
  isize_t n = 0;
  int crlf = 0, name_len_set = 0;
  int error = 0;
Pekka Pessi's avatar
Pekka Pessi committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
  msg_header_t *h;
  msg_href_t const *hr;
  msg_mclass_t const *mc = msg->m_class;

  hr = msg_find_hclass(mc, b, &n); /* Get header name */
  error = n == 0;
  if (hr == NULL)		/* Panic */
    return -1;

  xtra = span_ws(b + n);

  /* Find next crlf which is not followed by whitespace */
  do {
    n += xtra + crlf;
    if (!eos && bsiz == n)
      return 0;
    m = span_non_crlf(b + n);
    if (!name_len_set && m)
      name_len = n, name_len_set = 1; /* First non-ws after COLON */
    n += m;
    crlf = CRLF_TEST(b + n);
    xtra = span_ws(b + n + crlf);
  }
  while (xtra);

  if (!eos && bsiz == n + crlf)
    return 0;

  if (hr->hr_class->hc_hash == msg_unknown_hash)
    name_len = 0, name_len_set = 1;

  if (error) {
    msg->m_extract_err |= hr->hr_flags;
    if (hr->hr_class->hc_critical)
      mo->msg_flags |= MSG_FLG_ERROR;
    hr = mc->mc_error;
    copy_buffer = 1;
1060
    h = error_header_parse(msg, mo, hr);
Pekka Pessi's avatar
Pekka Pessi committed
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
  }
  else {
    if (!name_len_set)
      /* Empty header - nothing but name, COLON and LWS */
      name_len = n;
    else
      /* Strip extra whitespace at the end of header */
      while (n > name_len && IS_LWS(b[n - 1]))
	n--, crlf++;

    h = header_parse(msg, mo, hr, b + name_len, n - name_len, copy_buffer);
  }

  if (h == NULL)
    return -1;

  len = n + crlf;

  /*
   * If the header contains multiple header fields, set the pointer to the
   * encodeded data correctly
   */
  while (h) {
    if (copy_buffer)
      h->sh_data = b, h->sh_len = len;
    b += len, len = 0;
    if (h->sh_succ)
      assert(&h->sh_succ == h->sh_succ->sh_prev);
    h = h->sh_next;
  }

  return n + crlf;
}

1095 1096 1097
static
msg_header_t *header_parse(msg_t *msg, msg_pub_t *mo,
			   msg_href_t const *hr,
1098
			   char s[], isize_t slen,
Pekka Pessi's avatar
Pekka Pessi committed
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
			   int copy_buffer)
{
  su_home_t *home = msg_home(msg);
  msg_header_t *h, **hh;
  msg_hclass_t *hc = hr->hr_class;
  int n;
  int add_to_list, clear = 0;

  hh = (msg_header_t **)((char *)mo + hr->hr_offset);

  add_to_list = (hc->hc_kind == msg_kind_list && !copy_buffer && *hh);

  if (add_to_list)
    h = *hh;
  else
    h = msg_header_alloc(home, hc, copy_buffer ? slen + 1 : 0);
1115 1116

  if (!h)
Pekka Pessi's avatar
Pekka Pessi committed
1117 1118
    return NULL;

1119 1120
  if (copy_buffer)
    s = memcpy(MSG_HEADER_DATA(h), s, slen);
Pekka Pessi's avatar
Pekka Pessi committed
1121

1122
  s[slen] = '\0';
Pekka Pessi's avatar
Pekka Pessi committed
1123

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
  if (hc->hc_kind == msg_kind_list && *hh) {
    n = hc->hc_parse(home, *hh, s, slen);
    /* Clear if adding new header disturbs existing headers */
    clear = *hh != h && !copy_buffer;
    if (clear)
      msg_fragment_clear((*hh)->sh_common);
  }
  else
    n = hc->hc_parse(home, h, s, slen);

  if (n < 0) {
    msg->m_extract_err |= hr->hr_flags;

    if (hc->hc_critical)
      mo->msg_flags |= MSG_FLG_ERROR;

    clear = 0;

    if (!add_to_list) {
      /* XXX - This should be done by msg_header_free_all() */
      msg_header_t *h_next;
      msg_param_t *h_params;
Pekka Pessi's avatar
Pekka Pessi committed
1146

1147 1148 1149 1150 1151 1152 1153 1154 1155
      while (h) {
	h_next = h->sh_next;
	if (hc->hc_params) {
	  h_params = *(msg_param_t **)((char *)h + hc->hc_params);
	  if (h_params)
	    su_free(home, h_params);
	}
	su_free(home, h);
	h = h_next;
Pekka Pessi's avatar
Pekka Pessi committed
1156
      }
1157 1158 1159 1160 1161 1162 1163 1164
      /* XXX - This should be done by msg_header_free_all() */
      hr = msg->m_class->mc_error;
      h = msg_header_alloc(home, hr->hr_class, 0);
      if (!h)
	return h;

      h->sh_error->er_name = hc->hc_name;
      hh = (msg_header_t **)((char *)mo + hr->hr_offset);
Pekka Pessi's avatar
Pekka Pessi committed
1165 1166 1167 1168 1169 1170 1171
    }
  }

  if (clear)
    for (hh = &(*hh)->sh_next; *hh; *hh = (*hh)->sh_next)
      msg_chain_remove(msg, *hh);
  else if (h != *hh)
1172
    append_parsed(msg, mo, hr, h, 0);
Pekka Pessi's avatar
Pekka Pessi committed
1173 1174 1175 1176

  return h;
}

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
static
msg_header_t *error_header_parse(msg_t *msg, msg_pub_t *mo,
				 msg_href_t const *hr)
{
  msg_header_t *h;

  h = msg_header_alloc(msg_home(msg), hr->hr_class, 0);
  if (h)
    append_parsed(msg, mo, hr, h, 0);

  return h;
}

1190
/** Complete this header field and parse next header field.
1191 1192
 *
 * This function completes parsing a multi-field header like @Accept,
1193
 * @Contact, @Via or @Warning. It scans for the next header field and
1194
 * if one is found, it calls the parsing function recursively.
1195
 *
1196
 * @param home 	 memory home used ot allocate
1197 1198
 *             	 new header structures and parameter lists
 * @param prev 	 pointer to header structure already parsed
1199
 * @param s    	 header content to parse; should point to the area after
1200 1201 1202 1203
 *             	 current header field (either end of line or to a comma
 *             	 separating header fields)
 * @param slen 	 ignored
 *
1204
 * @since New in @VERSION_1_12_4.
1205 1206 1207 1208
 *
 * @retval >= 0 when successful
 * @retval -1 upon an error
 */
1209
issize_t msg_parse_next_field(su_home_t *home, msg_header_t *prev,
1210 1211
			      char *s, isize_t slen)
{
1212
  msg_hclass_t *hc = prev->sh_class;
1213 1214 1215 1216 1217 1218
  msg_header_t *h;
  char *end = s + slen;

  if (*s && *s != ',')
    return -1;

1219 1220 1221
  if (msg_header_update_params(prev->sh_common, 0) < 0)
    return -1;

1222 1223 1224 1225 1226
  while (*s == ',') /* Skip comma and following whitespace */
    *s = '\0', s += span_lws(s + 1) + 1;

  if (*s == 0)
    return 0;
1227

1228
  h = msg_header_alloc(home, hc, 0);
1229 1230 1231 1232 1233 1234
  if (!h)
    return -1;

  prev->sh_succ = h, h->sh_prev = &prev->sh_succ;
  prev->sh_next = h;

1235
  return hc->hc_parse(home, h, s, end - s);
1236 1237
}

Pekka Pessi's avatar
Pekka Pessi committed
1238 1239 1240 1241 1242
/** Decode a message header. */
msg_header_t *msg_header_d(su_home_t *home, msg_t const *msg, char const *b)
{
  msg_mclass_t const *mc = msg->m_class;
  msg_href_t const *hr = mc->mc_unknown;
1243 1244
  isize_t n;			/* Length of header contents */
  isize_t name_len, xtra;
Pekka Pessi's avatar
Pekka Pessi committed
1245 1246 1247
  msg_header_t *h;
  char *bb;

1248
  n = strlen(b);
Pekka Pessi's avatar
Pekka Pessi committed
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
  hr = msg_find_hclass(mc, b, &name_len);
  if (hr == NULL)
    return NULL;

  /* Strip extra whitespace at the end and begin of header */
  while (n > name_len && IS_LWS(b[n - 1]))
    n--;
  if (name_len < n && IS_LWS(b[name_len]))
    name_len++;

  xtra = (n - name_len);
  if (!(h = msg_header_alloc(home, hr->hr_class, xtra + 1)))
    return NULL;

  bb = memcpy(MSG_HEADER_DATA(h), b + name_len, xtra), bb[xtra] = 0;

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  if (hr->hr_class->hc_parse(home, h, bb, xtra) >= 0)
    return h;

  hr = mc->mc_unknown;
  su_free(home, h);
  if (!(h = msg_header_alloc(home, hr->hr_class, n + 1)))
    return NULL;
  bb = memcpy(MSG_HEADER_DATA(h), b, n), bb[n] = 0;
  if (hr->hr_class->hc_parse(home, h, bb, n) < 0)
    su_free(home, h), h = NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1275 1276 1277 1278 1279

  return h;
}

/** Extract a separator line */
1280 1281
issize_t msg_extract_separator(msg_t *msg, msg_pub_t *mo,
			       char b[], isize_t bsiz, int eos)
Pekka Pessi's avatar
Pekka Pessi committed
1282 1283 1284 1285
{
  msg_mclass_t const *mc = msg->m_class;
  msg_href_t const *hr = mc->mc_separator;
  int l = CRLF_TEST(b);  /* Separator length */
1286
  msg_header_t *h;
Pekka Pessi's avatar
Pekka Pessi committed
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

  /* Even if a single CR *may* be a payload separator we cannot be sure */
  if (l == 0 || (!eos && bsiz == 1 && b[0] == '\r'))
    return 0;

  /* Separator */
  if (!(h = msg_header_alloc(msg_home(msg), hr->hr_class, 0)))
    return -1;
  if (hr->hr_class->hc_parse(msg_home(msg), h, b, l) < 0)
    return -1;

1298
  h->sh_data = b, h->sh_len = l;
Pekka Pessi's avatar
Pekka Pessi committed
1299

1300
  append_parsed(msg, mo, hr, h, 0);
Pekka Pessi's avatar
Pekka Pessi committed
1301 1302 1303 1304

  return l;
}

1305
su_inline msg_header_t **msg_chain_tail(msg_t const *msg);
Pekka Pessi's avatar
Pekka Pessi committed
1306 1307 1308

/** Extract a message body of @a body_len bytes.
  */
1309 1310 1311 1312 1313
issize_t msg_extract_payload(msg_t *msg, msg_pub_t *mo,
			     msg_header_t **return_payload,
			     usize_t body_len,
			     char b[], isize_t bsiz,
			     int eos)
Pekka Pessi's avatar
Pekka Pessi committed
1314
{
1315 1316
  msg_mclass_t const *mc;
  msg_href_t const *hr;
1317
  msg_header_t *h, *h0;
Pekka Pessi's avatar
Pekka Pessi committed
1318 1319 1320 1321 1322 1323 1324
  msg_payload_t *pl;
  char *x;

  if (msg == NULL || mo == NULL)
    return -1;

  assert(!msg->m_chunk);
1325 1326
  mc = msg->m_class;
  hr = mc->mc_payload;
Pekka Pessi's avatar
Pekka Pessi committed
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337

  if (return_payload == NULL)
    return_payload = &h0;
  *return_payload = NULL;

  assert(body_len > 0);

  /* Allocate header structure for payload */
  if (!(h = msg_header_alloc(msg_home(msg), hr->hr_class, 0)))
    return -1;

1338
  append_parsed(msg, mo, hr, h, 0);
1339
  pl = (msg_payload_t*)h;
Pekka Pessi's avatar
Pekka Pessi committed
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
  *return_payload = h;

  if (bsiz >= body_len) {
    /* We have a complete body. */
    h->sh_data = b, h->sh_len = body_len;
    pl->pl_data = b, pl->pl_len = body_len;
    return body_len;
  }

  if (msg->m_maxsize != 0 && body_len > msg->m_maxsize) {
    mo->msg_flags |= MSG_FLG_TOOLARGE;
    return -1;
  }

  assert(msg->m_buffer->mb_commit == bsiz);
  assert(b == msg->m_buffer->mb_data + msg->m_buffer->mb_used);

  if (msg->m_buffer->mb_used + body_len <= msg->m_buffer->mb_size) {
    /* We don't have a complete body, but we have big enough buffer for it. */
    msg->m_chunk = pl;

    h->sh_data = b, h->sh_len  = bsiz;
    pl->pl_data = b, pl->pl_len  = body_len;

    if (msg->m_buffer->mb_used + body_len < msg->m_buffer->mb_size)
      /* NUL-terminate payload */
      b[body_len++] = '\0';

    /* Mark the rest of the body as used in the buffer */
    /* msg_buf_commit(msg, body_len - bsiz, eos); */
    msg_buf_used(msg, body_len);

    return bsiz;
  }

  /* We don't have big enough buffer for body. */

  if (msg_get_flags(msg, MSG_FLG_CHUNKING)) {
    /* Application supports chunking, use multiple chunks for payload */
1379
    usize_t current, rest;
Pekka Pessi's avatar
Pekka Pessi committed
1380 1381 1382 1383 1384

    current = msg->m_buffer->mb_size - msg->m_buffer->mb_used;
    rest = body_len - current;

    /* Use all the data from our current buffer */
1385
    msg_buf_used(msg, current);
Pekka Pessi's avatar
Pekka Pessi committed
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417

    msg->m_chunk = pl;

    h->sh_data = b, h->sh_len = bsiz;
    pl->pl_data = b, pl->pl_len  = current;

    for (;current < body_len; current += rest) {
      msg_header_t *h0 = h;

      /* Allocate header structure for next payload chunk */
      if (!(h = msg_header_alloc(msg_home(msg), hr->hr_class, 0)))
	return -1;
      if (msg->m_chain)
	msg_insert_here_in_chain(msg, msg_chain_tail(msg), h);
      h0->sh_next = h;

      rest = body_len - current;

      if (!msg->m_streaming) {
	x = msg_buf_exact(msg, rest);
	if (x == NULL) {
	  mo->msg_flags |= MSG_FLG_TOOLARGE;
	  return -1;
	}
      }
      else {
	x = NULL;
      }

      if (x) {
	/* Mark the just-allocated buffer as used */
	rest = msg->m_buffer->mb_size - msg->m_buffer->mb_used;
1418
	msg_buf_used(msg, rest);
Pekka Pessi's avatar
Pekka Pessi committed
1419 1420 1421 1422 1423 1424 1425
      }

      pl = h->sh_payload;

      h->sh_len = 0, pl->pl_len = rest;
      h->sh_data = x, pl->pl_data = x;
    }
1426
  }
Pekka Pessi's avatar
Pekka Pessi committed
1427 1428 1429
  else {
    /* No chunking.
     *
1430
     * Allocate a single buffer that contains enough free space for body.
Pekka Pessi's avatar
Pekka Pessi committed
1431
     *
1432 1433
     * msg_buf_exact() also copies committed but un-used data
     * from the old buffer (b[0] .. b[bsiz])
Pekka Pessi's avatar
Pekka Pessi committed
1434 1435 1436 1437 1438 1439 1440 1441 1442
     * to the new buffer (x[-bsiz-1]..b[-1])
     */
    if (!(x = msg_buf_exact(msg, body_len - bsiz + 1))) {
      if (mo->msg_flags & MSG_FLG_TOOLARGE) {
	msg_mark_as_complete(msg, MSG_FLG_TRUNC);
	return bsiz;
      }
      return -1;
    }
1443

Pekka Pessi's avatar
Pekka Pessi committed
1444 1445
    /* Fake un-received data as already received and then use it */
    /* msg_buf_commit(msg, body_len - bsiz + 1, eos); */
1446
    msg_buf_used(msg, body_len + 1);
Pekka Pessi's avatar
Pekka Pessi committed
1447 1448 1449 1450 1451

    msg->m_chunk = h->sh_payload;

    x -= bsiz; /* Start of un-used data */
    x[body_len] = '\0';
1452

Pekka Pessi's avatar
Pekka Pessi committed
1453 1454
    h->sh_data = x, h->sh_len = bsiz;
    pl->pl_data = x, pl->pl_len = body_len;
1455

Pekka Pessi's avatar
Pekka Pessi committed
1456 1457
    assert(MSG_CHUNK_AVAIL(pl) == body_len - bsiz);
  }
1458

Pekka Pessi's avatar
Pekka Pessi committed
1459 1460 1461 1462 1463
  return bsiz;
}

/** Extract incomplete chunks.
 */
1464
su_inline
Pekka Pessi's avatar
Pekka Pessi committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
int extract_incomplete_chunks(msg_t *msg, int eos)
{
  msg_payload_t *chunk;

  for (chunk = msg->m_chunk; chunk; chunk = MSG_CHUNK_NEXT(chunk)) {
    if (MSG_CHUNK_AVAIL(chunk) != 0)
      break;

    /* The incomplete payload fragment is now complete */
    assert(MSG_CHUNK_BUFFER(chunk) == chunk->pl_data + chunk->pl_len);

    msg->m_size += chunk->pl_common->h_len;
  }

  msg->m_chunk = chunk;

  if (chunk) {
    if (eos) {
      msg_mark_as_complete(msg, MSG_FLG_TRUNC);
      return 1;
    }
1486 1487
  }
  else {
Pekka Pessi's avatar
Pekka Pessi committed
1488 1489 1490 1491 1492 1493
    if (msg_get_flags(msg, MSG_FLG_FRAGS))
      msg_mark_as_complete(msg, 0);
  }

  /**@retval 1 when message is complete
   * @retval 0 when message is incomplete
1494
   * @retval -1 upon an error
Pekka Pessi's avatar
Pekka Pessi committed
1495
   */
1496
  return chunk == NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1497 1498 1499
}

/* Extract trailers */
1500
su_inline issize_t
1501
extract_trailers(msg_t *msg, msg_pub_t *mo,
1502
		 char *b, isize_t bsiz, int eos, int copy)
Pekka Pessi's avatar
Pekka Pessi committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
{
  if (IS_CRLF(b[0])) {
    msg_mark_as_complete(msg, MSG_FLG_COMPLETE);
    return CRLF_TEST(b);
  }
  else
    return extract_header(msg, mo, b, bsiz, eos, copy);
}

/* ====================================================================== */
/* Preparing (printing/encoding) a message structure for sending */

/* Internal prototypes */
1516
su_inline size_t
1517 1518
msg_header_name_e(char b[], size_t bsiz, msg_header_t const *h, int flags);
static size_t msg_header_prepare(msg_mclass_t const *, int flags,
1519 1520
				 msg_header_t *h, msg_header_t **return_next,
				 char *b, size_t bsiz);
Pekka Pessi's avatar
Pekka Pessi committed
1521 1522 1523

/**Encode all message fragments.
 *
1524
 * @relatesalso msg_s
Pekka Pessi's avatar
Pekka Pessi committed
1525 1526
 *
 * The function msg_prepare() prepares a message for sending. It encodes all
1527 1528 1529 1530 1531 1532
 * serialized fragments in the message. You have to call msg_serialize()
 * before calling msg_headers_prepare() in order to make sure that all the
 * heades and other message fragments are included in the chain.
 *
 * After encoding, the msg_common_s::h_data field will point to the encoding
 * result of size msg_common_s::h_len bytes in in each fragment.
Pekka Pessi's avatar
Pekka Pessi committed
1533 1534 1535 1536
 *
 * When multiple header fields are represented as a comma-separated list
 * within a single header line, the first fragment in the header will
 * contain all the text belonging to the header. The rest of the header
1537 1538
 * fields will have zero-length encoding with msg_common_s::h_data that
 * points to the end of the line.
Pekka Pessi's avatar
Pekka Pessi committed
1539 1540
 *
 * @return Total size of the encoded message in bytes, or -1 upon an error.
1541 1542
 *
 * @sa msg_extract(), msg_serialize()
Pekka Pessi's avatar
Pekka Pessi committed
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
 */
int msg_prepare(msg_t *msg)
{
  int total;

  assert(msg->m_chain);
  assert(msg_chain_errors(msg->m_chain) == 0);

  /* Get rid of data that was received but not yet used (parsed) */
  msg_clear_committed(msg);

  total = msg_headers_prepare(msg, msg->m_chain, msg_object(msg)->msg_flags);

  if (total != -1) {
    msg->m_size = total;
    msg->m_prepared = 1;
  }

  return total;
}

/** Clear 'prepared' flag. */
void msg_unprepare(msg_t *msg)
{
  if (msg) msg->m_prepared = 0;
}

/** Return true if message is prepared. */
int msg_is_prepared(msg_t const *msg)
{
  return msg && msg->m_prepared;
}

/**Encode headers in chain.
 *
 * The function msg_headers_prepare() encodes all the headers in the header
 * chain. You have to call msg_serialize() before calling
 * msg_headers_prepare() in order to make sure that all the heades and other
 * message fragments are included in the chain.
 *
1583
 * @return
Pekka Pessi's avatar
Pekka Pessi committed
1584 1585
 * The size of all the headers in chain, or -1 upon an error.
 */
1586
issize_t msg_headers_prepare(msg_t *msg, msg_header_t *headers, int flags)
Pekka Pessi's avatar
Pekka Pessi committed
1587 1588
{
  msg_mclass_t const *mc = msg->m_class;
1589
  msg_header_t *h, *next;
1590 1591
  ssize_t n = 0;
  size_t bsiz = 0, used = 0;
Pekka Pessi's avatar
Pekka Pessi committed
1592
  char *b;
1593
  size_t total = 0;
Pekka Pessi's avatar
Pekka Pessi committed
1594 1595 1596 1597 1598 1599 1600 1601

  b = msg_buf_alloc(msg, msg_min_size);
  bsiz = msg_buf_size(msg);

  if (!b)
    return -1;

  for (h = headers; h;) {
1602

Pekka Pessi's avatar
Pekka Pessi committed
1603 1604 1605 1606 1607 1608
    if (h->sh_data) {
      total += h->sh_len;
      h = h->sh_succ;
      continue;
    }

1609 1610 1611 1612 1613
    for (next = h->sh_succ; next; next = next->sh_succ)
      if (next->sh_class != h->sh_class || next->sh_data)
	break;

    n = msg_header_prepare(mc, flags, h, &next, b, bsiz - used);
Pekka Pessi's avatar
Pekka Pessi committed
1614

1615
    if (n == (ssize_t)-1) {
Pekka Pessi's avatar
Pekka Pessi committed
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
      errno = EINVAL;
      return -1;
    }

    if (used + n >= bsiz) {
      /* Allocate next buffer */
      if ((b = msg_buf_alloc(msg, n + 1)) == NULL)
	return -1;
      bsiz = msg_buf_size(msg); used = 0;
      continue;
    }

1628 1629 1630 1631 1632
    h->sh_data = b, h->sh_len = n;

    for (h = h->sh_succ; h != next; h = h->sh_succ)
      h->sh_data = b + n, h->sh_len = 0;

Pekka Pessi's avatar
Pekka Pessi committed
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    msg_buf_used(msg, n);

    total += n;
    used += n;
    b += n;
  }

  return total;
}

/** Encode a header or a list of headers */
static
1645
size_t msg_header_prepare(msg_mclass_t const *mc, int flags,
1646 1647
			  msg_header_t *h, msg_header_t **return_next,
			  char *b, size_t bsiz)
Pekka Pessi's avatar
Pekka Pessi committed
1648 1649 1650 1651
{
  msg_header_t *h0, *next;
  msg_hclass_t *hc;
  char const *s;
1652
  size_t n; ssize_t m;
1653
  int compact, one_line_list, comma_list;
Pekka Pessi's avatar
Pekka Pessi committed
1654 1655 1656 1657 1658

  assert(h); assert(h->sh_class);

  hc = h->sh_class;
  compact = MSG_IS_COMPACT(flags);
1659 1660
  one_line_list = hc->hc_kind == msg_kind_apndlist;
  comma_list = compact || one_line_list || MSG_IS_COMMA_LISTS(flags);
Pekka Pessi's avatar
Pekka Pessi committed
1661

1662
  for (h0 = h, n = 0; ; h = next) {
Pekka Pessi's avatar
Pekka Pessi committed
1663 1664
    next = h->sh_succ;

1665
    if (h == h0 && hc->hc_name && hc->hc_name[0])
Pekka Pessi's avatar
Pekka Pessi committed
1666 1667
      n += msg_header_name_e(b + n, bsiz >= n ? bsiz - n : 0, h, flags);

1668
    if ((m = hc->hc_print(b + n, bsiz >= n ? bsiz - n : 0, h, flags)) == -1) {
1669 1670 1671 1672 1673
      if (bsiz >= n + 64)
	m = 2 * (bsiz - n);
      else
	m = 128;
    }
Pekka Pessi's avatar
Pekka Pessi committed
1674 1675 1676 1677

    n += m;

    if (hc->hc_name) {
1678 1679 1680
      if (!comma_list || !next || next == *return_next)
	s = CRLF, m = 2;
      /* Else encode continuation */
Pekka Pessi's avatar
Pekka Pessi committed
1681
      else if (compact)
1682
	s = ",", m = 1;
Pekka Pessi's avatar
Pekka Pessi committed
1683
      else if (one_line_list)
1684
	s = ", ", m = 2;
Pekka Pessi's avatar
Pekka Pessi committed
1685
      else
1686
	s = "," CRLF "\t", m = 4;
Pekka Pessi's avatar
Pekka Pessi committed
1687

1688 1689
      if (bsiz > n + m)
	memcpy(b + n, s, m);
Pekka Pessi's avatar
Pekka Pessi committed
1690 1691 1692
      n += m;
    }

1693 1694
    if (!comma_list || !next || next == *return_next)
      break;
Pekka Pessi's avatar
Pekka Pessi committed
1695 1696
  }

1697
  *return_next = next;
Pekka Pessi's avatar
Pekka Pessi committed
1698 1699 1700 1701

  return n;
}

1702 1703
/** Encode a header.
 *
Pekka Pessi's avatar
Pekka Pessi committed
1704 1705 1706 1707 1708
 * The function msg_header_e() encodes a header field in the buffer @a
 * b[]. The encoding includes its name and trailing CRLF.  The function
 * returns the length of the encoding in bytes, excluding the final @c NUL.
 * The buffer @a b must be large enough for whole encoding, including the
 * final @c NUL.
1709
 *
Pekka Pessi's avatar
Pekka Pessi committed
1710 1711 1712 1713
 * The @a flags parameter define how the encoding is done.  If the flags
 * specify @c MSG_DO_COMPACT, the encoding is compact (short form with
 * minimal whitespace).
 */
1714
issize_t msg_header_e(char b[], isize_t bsiz, msg_header_t const *h, int flags)
Pekka Pessi's avatar
Pekka Pessi committed
1715
{
1716
  size_t n, m;
Pekka Pessi's avatar
Pekka Pessi committed
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730

  assert(h); assert(h->sh_class);

  if (h == NULL || h->sh_class == NULL)
    return -1;

  n = msg_header_name_e(b, bsiz, h, flags);
  m = h->sh_class->hc_print(b + n, bsiz > n ? bsiz - n : 0, h, flags);
  if (h->sh_class->hc_name) {
    /* Ordinary header */
    if (bsiz > n + m + strlen(CRLF))
      strcpy(b + n + m, CRLF);
    return n + m + strlen(CRLF);
  }
1731
  else
Pekka Pessi's avatar
Pekka Pessi committed
1732 1733 1734 1735
    return m;
}

/** Encode header name */
1736
su_inline
1737 1738
size_t
msg_header_name_e(char b[], size_t bsiz, msg_header_t const *h, int flags)
Pekka Pessi's avatar
Pekka Pessi committed
1739 1740 1741
{
  int compact = MSG_IS_COMPACT(flags);
  char const *name;
1742
  size_t n, n2;