msg_parser.c 66.1 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 79 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
				     msg_header_t **prev,
				     msg_header_t *h);
static inline msg_header_t *msg_chain_remove(msg_t *msg, msg_header_t *h);

#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;
}

Pekka Pessi's avatar
Pekka Pessi committed
120 121
/* ---------------------------------------------------------------------- */

Pekka Pessi's avatar
Pekka Pessi committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
/** Test if header is not in the chain */
#define msg_header_is_removed(h) ((h)->sh_prev == NULL)

static inline int msg_is_request(msg_header_t const *h)
{
  return h->sh_class->hc_hash == msg_request_hash;
}

static inline int msg_is_status(msg_header_t const *h)
{
  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. */
void *msg_buf_alloc(msg_t *msg, unsigned size)
{
  struct msg_mbuffer_s *mb = msg->m_buffer;
  unsigned room = mb->mb_size - mb->mb_commit - mb->mb_used;
  int target_size;

  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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    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. */
void *msg_buf_exact(msg_t *msg, unsigned size)
{
  struct msg_mbuffer_s *mb = msg->m_buffer;
  unsigned room = mb->mb_size - mb->mb_commit - mb->mb_used;
  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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    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. */
unsigned msg_buf_commit(msg_t *msg, unsigned size, int eos)
{
  if (msg) {
    assert(msg->m_buffer->mb_used + msg->m_buffer->mb_commit + size <=
	   msg->m_buffer->mb_size);
    msg->m_buffer->mb_commit += size;
    msg->m_buffer->mb_eos = eos;
  }
  return 0;
}

/** Get length of committed data */
unsigned msg_buf_committed(msg_t const *msg)
{
  if (msg)
    return msg->m_buffer->mb_commit;
  else
    return 0;
}

/** Get committed data */
void *msg_buf_committed_data(msg_t const *msg)
{
219 220
  return msg && msg->m_buffer->mb_data ?
    msg->m_buffer->mb_data + msg->m_buffer->mb_used
Pekka Pessi's avatar
Pekka Pessi committed
221 222 223 224 225 226 227
    : NULL;
}

unsigned msg_buf_size(msg_t const *msg)
{
  assert(msg);
  if (msg) {
228
    struct msg_mbuffer_s const *mb = msg->m_buffer;
Pekka Pessi's avatar
Pekka Pessi committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    return mb->mb_size - mb->mb_commit - mb->mb_used;
  }
  else
    return 0;
}

static inline
void msg_buf_used(msg_t *msg, unsigned used)
{
  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. */
void msg_buf_set(msg_t *msg, void *b, unsigned size)
{
  if (msg) {
    struct msg_mbuffer_s *mb = msg->m_buffer;
251

Pekka Pessi's avatar
Pekka Pessi committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    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;
270 271

  if (!dst || !src)
Pekka Pessi's avatar
Pekka Pessi committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    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;
}

/** Obtain iovec for receiving the data.
 *
 * @relates msg_s
 *
 * The function msg_recv_iovec() allocates buffers for receiving @a n bytes
 * of data available from network. It returns the buffers in the I/O vector
 * @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).
 *
 * Currently, the msg_recv_iovec() allocates buffers in at most two blocks,
 * so the caller should allocate at least two elements for the I/O vector @a
 * vec.
 *
 * @param msg     message object [IN]
 * @param vec     I/O vector [OUT]
 * @param veclen  available length of @a vec [IN]
 * @param n       number of available bytes[IN]
 * @param exact   true if data ends at message boundary [IN]
 *
 * @return
 * The function msg_recv_iovec() returns the length of I/O vector to
 * receive data, 0 if there are not enough buffers, or -1 upon an error.
 */
316
int msg_recv_iovec(msg_t *msg, msg_iovec_t vec[], int veclen,
Pekka Pessi's avatar
Pekka Pessi committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
		   unsigned n, int exact)
{
  int i = 0;
  msg_payload_t *chunk;
  unsigned len = 0;
  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;
338

Pekka Pessi's avatar
Pekka Pessi committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 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 395 396 397 398 399 400 401 402 403 404 405 406 407
    if (len > n)
      len = n;
    if (vec)
      vec[i].mv_base = buf, vec[i].mv_len = len;
    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)
    vec[i].mv_base = buf, vec[i].mv_len = n;

  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;
    } else if (len > MSG_CHUNK_AVAIL(chunk)) {
      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;
408

Pekka Pessi's avatar
Pekka Pessi committed
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
    /* 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
}

Pekka Pessi's avatar
Pekka Pessi committed
436

Pekka Pessi's avatar
Pekka Pessi committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
/** Obtain a buffer for receiving data */
int msg_recv_buffer(msg_t *msg, void **return_buffer)
{
  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) {
      unsigned n = MSG_CHUNK_AVAIL(pl);
      if (n) {
	*return_buffer = MSG_CHUNK_BUFFER(pl);
	return n;
      }
    }

    return 0;
460
  }
Pekka Pessi's avatar
Pekka Pessi committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

  if (msg_get_flags(msg, MSG_FLG_FRAGS)) {
    /* Message is complete */
    return 0;
  } else if ((*return_buffer = msg_buf_alloc(msg, 2))) {
    return msg_buf_size(msg) - 1;
  } else
    return -1;
}



/**Commit @a n bytes of buffers.
 *
 * @relates msg_s
 *
 * 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
483
 * @param eos true if stream is complete
Pekka Pessi's avatar
Pekka Pessi committed
484 485 486
 *
 * @note The @a eos should be always true for message-based transports. It
 * should also be true when a TCP FIN is received, for instance.
487
 *
Pekka Pessi's avatar
Pekka Pessi committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
 * @retval The function msg_recv_commit() returns 0 when successful, -1 upon
 * an error.
 */
int msg_recv_commit(msg_t *msg, unsigned n, int eos)
{
  msg_payload_t *pl;

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

  for (pl = msg->m_chunk; pl; pl = pl->pl_next) {
    unsigned len = MSG_CHUNK_AVAIL(pl);

    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);
}

518
/**Get a next message of the stream.
Pekka Pessi's avatar
Pekka Pessi committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
 *
 * @relates msg_s
 *
 * 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;
  unsigned n;

  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;
}

/** Set next message of the stream */
int msg_set_next(msg_t *msg, msg_t *next)
{
  if (!msg || (next && next->m_next))
    return -1;

557
  if (msg->m_next && next)
Pekka Pessi's avatar
Pekka Pessi committed
558 559 560
    next->m_next = msg->m_next;

  msg->m_next = next;
561

Pekka Pessi's avatar
Pekka Pessi committed
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
  return 0;
}

/** Clear committed data */
void msg_clear_committed(msg_t *msg)
{
  if (msg) {
    unsigned n = msg_buf_committed(msg);

    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.
 *
 * @relates msg_s
 */
inline
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;
  } else {
    return 0;
  }
}

/** Return true if message is complete.
 *
 * @relates msg_s
 */
int msg_is_complete(msg_t const *msg)
{
  return msg && MSG_IS_COMPLETE(msg->m_object);
}

627
/** Return true if message has parsing errors.
Pekka Pessi's avatar
Pekka Pessi committed
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
 *
 * @relates msg_s
*/
int msg_has_error(msg_t const *msg)
{
  return msg->m_object->msg_flags & MSG_FLG_ERROR;
}

/**Total size of message.
 *
 * @relates msg_s
 */
unsigned msg_size(msg_t const *msg)
{
  return msg ? msg->m_size : 0;
}

/** Set the maximum size of a message.
 *
 * @relates msg_s
 *
 * 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.
 */
unsigned msg_maxsize(msg_t *msg, unsigned maxsize)
{
  unsigned retval = 0;

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

  return retval;
}

/**Set the size of next fragment.
 *
 * @relates msg_s
 *
 * The function msg_streaming_size() sets the size of the message body for
674
 * streaming.
Pekka Pessi's avatar
Pekka Pessi committed
675 676 677 678 679
 */
unsigned msg_streaming_size(msg_t *msg, unsigned ssize)
{
  if (!msg)
    return -1;
680

Pekka Pessi's avatar
Pekka Pessi committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
  msg->m_ssize = ssize;

  return 0;
}

/**Allocate a list of external buffers.
 *
 * @relates msg_s
 *
 * 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.
 */
696 697
int msg_buf_external(msg_t *msg,
		     unsigned N,
Pekka Pessi's avatar
Pekka Pessi committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
		     unsigned blocksize)
{
  msg_buffer_t *ext, *b, **bb;
  int i, I;

  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);
717

Pekka Pessi's avatar
Pekka Pessi committed
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
  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;
743
	}
Pekka Pessi's avatar
Pekka Pessi committed
744 745
	msg->m_ssize -= b->b_size;
      }
746

Pekka Pessi's avatar
Pekka Pessi committed
747 748 749 750 751 752 753 754 755 756
    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;
757

Pekka Pessi's avatar
Pekka Pessi committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
}

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 */

static inline int extract_incomplete_chunks(msg_t *, int eos);
static int extract_first(msg_t *, msg_pub_t *, char b[], int bsiz, int eos);
static inline int extract_next(msg_t *, msg_pub_t *, char *, int, int, int);
777
static int extract_header(msg_t *, msg_pub_t*,
Pekka Pessi's avatar
Pekka Pessi committed
778
			  char b[], int bsiz, int eos, int copy);
779
static msg_header_t *header_parse(msg_t *, msg_pub_t *, msg_href_t const *,
Pekka Pessi's avatar
Pekka Pessi committed
780
				  char s[], int slen, int copy_buffer);
781
static inline int
Pekka Pessi's avatar
Pekka Pessi committed
782 783 784 785 786 787
extract_trailers(msg_t *msg, msg_pub_t *mo,
		 char *b, int bsiz, int eos, int copy);

/** Calculate length of line ending (0, 1 or 2) */
#define CRLF_TEST(b) ((b)[0] == '\r' ? ((b)[1] == '\n') + 1 : (b)[0] =='\n')

788
static inline void
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 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
append_parsed(msg_t *msg, msg_pub_t *mo, msg_header_t **hh, msg_header_t *h,
	      int always_into_chain);

/**Extract and parse a message from internal buffer.
 *
 * @relates msg_s
 *
 * 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;
  int m, bsiz, eos;

  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) {
    m = extract_incomplete_chunks(msg, eos);
    if (m < 1 || MSG_IS_COMPLETE(mo))
      return m;
  }

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

830
  if (msg->m_buffer->mb_used + msg->m_buffer->mb_commit ==
Pekka Pessi's avatar
Pekka Pessi committed
831 832 833 834
      msg->m_buffer->mb_size)
    /* Why? When? */
    return 0;

835
  assert(msg->m_buffer->mb_used + msg->m_buffer->mb_commit <
Pekka Pessi's avatar
Pekka Pessi committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
	 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);
857
    else
Pekka Pessi's avatar
Pekka Pessi committed
858 859 860 861 862 863 864 865 866 867 868 869 870
      m = extract_first(msg, mo, b, bsiz, eos);

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

    b += m;
    bsiz -= m;

    msg_buf_used(msg, m);
  }

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

Pekka Pessi's avatar
Pekka Pessi committed
872 873 874 875 876 877 878 879 880 881 882 883 884 885
  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;
}

886
static
Pekka Pessi's avatar
Pekka Pessi committed
887 888 889 890 891
int extract_first(msg_t *msg, msg_pub_t *mo, char b[], int bsiz, int eos)
{
  /* First line */
  int k, l, m, n, crlf, xtra;
  msg_header_t *h, **hh;
892
  msg_href_t const *hr;
Pekka Pessi's avatar
Pekka Pessi committed
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  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);
910

Pekka Pessi's avatar
Pekka Pessi committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
  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;
  }

931
  b[n] = 0;
Pekka Pessi's avatar
Pekka Pessi committed
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947

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

  assert(hr->hr_offset);

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

  append_parsed(msg, mo, hh, h, 1);

  mo->msg_flags |= MSG_FLG_HEADERS;

  return m;
}

/* Extract header or message body */
948
static inline int
Pekka Pessi's avatar
Pekka Pessi committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
extract_next(msg_t *msg, msg_pub_t *mo, char *b, int bsiz, int eos, int copy)
{
  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. */
int msg_extract_header(msg_t *msg, msg_pub_t *mo, char b[], int bsiz, int eos)
{
  return extract_header(msg, mo, b, bsiz, eos, 0);
}

/** Extract a header from buffer @a b.
 */
965 966
static
int
Pekka Pessi's avatar
Pekka Pessi committed
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
extract_header(msg_t *msg, msg_pub_t *mo, char *b, int bsiz, int eos,
	       int copy_buffer)
{
  int len, n = 0, m, crlf = 0;
  int name_len = 0, name_len_set = 0;
  int error = 0, xtra;
  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;
    h = header_parse(msg, mo, hr, NULL, 0, 0);
  }
  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;
}

1045 1046 1047 1048
static
msg_header_t *header_parse(msg_t *msg, msg_pub_t *mo,
			   msg_href_t const *hr,
			   char s[], int slen,
Pekka Pessi's avatar
Pekka Pessi committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
			   int copy_buffer)
{
  su_home_t *home = msg_home(msg);
  msg_header_t *h, **hh;
  msg_header_t *h0, *h_next;
  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);
1066 1067

  if (!h)
Pekka Pessi's avatar
Pekka Pessi committed
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 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    return NULL;

  if (s) {
    if (copy_buffer)
      s = memcpy(MSG_HEADER_DATA(h), s, slen);

    s[slen] = '\0';

    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) {
	/* Try to free memory allocated by hc->hc_parse() */
	for (h0 = h; h0; h0 = h_next) {
	  h_next = h0->sh_next;
	  if (hc->hc_params) {
	    msg_param_t *params = *(msg_param_t **)
	      ((char *)h0 + hc->hc_params);
	    if (params)
	      su_free(home, params);
	  }
	  if (h0 != h)
	    su_free(home, h0);
	}

	memset(h, 0, hc->hc_size);
	h->sh_error->er_name = hc->hc_name;
1110
	hr = msg->m_class->mc_error;
Pekka Pessi's avatar
Pekka Pessi committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
	h->sh_class = hr->hr_class;
	hh = (msg_header_t **)((char *)mo + hr->hr_offset);
      }
    }
  }

  if (clear)
    for (hh = &(*hh)->sh_next; *hh; *hh = (*hh)->sh_next)
      msg_chain_remove(msg, *hh);
  else if (h != *hh)
    append_parsed(msg, mo, hh, h, 0);

  return h;
}

/** 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;
  int n;			/* Length of header contents */
1132
  int name_len, xtra;
Pekka Pessi's avatar
Pekka Pessi committed
1133 1134 1135
  msg_header_t *h;
  char *bb;

1136
  n = strlen(b);
Pekka Pessi's avatar
Pekka Pessi committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
  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;

  if (hr->hr_class->hc_parse(home, h, bb, xtra) < 0) {
    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;
    }
  }

  return h;
}

/** Extract a separator line */
1168
int msg_extract_separator(msg_t *msg, msg_pub_t *mo,
Pekka Pessi's avatar
Pekka Pessi committed
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
			  char b[], int bsiz, int eos)
{
  msg_mclass_t const *mc = msg->m_class;
  msg_href_t const *hr = mc->mc_separator;
  int l = CRLF_TEST(b);  /* Separator length */
  msg_header_t *h, **hh;

  /* 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;

  h->sh_data = b, h->sh_len  = l;

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

  append_parsed(msg, mo, hh, h, 0);

  return l;
}

Pekka Pessi's avatar
Pekka Pessi committed
1195
static inline msg_header_t **msg_chain_tail(msg_t const *msg);
Pekka Pessi's avatar
Pekka Pessi committed
1196 1197 1198

/** Extract a message body of @a body_len bytes.
  */
1199
int msg_extract_payload(msg_t *msg, msg_pub_t *mo,
Pekka Pessi's avatar
Pekka Pessi committed
1200 1201
			msg_header_t **return_payload,
			unsigned body_len,
1202
			char b[], int bsiz,
Pekka Pessi's avatar
Pekka Pessi committed
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
			int eos)
{
  msg_mclass_t const *mc = msg->m_class;
  msg_href_t const *hr = mc->mc_payload;
  msg_header_t *h, **hh, *h0;
  msg_payload_t *pl;
  char *x;

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

  assert(!msg->m_chunk);

  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;

  hh = (msg_header_t **)((char *)mo + hr->hr_offset);
  append_parsed(msg, mo, hh, h, 0);
  pl = h->sh_payload;
  *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 */
    unsigned current, rest;

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

    /* Use all the data from our current buffer */
1274
    msg_buf_used(msg, current);
Pekka Pessi's avatar
Pekka Pessi committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

    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;
1307
	msg_buf_used(msg, rest);
Pekka Pessi's avatar
Pekka Pessi committed
1308 1309 1310 1311 1312 1313 1314
      }

      pl = h->sh_payload;

      h->sh_len = 0, pl->pl_len = rest;
      h->sh_data = x, pl->pl_data = x;
    }
1315
  }
Pekka Pessi's avatar
Pekka Pessi committed
1316 1317 1318
  else {
    /* No chunking.
     *
1319
     * Allocate a single buffer that contains enough free space for body.
Pekka Pessi's avatar
Pekka Pessi committed
1320
     *
1321 1322
     * 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
1323 1324 1325 1326 1327 1328 1329 1330 1331
     * 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;
    }
1332

Pekka Pessi's avatar
Pekka Pessi committed
1333 1334
    /* Fake un-received data as already received and then use it */
    /* msg_buf_commit(msg, body_len - bsiz + 1, eos); */
1335
    msg_buf_used(msg, body_len + 1);
Pekka Pessi's avatar
Pekka Pessi committed
1336 1337 1338 1339 1340

    msg->m_chunk = h->sh_payload;

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

Pekka Pessi's avatar
Pekka Pessi committed
1342 1343
    h->sh_data = x, h->sh_len = bsiz;
    pl->pl_data = x, pl->pl_len = body_len;
1344

Pekka Pessi's avatar
Pekka Pessi committed
1345 1346
    assert(MSG_CHUNK_AVAIL(pl) == body_len - bsiz);
  }
1347

Pekka Pessi's avatar
Pekka Pessi committed
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 1379 1380 1381
  return bsiz;
}

/** Extract incomplete chunks.
 */
static inline
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;
    }
  } else {
    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
1382
   * @retval -1 upon an error
Pekka Pessi's avatar
Pekka Pessi committed
1383
   */
1384
  return chunk == NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1385 1386 1387
}

/* Extract trailers */
1388 1389
static inline int
extract_trailers(msg_t *msg, msg_pub_t *mo,
Pekka Pessi's avatar
Pekka Pessi committed
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		 char *b, int bsiz, int eos, int copy)
{
  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 */
1404
static inline int
Pekka Pessi's avatar
Pekka Pessi committed
1405
msg_header_name_e(char b[], int bsiz, msg_header_t const *h, int flags);
1406
static int msg_header_prepare(msg_mclass_t const *, int flags,
Pekka Pessi's avatar
Pekka Pessi committed
1407 1408 1409 1410 1411 1412 1413
			      msg_header_t *h, char *b, int bsiz);

/**Encode all message fragments.
 *
 * @relates msg_s
 *
 * The function msg_prepare() prepares a message for sending. It encodes all
1414 1415 1416 1417 1418 1419
 * 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
1420 1421 1422 1423
 *
 * 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
1424 1425
 * 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
1426 1427
 *
 * @return Total size of the encoded message in bytes, or -1 upon an error.
1428 1429
 *
 * @sa msg_extract(), msg_serialize()
Pekka Pessi's avatar
Pekka Pessi committed
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
 */
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.
 *
1470
 * @return
Pekka Pessi's avatar
Pekka Pessi committed
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
 * The size of all the headers in chain, or -1 upon an error.
 */
int msg_headers_prepare(msg_t *msg, msg_header_t *headers, int flags)
{
  msg_mclass_t const *mc = msg->m_class;
  msg_header_t *h;
  int n = 0, bsiz = 0, used = 0;
  char *b;
  unsigned total = 0;

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

  if (!b)
    return -1;

  for (h = headers; h;) {
    if (h->sh_data) {
      total += h->sh_len;
      h = h->sh_succ;
      continue;
    }

    n = msg_header_prepare(mc, flags, h, b, bsiz - used);

    if (n < 0) {
      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;
    }

    msg_buf_used(msg, n);

    total += n;
    used += n;
    b += n;
    h = h->sh_succ;
  }

  return total;
}

/** Encode a header or a list of headers */
static
1522
int msg_header_prepare(msg_mclass_t const *mc, int flags,
Pekka Pessi's avatar
Pekka Pessi committed
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
		       msg_header_t *h, char *b, int bsiz)
{
  msg_header_t *h0, *next;
  msg_hclass_t *hc;
  char const *s;
  int n, m, middle = 0;
  int compact, one_line_list, comma_list;

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

  hc = h->sh_class;
  compact = MSG_IS_COMPACT(flags);
  one_line_list = compact || hc->hc_kind == msg_kind_apndlist;
  comma_list = one_line_list || MSG_IS_COMMA_LISTS(flags);

  for (h0 = h, n = 0; h; h = next) {
    next = h->sh_succ;

    if (!next || next->sh_class != hc || next->sh_data || !comma_list)
      next = NULL;

    if (!middle && hc->hc_name && hc->hc_name[0])
      n += msg_header_name_e(b + n, bsiz >= n ? bsiz - n : 0, h, flags);

1547 1548 1549 1550 1551 1552
    if ((m = hc->hc_print(b + n, bsiz >= n ? bsiz - n : 0, h, flags)) < 0) {
      if (bsiz >= n + 64)
	m = 2 * (bsiz - n);
      else
	m = 128;
    }
Pekka Pessi's avatar
Pekka Pessi committed
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 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594

    n += m;

    if (hc->hc_name) {
      /* Encode continuation */
      if (!next)
	s = CRLF;
      else if (compact)
	s = ",";
      else if (one_line_list)
	s = ", ";
      else
	s = "," CRLF "\t";

      m = strlen(s);
      if (bsiz <= n + m) {
	if (!next)
	  return n + m;
      } else {
	strcpy(b + n, s);
      }
      n += m;
    }

    middle = 1;
  }

  if (bsiz > n) {		/* XXX */
    h0->sh_data = b, h0->sh_len = n;

    for (h = h0; h; h = next) {
      next = h->sh_succ;
      if (!next || next->sh_class != hc || next->sh_data || !comma_list)
	break;
      else
	next->sh_data = b, next->sh_len = 0;
    }
  }

  return n;
}

1595 1596
/** Encode a header.
 *
Pekka Pessi's avatar
Pekka Pessi committed
1597 1598 1599 1600 1601
 * 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.
1602
 *
Pekka Pessi's avatar
Pekka Pessi committed
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
 * 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).
 */
int msg_header_e(char b[], int bsiz, msg_header_t const *h, int flags)
{
  int n, m;

  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);
  }
1624
  else
Pekka Pessi's avatar
Pekka Pessi committed
1625 1626 1627 1628 1629
    return m;
}

/** Encode header name */
static inline
1630
int
Pekka Pessi's avatar
Pekka Pessi committed
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
msg_header_name_e(char b[], int bsiz, msg_header_t const *h, int flags)
{
  int compact = MSG_IS_COMPACT(flags);
  char const *name;
  int n, n2;

  if (compact && h->sh_class->hc_short[0])
    name = h->sh_class->hc_short, n = 1;
  else
    name = h->sh_class->hc_name, n = h->sh_class->hc_len;

  if (!name || !name[0])
    return 0;

  n2 = compact ? n + 1 : n + 2;

  if (n2 < bsiz) {
    memcpy(b, name, n);
    b[n++] = ':';
    if (!compact)
      b[n++] = ' ';
    b[n++] = '\0';
  }

  return n2;
}

/* ====================================================================== */
/* Handling header chain */

static inline void serialize_first(msg_t *msg, msg_header_t *h);
1662
static msg_header_t **serialize_one(msg_t *msg, msg_header_t *h,
Pekka Pessi's avatar
Pekka Pessi committed
1663 1664 1665
				    msg_header_t **prev);

/** Return head of the fragment chain */
Pekka Pessi's avatar
Pekka Pessi committed
1666
msg_header_t **msg_chain_head(msg_t const *msg)
Pekka Pessi's avatar
Pekka Pessi committed
1667
{
Pekka Pessi's avatar
Pekka Pessi committed
1668
  return msg ? (msg_header_t **)&msg->m_chain : NULL;
Pekka Pessi's avatar
Pekka Pessi committed
1669 1670
}

Pekka Pessi's avatar
Pekka Pessi committed
1671
static inline msg_header_t **_msg_chain_head(msg_t const *msg)
Pekka Pessi's avatar
Pekka Pessi committed
1672
{
Pekka Pessi's avatar