header.c 24.3 KB
1 2 3 4 5 6 7 8 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 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 120 121 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 148 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 177 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 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 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 518 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 557 558 559 560 561 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 627 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 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 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 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 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 785 786 787 788 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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 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 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 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 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 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 1168 1169 1170 1171 1172 1173 1174 1175 1176
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001, 2004, 2005, 2007, 2008, 2009, 2010
   Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 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 Street, Fifth Floor,
   Boston, MA 02110-1301 USA */

/*  This all header business needs a good rewrite.
 *          -- Alain Magloire, 2000-07-03 (rev. 1.21)
 *
 *  It's the job that's never started as takes longest to finish.
 *          -- Hamfast Gamgee, some time in the Third Age
 *
 *  It took almost 7 years to gather the courage to start the job,
 *  and only one day to finish it.
 *          -- Sergey Poznyakoff, 2007-06-24
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

#ifdef HAVE_STRINGS_H
# include <strings.h>
#endif

#include <mailutils/stream.h>
#include <mailutils/address.h>
#include <mailutils/mutil.h>
#include <mailutils/errno.h>
#include <mailutils/cstr.h>
#include <mailutils/sys/header_stream.h>
#include <mailutils/sys/header.h>

#define HEADER_MODIFIED   0x01
#define HEADER_INVALIDATE 0x02

#define HEADER_SET_MODIFIED(h) \
  ((h)->flags |= (HEADER_MODIFIED|HEADER_INVALIDATE))


/* mu_hdrent manipulation */

#define MU_HDRENT_NAME(hp,ep) ((hp)->spool + (ep)->fn)
#define MU_HDRENT_VALUE(hp,ep) ((hp)->spool + (ep)->fv)
#define MU_STR_SIZE(nlen,vlen) ((nlen) + 2 + (vlen) + 1)

static struct mu_hdrent *
mu_hdrent_nth (struct _mu_header *hdr, int n)
{
  struct mu_hdrent *p;
  for (p = hdr->head; p; p = p->next)
    if (n-- == 1)
      break;
  return p;
}

static struct mu_hdrent *
mu_hdrent_find (struct _mu_header *hdr, const char *name, int pos)
{
  struct mu_hdrent *p;

  if (pos > 0)
    {
      for (p = hdr->head; p; p = p->next)
	if (mu_c_strcasecmp (MU_HDRENT_NAME (hdr,p), name) == 0 && pos-- == 1)
	  break;
    }
  else if (pos < 0)
    {
      for (p = hdr->tail; p; p = p->prev)
	if (mu_c_strcasecmp (MU_HDRENT_NAME (hdr,p), name) == 0 && ++pos == 0)
	  break;
    }
  else
    p = NULL;
  return p;
}

static int
mu_hdrent_find_stream_pos (struct _mu_header *hdr, mu_off_t pos,
			   struct mu_hdrent **pent, size_t *poff)
{
  mu_off_t x;
  struct mu_hdrent *p;

  for (p = hdr->head, x = 0; p; p = p->next)
    {
      size_t strsize = MU_STR_SIZE (p->nlen, p->vlen);
      if (x <= pos && pos < x + strsize)
	{
	  *poff = pos - x;
	  *pent = p;
	  return 0;
	}
      x += strsize;
    }
  if (x == pos && hdr->tail)
    {
      /* To supply the trailing '\n' */
      p = hdr->tail;
      *pent = p;
      *poff = MU_STR_SIZE (p->nlen, p->vlen) - 1;
      return 0;
    }
  return 1;
}
     
static void
mu_hdrent_count (struct _mu_header *hdr, size_t *pcount, size_t *psize,
		 size_t *plines)
{
  if (hdr->flags & HEADER_INVALIDATE)
    {
      size_t size = 0;
      size_t count = 0;
      size_t lines = 0;
      struct mu_hdrent *p;
      for (p = hdr->head; p; p = p->next)
	{
	  count++;
	  size += MU_STR_SIZE (p->nlen, p->vlen);
	  lines += p->nlines;
	}

      hdr->numhdr = count;
      hdr->numlines = lines;
      hdr->size = size;
      hdr->flags &= ~HEADER_INVALIDATE;
    }
      
  *pcount = hdr->numhdr;
  *psize = hdr->size;
  *plines = hdr->numlines;
}

static void
mu_hdrent_remove (struct _mu_header *hdr, struct mu_hdrent *ent)
{
  struct mu_hdrent *p = ent->prev;
  if (p)
    p->next = ent->next;
  else
    hdr->head = ent->next;

  p = ent->next;
  if (p)
    p->prev = ent->prev;
  else
    hdr->tail = ent->prev;
}

static void
mu_hdrent_prepend (struct _mu_header *hdr, struct mu_hdrent *ent)
{
  struct mu_hdrent *p = hdr->head;
  ent->prev = NULL;
  ent->next = p;
  if (p)
    p->prev = ent;
  else
    hdr->tail = ent;
  hdr->head = ent;
}

static void
mu_hdrent_append (struct _mu_header *hdr, struct mu_hdrent *ent)
{
  struct mu_hdrent *p = hdr->tail;
  ent->next = NULL;
  ent->prev = p;
  if (p)
    p->next = ent;
  else
    hdr->head = ent;
  hdr->tail = ent;
}

static int
mu_hdrent_insert (struct _mu_header *hdr, struct mu_hdrent *ent,
		  const char *name, int pos, int before)
{
  struct mu_hdrent *p;
  struct mu_hdrent *ref = mu_hdrent_find (hdr, name, pos);
  if (!ref)
    return MU_ERR_NOENT;

  if (before)
    {
      ref = ref->prev;
      if (!ref)
	{
	  mu_hdrent_prepend (hdr, ent);
	  return 0;
	}
    }

  p = ref->next;
  if (!p)
    {
      mu_hdrent_append (hdr, ent);
      return 0;
    }

  ent->next = p;
  p->prev = ent;
  ent->prev = ref;
  ref->next = ent;
  
  return 0;
}

#define SPOOLBLKSIZ 1024

static struct mu_hdrent *
mu_hdrent_create (struct _mu_header *ph,
		  struct mu_hdrent *ent,
		  const char *name, size_t nsize,
		  const char *value, size_t vsize)
{
  size_t strsize;
  size_t sizeleft;
  const char *p;
  
  if (!ent)
    {
      ent = calloc (1, sizeof (*ent));
      if (!ent)
	return NULL;
    }
  
  strsize = MU_STR_SIZE (nsize, vsize);
  sizeleft = ph->spool_size - ph->spool_used;

  /* Ensure there is enough space in spool */
  if (sizeleft < strsize)
    {
      char *newp;
      size_t delta = (strsize - sizeleft + SPOOLBLKSIZ - 1) / SPOOLBLKSIZ;
      delta *= SPOOLBLKSIZ;
      newp = realloc (ph->spool, ph->spool_size + delta);
      if (!newp)
	return 0;
      ph->spool = newp;
      ph->spool_size += delta;
    }

  /* Copy header name */
  ent->fn = ph->spool_used;
  ent->nlen = nsize;
  memcpy (ph->spool + ph->spool_used, name, nsize);
  ph->spool_used += nsize;
  ph->spool[ph->spool_used++] = 0;
  ph->spool[ph->spool_used++] = ' ';

  /* Copy header value */
  ent->fv = ph->spool_used;
  ent->vlen = vsize;
  memcpy (ph->spool + ph->spool_used, value, vsize);
  ph->spool_used += vsize;
  ph->spool[ph->spool_used++] = 0;
  
  ent->nlines = 1;
  for (p = value; p < value + vsize; p++)
    if (*p == '\n')
      ent->nlines++;
  
  return ent;
}

static void
mu_hdrent_free_list (struct _mu_header *hdr)
{
  struct mu_hdrent *p;
  for (p = hdr->head; p; )
    {
      struct mu_hdrent *next = p->next;
      free (p);
      p = next;
    }
  hdr->head = hdr->tail = NULL;
  hdr->spool_used = 0;
}
  


#define ISLWSP(c) (((c) == ' ' || (c) == '\t'))

/* Parsing is done in a rather simple fashion, meaning we just consider an
   entry to be a field-name an a field-value.  So they maybe duplicate of
   field-name like "Received" they are just put in the array, see _get_value()
   on how to handle the case. in the case of error .i.e a bad header construct
   we do a full stop and return what we have so far.  */

static int
header_parse (mu_header_t header, const char *blurb, int len)
{
  const char *header_end;
  const char *header_start;
  const char *header_start2;
  
  /* Nothing to parse.  */
  if (blurb == NULL)
    return 0;

  header->flags |= HEADER_INVALIDATE;
  mu_hdrent_free_list (header);

  /* Get a header, a header is:
     field-name LWSP ':'
       LWSP field-value '\r' '\n'
       *[ (' ' | '\t') field-value '\r' '\n' ]
  */
  /* First loop goes through the blurb */
  for (header_start = blurb;  ; header_start = ++header_end)
    {
      const char *fn, *fn_end, *fv, *fv_end;
      struct mu_hdrent *ent;

      if (header_start[0] == ' '
	  || header_start[0] == '\t'
	  || header_start[0] == '\n')
	break;

      /* Second loop extract one header field. */
      for (header_start2 = header_start;  ;header_start2 = ++header_end)
	{
	  header_end = memchr (header_start2, '\n', len);
	  if (header_end == NULL)
	    break;
	  else
	    {
	      len -= (header_end - header_start2 + 1);
	      if (len < 0)
		{
		  header_end = NULL;
		  break;
		}
	      if (header_end[1] != ' '
		  && header_end[1] != '\t')
		break; /* New header break the inner for. */
	    }
	  /* *header_end = ' ';  smash LF ? NO */
	}

      if (header_end == NULL)
	break; /* FIXME: Bail out.  */
      
      /* Now save the header in the data structure.  */

      /* Treats unix "From " specially.  FIXME: Should we? */
      if ((header_end - header_start >= 5)
      	  && strncmp (header_start, "From ", 5) == 0)
	{
	  fn = header_start;
	  fn_end = header_start + 5;
	  fv = header_start + 5;
	  fv_end = header_end;
	}
      else /* Break the header in key: value */
	{
	  char *colon = memchr (header_start, ':', header_end - header_start);

	  /* Houston we have a problem.  */
	  if (colon == NULL)
	    break; /* FIXME: Disregard the rest and bailout.  */

	  fn = header_start;
	  fn_end = colon;
	  /* Shrink any LWSP after the field name -- CRITICAL for 
	     later name comparisons to work correctly! */
	  while (ISLWSP (fn_end[-1]))
	    fn_end--;

	  fv = colon + 1;
	  fv_end = header_end;

	  /* Skip any LWSP before the field value -- unnecessary, but
	     might make some field values look a little tidier. */
	  while (ISLWSP (fv[0]))
	    fv++;
	}

      /* Register this header */
      ent = mu_hdrent_create (header, NULL, fn, fn_end - fn, fv, fv_end - fv);
      if (!ent)
	return ENOMEM;
      mu_hdrent_append (header, ent);
    } /* for (header_start ...) */

  return 0;
}


static int 
mu_header_fill (mu_header_t header)
{
  int status;
  size_t blurb_len = 0;
  char *blurb = NULL;
  
  if (header->spool_used)
    return 0;
  
  if (header->_fill == NULL)
    return 0; /* FIXME: Really? */

  /* Bring in the entire header.  */
  status = header->_fill (header->data, &blurb, &blurb_len);
  if (status)
    return status;
  status = header_parse (header, blurb, blurb_len);
  free (blurb);
  return status;
}



int
mu_header_create (mu_header_t *ph, const char *blurb, size_t len)
{
  mu_header_t header;
  int status = 0;
  
  header = calloc (1, sizeof (*header));
  if (header == NULL)
    return ENOMEM;
  
  status = header_parse (header, blurb, len);

  *ph = header;
  return status;
}

void
mu_header_destroy (mu_header_t *ph)
{
  if (ph && *ph)
    {  
      mu_header_t header = *ph;

      mu_stream_destroy (&header->stream);
      mu_hdrent_free_list (header);
      free (header->spool);
      free (header);
      *ph = NULL;
    }
}


int
mu_header_set_value (mu_header_t header, const char *fn, const char *fv,
		     int replace)
{
  int status;
  struct mu_hdrent *ent = NULL;
  
  if (header == NULL || fn == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status)
    return status;
  
  /* An fv of NULL means delete the field, but only do it if replace
     was also set to true! */
  if (fv == NULL && !replace)
    return EINVAL;

  if (replace)
    {
      ent = mu_hdrent_find (header, fn, 1);
      if (ent)
	{
	  if (fv == NULL)
	    {
	      /* Delete the header */
	      mu_hdrent_remove (header, ent);
	      free (ent);
	      return 0;
	    }
	  mu_hdrent_create (header, ent, fn, strlen (fn), fv, strlen (fv));
	  HEADER_SET_MODIFIED (header);
	  return 0;
	}
      else if (fv == NULL)
	return 0;
    }

  ent = mu_hdrent_create (header, NULL,
			  fn, strlen (fn), fv, strlen (fv));
  if (!ent)
    return ENOMEM;
  mu_hdrent_prepend (header, ent);
  HEADER_SET_MODIFIED (header);
  return 0;
}

int
mu_header_remove (mu_header_t header, const char *fn, int n)
{
  int status;
  struct mu_hdrent *ent;
  
  if (header == NULL || fn == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status)
    return status;

  ent = mu_hdrent_find (header, fn, n);
  if (!ent)
    return MU_ERR_NOENT;

  mu_hdrent_remove (header, ent);
  HEADER_SET_MODIFIED (header);
  free (ent);
  return 0;
}

int
mu_header_append (mu_header_t header, const char *fn, const char *fv)
{
  int status;
  struct mu_hdrent *ent;

  if (header == NULL || fn == NULL || fv == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status)
    return status;

  ent = mu_hdrent_create (header, NULL, fn, strlen (fn), fv, strlen (fv));
  if (!ent)
    return ENOMEM;
  mu_hdrent_append (header, ent);
  HEADER_SET_MODIFIED (header);
  return 0;
}

int
mu_header_prepend (mu_header_t header, const char *fn, const char *fv)
{
  int status;
  struct mu_hdrent *ent;

  if (header == NULL || fn == NULL || fv == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status)
    return status;

  ent = mu_hdrent_create (header, NULL, fn, strlen (fn), fv, strlen (fv));
  if (!ent)
    return ENOMEM;
  mu_hdrent_prepend (header, ent);
  HEADER_SET_MODIFIED (header);
  return 0;
}

int
mu_header_insert (mu_header_t header,
		  const char *fn, const char *fv, 
		  const char *ref, int n, int flags)
{
  int status;
  struct mu_hdrent *ent;

  if (header == NULL || fn == NULL || fv == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status)
    return status;
    
  if (flags & MU_HEADER_REPLACE)
    {
      if (!ref)
	ref = fn;
      ent = mu_hdrent_find (header, ref, n);
      mu_hdrent_create (header, ent, fn, strlen (fn), fv, strlen (fv));
    }
  else
    {
      ent = mu_hdrent_create (header, NULL,
			      fn, strlen (fn), fv, strlen (fv));
      if (!ent)
	return ENOMEM;
      if (ref)
	return mu_hdrent_insert (header, ent, ref, n,
				 flags & MU_HEADER_BEFORE);
      else
	mu_hdrent_prepend (header, ent);
    }
  HEADER_SET_MODIFIED (header);
  return 0;
}
  

int
mu_header_sget_value_n (mu_header_t header,
			const char *name, int n,
			const char **pval)
{
  int status;
  struct mu_hdrent *ent;

  if (header == NULL || name == NULL)
    return EINVAL;
  status = mu_header_fill (header);
  if (status)
    return status;

  ent = mu_hdrent_find (header, name, n);
  if (!ent)
    return MU_ERR_NOENT;

  *pval = MU_HDRENT_VALUE (header, ent);
  return 0;
}

int
mu_header_aget_value_n (mu_header_t header,
		      const char *name, int n,
		      char **pval)
{
  const char *s;
  int status = mu_header_sget_value_n (header, name, n, &s);
  if (status == 0)
    {
      *pval = strdup (s);
      if (!*pval)
	status = ENOMEM;
    }
  return status;
}

int
mu_header_get_value_n (mu_header_t header, const char *name, int n,
		       char *buffer, size_t buflen, size_t *pn)
{
  const char *s;
  int status = mu_header_sget_value_n (header, name, n, &s);
  if (status == 0)
    {
      size_t slen = strlen (s);

      if (buffer)
	{
	  if (slen > buflen)
	    slen = buflen;
	  memcpy (buffer, s, slen);
	  buffer[slen] = 0;
	}
      if (pn)
	*pn = slen;
    }
  return status;
}


/* Unfolding functions */
int
mu_header_get_value_unfold_n (mu_header_t header,
			      const char *name, int n, char *buffer,
			      size_t buflen, size_t *pn)
{
  int rc = mu_header_get_value_n (header, name, n, buffer, buflen, pn);

  if (rc == 0)
    mu_string_unfold (buffer, pn);
  return rc;
}

int
mu_header_aget_value_unfold_n (mu_header_t header, const char *name, int n,
			       char **pvalue)
{
  int rc = mu_header_aget_value_n (header, name, n, pvalue);
  if (rc == 0)
    mu_string_unfold (*pvalue, NULL);
  return rc;
}


int
mu_header_get_address_n (mu_header_t header, const char *name, int n,
			 mu_address_t *addr)
{
  const char *value = NULL;
  int status = mu_header_sget_value_n (header, name, n, &value);

  if (status)
    return status;

  return mu_address_create (addr, value);
}


int
mu_header_get_field_count (mu_header_t header, size_t *pcount)
{
  size_t count;
  size_t size;
  size_t lines;
  int status;
  
  if (header == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status == 0)
    {
      mu_hdrent_count (header, &count, &size, &lines);
      
      if (pcount)
	*pcount = count;
    }
  
  return status;
}

int
mu_header_sget_field_name (mu_header_t header, size_t num, const char **sptr)
{
  int status;
  
  if (header == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status == 0)
    {
      struct mu_hdrent *ent = mu_hdrent_nth (header, num);
      if (ent)
	*sptr = MU_HDRENT_NAME (header, ent);
      else
	status = MU_ERR_NOENT;
    }
  return status;
}

int
mu_header_get_field_name (mu_header_t header, size_t num, char *buffer,
			  size_t buflen, size_t *pn)
{
  const char *s;
  int status = mu_header_sget_field_name (header, num, &s);
  if (status == 0)
    {
      size_t slen = strlen (s);

      if (buffer)
	{
	  if (slen > buflen)
	    slen = buflen;
	  memcpy (buffer, s, slen);
	  buffer[slen] = 0;
	}
      if (pn)
	*pn = slen;
    }
  return status;
}

int
mu_header_aget_field_name (mu_header_t header, size_t num, char **pvalue)
{
  const char *s;
  int status = mu_header_sget_field_name (header, num, &s);
  if (status == 0)
    {
      if ((*pvalue = strdup (s)) == NULL)
	status = ENOMEM;
    }
  return status;
}


int
mu_header_sget_field_value (mu_header_t header, size_t num, const char **sptr)
{
  int status;
  
  if (header == NULL)
    return EINVAL;

  status = mu_header_fill (header);
  if (status == 0)
    {
      struct mu_hdrent *ent = mu_hdrent_nth (header, num);
      if (ent)
	*sptr = MU_HDRENT_VALUE (header, ent);
      else
	status = MU_ERR_NOENT;
    }
  return status;
}

int
mu_header_get_field_value (mu_header_t header, size_t num, char *buffer,
			   size_t buflen, size_t *pn)
{
  const char *s;
  int status = mu_header_sget_field_value (header, num, &s);
  if (status == 0)
    {
      size_t slen = strlen (s);

      if (buffer)
	{
	  if (slen > buflen)
	    slen = buflen;
	  memcpy (buffer, s, slen);
	  buffer[slen] = 0;
	}
      if (pn)
	*pn = slen;
    }
  return status;
}

int
mu_header_aget_field_value (mu_header_t header, size_t num, char **pvalue)
{
  const char *s;
  int status = mu_header_sget_field_value (header, num, &s);
  if (status == 0)
    {
      if ((*pvalue = strdup (s)) == NULL)
	status = ENOMEM;
    }
  return status;
}

int
mu_header_get_field_value_unfold (mu_header_t header, size_t num, char *buf,
				  size_t buflen, size_t *nwritten)
{
  int rc = mu_header_get_field_value (header, num, buf, buflen, nwritten);
  if (rc == 0)
    mu_string_unfold (buf, nwritten);
  return rc;
}

int
mu_header_aget_field_value_unfold (mu_header_t header, size_t num,
				   char **pvalue)
{
  int rc = mu_header_aget_field_value (header, num, pvalue);
  if (rc == 0)
    mu_string_unfold (*pvalue, NULL);
  return rc;
}


int
mu_header_lines (mu_header_t header, size_t *plines)
{
  int status;

  if (header == NULL)
    return EINVAL;
  if (plines == NULL)
    return MU_ERR_OUT_PTR_NULL;

  status = mu_header_fill (header);
  if (status == 0)
    {
      size_t count;
      size_t size;
      size_t lines;
      mu_hdrent_count (header, &count, &size, &lines);
      *plines = lines + 1;
    }
  return status;
}

int
mu_header_size (mu_header_t header, size_t *psize)
{
  int status;

  if (header == NULL)
    return EINVAL;
  if (psize == NULL)
    return MU_ERR_OUT_PTR_NULL;

  status = mu_header_fill (header);
  if (status == 0)
    {
      size_t count;
      size_t size;
      size_t lines;
      mu_hdrent_count (header, &count, &size, &lines);
      *psize = size + 1;
    }
  return status;
}


static void
mu_hdrent_fixup (mu_header_t hdr, struct mu_hdrent *ent)
{
  char *s = MU_HDRENT_NAME (hdr, ent);
  s[ent->nlen] = ':';
  s = MU_HDRENT_VALUE (hdr, ent);
  s[ent->vlen] = '\n';
}

static void
mu_hdrent_unroll_fixup (mu_header_t hdr, struct mu_hdrent *ent)
{
  char *s = MU_HDRENT_NAME (hdr, ent);
  s[ent->nlen] = 0;
  s = MU_HDRENT_VALUE (hdr, ent);
  s[ent->vlen] = 0;
}

int
header_seek (mu_stream_t str, mu_off_t off, int whence, mu_off_t *presult)
{ 
  struct _mu_header_stream *hstr = (struct _mu_header_stream *) str;

  switch (whence)
    {
    case MU_SEEK_SET:
      break;

    case MU_SEEK_CUR:
      off += hstr->off;
      break;

    case MU_SEEK_END:
      off += hstr->hdr->size;
      break;
    }

  if (off < 0 || off > hstr->hdr->size)
    return EINVAL;
  hstr->off = off;
  return 0;
}

static int
header_read (mu_stream_t is, char *buffer, size_t buflen, size_t *pnread)
{
  struct _mu_header_stream *hstr = (struct _mu_header_stream *) is;
  mu_header_t header;
  struct mu_hdrent *ent;
  size_t ent_off;
  int status;
  size_t nread;
  
  if (is == NULL)
    return EINVAL;

  header = hstr->hdr;
  status = mu_header_fill (header);
  if (status)
    return status;
  
  if (mu_hdrent_find_stream_pos (header, hstr->off, &ent, &ent_off))
    {
      if (pnread)
	*pnread = 0;
      return 0;
    }

  for (nread = 0; nread < buflen && ent; ent = ent->next)
    {
      size_t rest = buflen - nread;
      size_t strsize = MU_STR_SIZE (ent->nlen, ent->vlen) - ent_off;
      if (rest > strsize)
	rest = strsize;
      mu_hdrent_fixup (header, ent);
      memcpy (buffer + nread, MU_HDRENT_NAME (header, ent) + ent_off, rest);
      mu_hdrent_unroll_fixup (header, ent);
      nread += rest;
      hstr->off += rest;
      ent_off = 0;
    }
  if (pnread)
    *pnread = nread;
  return 0;
}

static int
header_write (mu_stream_t os, const char *buf, size_t buflen, size_t *pnwrite)
{
  struct _mu_header_stream *hstr;
  mu_header_t header;
  int status;
  mu_off_t mstream_size;
  
  if (!os || !buf)
    return EINVAL;

  hstr = (struct _mu_header_stream *) os;
  header = hstr->hdr;
  if (header == NULL)
    return EINVAL;
  
  /* Skip the obvious.  */
  if (*buf == '\0' || buflen == 0)
    {
      if (pnwrite)
        *pnwrite = 0;
      return 0;
    }

  if (!header->mstream)
    {
      status = mu_memory_stream_create (&header->mstream, MU_STREAM_RDWR);
      if (status)
	return status;
      status = mu_stream_open (header->mstream);
      if (status)
	{
	  mu_stream_destroy (&header->mstream);
	  return status;
	}
    }

  status = mu_stream_write (header->mstream, buf, buflen, NULL);
  if (status)
    {
      mu_stream_destroy (&header->mstream);
      return status;
    }

  status = mu_stream_size (header->mstream, &mstream_size);
  if (status == 0 && mstream_size > 1)
    {
      char nlbuf[2];

      status = mu_stream_seek (header->mstream, -2, MU_SEEK_END, NULL);
      if (status == 0)
	status = mu_stream_read (header->mstream, nlbuf, 2, NULL);
      if (status == 0 && memcmp (nlbuf, "\n\n", 2) == 0)
	{
	  char *blurb;

	  blurb = calloc (1, mstream_size + 1);
	  if (blurb)
	    {
	      mu_stream_read (header->mstream, blurb, mstream_size, NULL);
	      status = header_parse (header, blurb, mstream_size);
	    }
	  free (blurb);
	  mu_stream_destroy (&header->mstream);
	}
    }
  
  if (pnwrite)
    *pnwrite = buflen;
  
  return status;
}

static int
header_size (mu_stream_t str, mu_off_t *psize)
{
  mu_header_t header;
  int status;
  size_t size;
  
  if (str == NULL)
    return EINVAL;
  if (psize == NULL)
    return MU_ERR_OUT_PTR_NULL;
  
  header = ((struct _mu_header_stream *) str)->hdr;
  status = mu_header_fill (header);
  if (status)
    return status;
  status = mu_header_size (header, &size);
  if (status == 0)
    *psize = size;
  return status;
}

static int
_header_get_stream (mu_header_t header, mu_stream_t *pstream, int ref)
{
  if (header == NULL)
    return EINVAL;

  if (pstream == NULL)
    return MU_ERR_OUT_PTR_NULL;

  if (header->stream == NULL)
    {
      struct _mu_header_stream *str = 
	(struct _mu_header_stream *) _mu_stream_create (sizeof (*str),
							MU_STREAM_RDWR|MU_STREAM_SEEK);
      if (!str)
	return ENOMEM;
      str->stream.read = header_read;
      /*str->stream.rdelim? */
      str->stream.write = header_write;
      str->stream.seek = header_seek;
      str->stream.size = header_size;
      str->hdr = header;
      header->stream = (mu_stream_t) str;
    }
  if (!ref)
    {
      *pstream = header->stream;
      return 0;
    }
  return mu_streamref_create (pstream, header->stream);
}

int
mu_header_get_stream (mu_header_t header, mu_stream_t *pstream)
{
  /* FIXME: Deprecation warning */
  return _header_get_stream (header, pstream, 0);
}

int
mu_header_get_streamref (mu_header_t header, mu_stream_t *pstream)
{
  return _header_get_stream (header, pstream, 1);
}


int
mu_header_set_fill (mu_header_t header, int
		    (*_fill) (void *data, char **, size_t *),
		    void *data)
{
  if (header == NULL)
    return EINVAL;
  header->_fill = _fill;
  header->data = data;
  return 0;
}


int
mu_header_is_modified (mu_header_t header)
{
  return header ? (header->flags & HEADER_MODIFIED) : 0;
}

int
mu_header_clear_modified (mu_header_t header)
{
  if (header)
    header->flags &= ~HEADER_MODIFIED;
  return 0;
}