header.c 27.7 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 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001 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 2 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA  */

#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 <header0.h>

#define HEADER_MODIFIED 1

static int header_parse    __P ((header_t, const char *, int));
static int header_read     __P ((stream_t, char *, size_t, off_t, size_t *));
static int header_readline __P ((stream_t, char *, size_t, off_t, size_t *));
static int header_write    __P ((stream_t, const char *, size_t, off_t,
				 size_t *));
static int fill_blurb      __P ((header_t));
static void header_free_cache __P ((header_t));

int
header_create (header_t *ph, const char *blurb, size_t len, void *owner)
{
  header_t header;
  int status = 0;

  header = calloc (1, sizeof (*header));
  if (header == NULL)
    return ENOMEM;

  header->owner = owner;

  status = header_parse (header, blurb, len);

  *ph = header;
  return status;
}

static void
header_free_cache (header_t header)
{
  /* Clean up our fast header cache.  */
  if (header->fhdr)
    {
      size_t i;
      for (i = 0; i < header->fhdr_count; i++)
	{
	  if (header->fhdr[i].fn)
	    free (header->fhdr[i].fn);
	  if (header->fhdr[i].fv)
	    free (header->fhdr[i].fv);
	}
      free (header->fhdr);
      header->fhdr = NULL;
      header->fhdr_count = 0;
    }
}

void
header_destroy (header_t *ph, void *owner)
{
  if (ph && *ph)
    {
      header_t header = *ph;

      /* Can we destroy ?.  */
      if (header->owner == owner)
	{
	  stream_destroy (&(header->stream), header);

	  if (header->hdr)
	    free (header->hdr);

	  if (header->blurb)
	    free (header->blurb);

	  header_free_cache (header);

	  if (header->mstream)
	    stream_destroy (&(header->mstream), NULL);

	  free (header);
	}
      *ph = NULL;
    }
}

void *
header_get_owner (header_t header)
{
  return (header) ? header->owner : NULL;
}

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

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

/* 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 (header_t header, const char *blurb, int len)
{
  char *header_end;
  char *header_start;
  char *header_start2;
  struct _hdr *hdr;

  /* Nothing to parse.  */
  if (blurb == NULL)
    return 0;

  header->blurb_len = len;
  /* Why "+ 1", if for a terminating NULL, where is written? */
  header->blurb = calloc (1, header->blurb_len + 1);
  if (header->blurb == NULL)
    return ENOMEM;
  memcpy (header->blurb, blurb, header->blurb_len);

  if (header->hdr)
    free (header->hdr);
  header->hdr = NULL;
  header->hdr_count = 0;

  /* 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 = header->blurb;  ; header_start = ++header_end)
    {
      char *fn, *fn_end, *fv, *fv_end;

      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; /* Bail out.  */

      /* Now save the header in the data structure.  */

      /* Treats unix "From " specially.  */
      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);

#define ISLWSP(c) (((c) == ' ' || (c) == '\t'))
	  /* Houston we have a problem.  */
	  if (colon == NULL)
	    break; /* 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++;
	}
#undef ISLWSP
      /* Allocate a new slot for the field:value.  */
      hdr = realloc (header->hdr, (header->hdr_count + 1) * sizeof (*hdr));
      if (hdr == NULL)
	{
	  free (header->blurb);
	  free (header->hdr);
	  header->blurb = NULL;
	  header->hdr = NULL;
	  return ENOMEM;
	}
      hdr[header->hdr_count].fn = fn;
      hdr[header->hdr_count].fn_end = fn_end;
      hdr[header->hdr_count].fv = fv;
      hdr[header->hdr_count].fv_end = fv_end;
      header->hdr = hdr;
      header->hdr_count++;
    } /* for (header_start ...) */

 return 0;
}

/* FIXME: grossly inneficient, to many copies and reallocating.
   This all header business need a good rewrite.  */
int
header_set_value (header_t header, const char *fn, const char *fv,
		  int replace)
{
  char *blurb;
  size_t len;

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

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

  /* Overload.  */
  if (header->_set_value)
    return header->_set_value (header, fn, fv, replace);

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  /* Easy approach: if replace, overwrite the field-{name,value} and readjust
     the pointers by calling header_parse () this is wastefull, we're just
     fragmenting the memory it can be done better.  But that may imply a
     rewite of the headers ... for another day.  */

  /* If replace, remove all fields in the header blurb that have the
     same name as the field we are writing.

     Algorithm:

     for i = 0, ... i < max_hdrs
     - if ith field has name 'fn' memmove() all following fields up over
     this field
     - reparse the headers
     - restart the for loop at the ith field
   */
  if (replace)
    {
      size_t name_len;
      size_t i;
      size_t fn_len;		/* Field Name len.  */
      size_t fv_len;		/* Field Value len.  */
      len = header->blurb_len;
      /* Find FN in the header fields... */
      for (name_len = strlen (fn), i = 0; i < header->hdr_count; i++)
	{
	  fn_len = header->hdr[i].fn_end - header->hdr[i].fn;
	  fv_len = header->hdr[i].fv_end - header->hdr[i].fv;
	  if (fn_len == name_len &&
	      strncasecmp (header->hdr[i].fn, fn, fn_len) == 0)
	    {
	      blurb = header->blurb;
	      /* ... and if its NOT the last field, move the next field
	         through to last field into its place, */
	      if ((i + 1) < header->hdr_count)
		{
		  memmove (header->hdr[i].fn, header->hdr[i + 1].fn,
			   header->hdr[header->hdr_count - 1].fv_end
			   - header->hdr[i + 1].fn + 3);
		}
	      /* or if it is the last, just truncate the fields. */
	      else
		{
		  header->hdr[i].fn[0] = '\n';
		  header->hdr[i].fn[1] = '\0';
		}
	      /* Readjust the pointers. */
	      /* FIXME: I'm not sure this 3 will work when the
	         original data looked like:
	         Field  :   Value
	         Test this... and why not just do a strlen(blurb)?
	       */
	      len -= fn_len + fv_len + 3;	/* :<sp>\n */
	      i--;
	      blurb = header->blurb;
	      header_parse (header, blurb, len);
	      free (blurb);
	      header->flags |= HEADER_MODIFIED;
	    }
	}
    }

  /* If FV is NULL, then we are done. */
  if (!fv)
    return 0;

  /* Replacing was taken care of above, now write the new header.
     header.  Really not cute.
     COLON SPACE NL =  3 ;  */
  len = strlen (fn) + strlen (fv) + 3;
  /* Add one for the NULL and leak a bit by adding one more
     it will be the separtor \n from the body if the first
     blurb did not have it.  */
  blurb = calloc (header->blurb_len + len + 2, 1);
  if (blurb == NULL)
    return ENOMEM;

  sprintf (blurb, "%s: %s", fn, fv);

  /* Strip off trailing newlines and LWSP. */
  while (blurb[strlen (blurb) - 1] == '\n' ||
	 blurb[strlen (blurb) - 1] == ' ' ||
	 blurb[strlen (blurb) - 1] == '\t')
    {
      blurb[strlen (blurb) - 1] = '\0';
    }
  len = strlen (blurb);
  blurb[len] = '\n';
  len++;

  /* Prepend the rest of the headers.  */
  if (header->blurb)
    {
      memcpy (blurb + len, header->blurb, header->blurb_len);
      free (header->blurb);
      header->blurb = NULL;
    }
  else
    blurb[len] = '\n';

  /* before parsing the new blurb make sure it is properly terminated
     by \n\n. The trailing NL separator.  */
  if (blurb[header->blurb_len + len - 1] != '\n'
      || blurb[header->blurb_len + len - 2] != '\n')
    {
      blurb[header->blurb_len + len] = '\n';
      len++;
    }
  header_parse (header, blurb, len + header->blurb_len);
  free (blurb);
  header->flags |= HEADER_MODIFIED;
  return 0;
}

/* We try to cache the headers here to reduce networking access
   especially for IMAP.  When the buffer is NULL it means that
   the field does not exist on the server and we should not
   attempt to contact the server again for this field.  */
static int
header_set_fvalue (header_t header, const char *name, char *buffer)
{
  struct _hdr *thdr;
  thdr = realloc (header->fhdr, (header->fhdr_count + 1) * sizeof(*thdr));
  if (thdr)
    {
      size_t len = strlen (name);
      char *field = malloc (len + 1);
      if (field == NULL)
	return ENOMEM;
      memcpy (field, name, len);
      field[len] = '\0';
      thdr[header->fhdr_count].fn = field;
      thdr[header->fhdr_count].fn_end = field + len;

      if (buffer)
	{
          len = strlen (buffer);
          field =  malloc (len + 1);
          if (field == NULL)
	    return ENOMEM;
	  memcpy (field, buffer, len);
	  field[len] = '\0';
	  thdr[header->fhdr_count].fv = field;
	  thdr[header->fhdr_count].fv_end = field + len;
	}
      else
	{
	  thdr[header->fhdr_count].fv = NULL;
	  thdr[header->fhdr_count].fv_end = NULL;
	}
      header->fhdr_count++;
      header->fhdr = thdr;
      return 0;
    }
  return ENOMEM;
}

/* For the cache header if the field exist but with no corresponding
   value, it is a permanent failure i.e.  the field does not exist
   in the header return EINVAL to notify header_get_value().  */
static int
header_get_fvalue (header_t header, const char *name, char *buffer,
		  size_t buflen, size_t *pn)
{
  size_t i, fn_len, fv_len = 0;
  size_t name_len;
  int err = ENOENT;

  for (i = 0, name_len = strlen (name); i < header->fhdr_count; i++)
    {
      fn_len = header->fhdr[i].fn_end - header->fhdr[i].fn;
      if (fn_len == name_len
	  && strcasecmp (header->fhdr[i].fn, name) == 0)
	{
	  fv_len = header->fhdr[i].fv_end - header->fhdr[i].fv;

	  /* Permanent failure.  */
	  if (fv_len == 0)
	    {
	      err = EINVAL;
	      break;
	    }

	  if (buffer && buflen > 0)
	    {
	      buflen--;
	      fv_len = (fv_len < buflen) ? fv_len : buflen;
	      memcpy (buffer, header->fhdr[i].fv, fv_len);
	      buffer[fv_len] = '\0';
	    }
	  err = 0;
	  break;
	}
    }
  if (pn)
    *pn = fv_len;
  return err;

}

int
header_get_value (header_t header, const char *name, char *buffer,
		  size_t buflen, size_t *pn)
{
  size_t i = 0;
  size_t name_len;
  size_t total = 0, fn_len = 0, fv_len = 0;
  size_t threshold;
  int err = 0;

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

  /* First scan our cache headers for hits.  */
  err = header_get_fvalue (header, name, buffer, buflen, pn);
  switch (err)
    {
    case EINVAL: /* Permanent failure.  */
      err = ENOENT;
    case ENOMEM:
      if (pn)
	*pn = 0;
    case 0:
      return err;
    }

  /* Try the provided cache.  */
  if (header->_get_fvalue)
    err = header->_get_fvalue (header, name, buffer, buflen, pn);
  if (err == 0)
    return 0;

  if (header->_get_value)
    {
      char buf[1024]; /* should suffice for field-value. */
      size_t len = 0;
      err = header->_get_value (header, name, buf, sizeof (buf), &len);
      if (err == 0)
	{
	  /* Save in the fast header buffer.  */
	  header_set_fvalue (header, name, buf);
	  if (buffer && buflen > 0)
	    {
	      buflen--;
	      buflen = (len < buflen) ? len : buflen;
	      memcpy (buffer, buf, buflen);
	      buffer[buflen] = '\0';
	    }
	  else
	    buflen = len;
	  if (pn)
	    *pn = buflen;
	}
      else
        {
	  /* Cache permanent failure also.  */
	  header_set_fvalue (header, name, NULL);
        }
      return err;
    }

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  /* We set the threshold to be 1 less for the null.  */
  threshold = --buflen;

  /* Caution: We may have more then one value for a field name, for example
     a "Received" field-name is added by each passing MTA.  The way that the
     parsing (_parse()) is done it's not take to account.  So we just stuff
     in the buffer all the field-values to a corresponding field-name.
     FIXME: Should we kosher the output ? meaning replace occurences of
     " \t\r\n" for spaces ? for now we don't.
   */
  for (name_len = strlen (name), i = 0; i < header->hdr_count; i++)
    {
      fn_len = header->hdr[i].fn_end - header->hdr[i].fn;
      if (fn_len == name_len &&
	  strncasecmp (header->hdr[i].fn, name, fn_len) == 0)
	{
	  fv_len = (header->hdr[i].fv_end - header->hdr[i].fv);
	  /* FIXME:FIXME:PLEASE: hack, add a space/nl separator  */
	  /*
	  if (total && (threshold - 2) > 0)
	    {
	      if (buffer)
		{
		  *buffer++ = '\n';
		  *buffer++ = ' ';
		}
	      threshold -= 2;
	      total += 2;
	    }
          */
	  total += fv_len;
	  /* Can everything fit in the buffer.  */
	  if (buffer && threshold > 0)
	    {
	      buflen = (fv_len < threshold) ? fv_len : threshold;
	      memcpy (buffer, header->hdr[i].fv, buflen);
	      buffer += buflen;
	      threshold -= buflen;
	    }

	  /* Jump out after the first header we found. -sr */
	  break;
	}
    }
  if (buffer)
    *buffer = '\0'; /* Null terminated.  */
  if (pn)
    *pn = total;

  return  (total == 0) ? ENOENT : 0;
}

int
header_get_value_unfold (header_t header, const char *name, char *buffer,
			 size_t buflen, size_t *pn)
{
  int rc = header_get_value (header, name, buffer, buflen, pn);

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

int
header_aget_value (header_t header, const char *name, char **pvalue)
{
  char *value;
  size_t n = 0;
  int status = header_get_value (header, name, NULL, 0, &n);
  if (status == 0)
    {
      value = calloc (n + 1, 1);
      if (value == NULL)
        return ENOMEM;
      header_get_value (header, name, value, n + 1, NULL);
      *pvalue = value;
    }

  return status;
}

int
header_aget_value_unfold (header_t header, const char *name, char **pvalue)
{
  int rc = header_aget_value (header, name, pvalue);
  if (rc == 0)
    mu_string_unfold (*pvalue, NULL);
  return rc;
}

int
header_get_address (header_t header, const char *name, address_t *addr)
{
  char* value = NULL;
  int status = header_aget_value(header, name, &value);

  if(status)
    return status;

  status = address_create(addr, value);

  free(value);

  return status;
}

int
header_get_field_count (header_t header, size_t *pcount)
{
  if (header == NULL)
    {
      if (pcount)
        *pcount = 0;
      return EINVAL;
    }

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  if (pcount)
    *pcount = header->hdr_count;
  return 0;
}

int
header_get_field_name (header_t header, size_t num, char *buf,
		       size_t buflen, size_t *nwriten)
{
  size_t len;

  if (header == NULL)
    return EINVAL;

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  if (header->hdr_count == 0 || num > header->hdr_count || num == 0)
    return ENOENT;

  num--;
  len = (header->hdr[num].fn_end - header->hdr[num].fn);
  if (buf && buflen)
    {
      /* save one for the null */
      --buflen;
      len = (len > buflen) ? len : len;
      memcpy (buf, header->hdr[num].fn, len);
      buf[len] = '\0';
    }
  if (nwriten)
    *nwriten = len;
  return 0;
}

int
header_aget_field_name (header_t header, size_t num, char **pvalue)
{
  char *value;
  size_t n = 0;
  int status = header_get_field_name (header, num, NULL, 0, &n);
  if (status == 0)
    {
      value = calloc (n + 1, 1);
      if (value == NULL)
        return ENOMEM;
      header_get_field_name (header, num, value, n + 1, NULL);
      *pvalue = value;
    }
  else
    *pvalue  = strdup ("");
  return status;
}

int
header_get_field_value (header_t header, size_t num, char *buf,
			size_t buflen, size_t *nwritten)
{
  size_t len;

  if (header == NULL || num < 1)
    return EINVAL;

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  if (header->hdr_count == 0 || num > header->hdr_count || num == 0)
    return ENOENT;

  num--;
  len = header->hdr[num].fv_end - header->hdr[num].fv;
  if (buf && buflen > 0)
    {
      /* save one for the null */
      --buflen;
      len = (len > buflen) ? buflen : len;
      memcpy (buf, header->hdr[num].fv, len);
      buf[len] = '\0';
    }

  if (nwritten)
    *nwritten = len;
  return 0;
}

int
header_get_field_value_unfold (header_t header, size_t num, char *buf,
			       size_t buflen, size_t *nwritten)
{
  int rc = header_get_field_value (header, num, buf, buflen, nwritten);
  if (rc == 0)
    mu_string_unfold (buf, nwritten);
  return rc;
}

int
header_aget_field_value (header_t header, size_t num, char **pvalue)
{
  char *value;
  size_t n = 0;
  int status = header_get_field_value (header, num, NULL, 0, &n);
  if (status == 0)
    {
      value = calloc (n + 1, 1);
      if (value == NULL)
        return ENOMEM;
      header_get_field_value (header, num, value, n + 1, NULL);
      *pvalue = value;
    }
  else
    *pvalue = strdup ("");
  return status;
}

int
header_aget_field_value_unfold (header_t header, size_t num, char **pvalue)
{
  int rc = header_aget_field_value (header, num, pvalue);
  if (rc == 0)
    mu_string_unfold (*pvalue, NULL);
  return rc;
}

int
header_set_lines (header_t header, int (*_lines)
		 (header_t, size_t *), void *owner)
{
  if (header ==  NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->_lines = _lines;
  return 0;
}

int
header_lines (header_t header, size_t *plines)
{
  int n;
  size_t lines = 0;
  if (header == NULL || plines == NULL)
    return EINVAL;

  /* Overload.  */
  if (header->_lines)
    return header->_lines (header, plines);

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  for (n = header->blurb_len - 1; n >= 0; n--)
    {
      if (header->blurb[n] == '\n')
	lines++;
    }
  if (plines)
    *plines = lines;
  return 0;
}

int
header_set_size (header_t header, int (*_size)
		 (header_t, size_t *), void *owner)
{
  if (header ==  NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->_size = _size;
  return 0;
}

int
header_size (header_t header, size_t *psize)
{
  if (header == NULL)
      return EINVAL;

  /* Overload.  */
  if (header->_size)
    return header->_size (header, psize);

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  if (psize)
    *psize = header->blurb_len;
  return 0;
}

int
header_set_get_fvalue (header_t header, int (*_get_fvalue)
		       __P ((header_t, const char *, char *, size_t,
			     size_t *)), void *owner)
{
  if (header == NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->_get_fvalue = _get_fvalue;
  return 0;
}

int
header_set_get_value (header_t header, int (*_get_value)
		     __P ((header_t, const char *, char *, size_t, size_t *)),
		     void *owner)
{
  if (header == NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->_get_value = _get_value;
  return 0;
}

int
header_set_set_value (header_t header, int (*_set_value)
		      (header_t , const char *, const char *, int),
		      void *owner)
{
  if (header == NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->_set_value = _set_value;
  return 0;
}

int
header_set_stream (header_t header, stream_t stream, void *owner)
{
  if (header == NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->stream = stream;
  return 0;
}

int
header_set_fill (header_t header, int
		 (*_fill) __P ((header_t, char *, size_t, off_t, size_t *)),
		 void *owner)
{
  if (header == NULL)
    return EINVAL;
  if (header->owner != owner)
    return EACCES;
  header->_fill = _fill;
  return 0;
}

static int
fill_blurb (header_t header)
{
  int status;
  char buf[1024];
  size_t nread;

  if (header->_fill == NULL)
    return 0;

  /* The entire header is now ours(part of header_t), clear all the
     overloading.  */
  header_free_cache (header);
  header->_get_fvalue = NULL;
  header->_get_value = NULL;
  header->_set_value = NULL;
  header->_size = NULL;
  header->_lines = NULL;

  if (header->mstream == NULL)
    {
      status = memory_stream_create (&header->mstream, NULL, MU_STREAM_RDWR);
      if (status != 0)
	return status;
      stream_open (header->mstream);
      header->stream_len = 0;
    }

  /* Bring in the entire header.  */
  do
    {
      nread = 0;
      status = header->_fill (header, buf, sizeof buf,
			      header->stream_len, &nread) ;
      if (status != 0)
	{
	  if (status != EAGAIN && status != EINTR)
	    {
	      stream_destroy (&(header->mstream), NULL);
	      header->stream_len = 0;
	    }
	  return status;
	}
      if (nread > 0)
	{
	  status = stream_write (header->mstream, buf, nread, header->stream_len, NULL);
	  if (status != 0)
	    {
	      stream_destroy (&(header->mstream), NULL);
	      header->stream_len = 0;
	      return status;
	    }
	  header->stream_len += nread;
	}
    }
  while (nread > 0);

  /* parse it. */
  {
    char *blurb;
    size_t len = header->stream_len;
    blurb = calloc (1, len + 1);
    if (blurb)
      {
	stream_read (header->mstream, blurb, len, 0, &len);
	status = header_parse (header, blurb, len);
      }
    free (blurb);
  }
  stream_destroy (&header->mstream, NULL);
  header->stream_len = 0;
  return status;
}

static int
header_write (stream_t os, const char *buf, size_t buflen,
	      off_t off, size_t *pnwrite)
{
  header_t header = stream_get_owner (os);
  int status;

  if (header == NULL)
    return EINVAL;

  if ((size_t)off != header->stream_len)
    return ESPIPE;

  /* Skip the obvious.  */
  if (buf == NULL || *buf == '\0' || buflen == 0)
    {
      if (pnwrite)
        *pnwrite = 0;
      return 0;
    }

  if (header->mstream == NULL)
    {
      status = memory_stream_create (&header->mstream, NULL, MU_STREAM_RDWR);
      if (status != 0)
	return status;
      status = stream_open (header->mstream);
      if (status != 0)
      {
	stream_destroy(&header->mstream, NULL);
	return status;
      }
      header->stream_len = 0;
    }

  status = stream_write (header->mstream, buf, buflen, header->stream_len, &buflen);
  if (status != 0)
    {
      stream_destroy (&header->mstream, NULL);
      header->stream_len = 0;
      return status;
    }
  header->stream_len += buflen;

  /* We detect an empty line .i.e "^\n$" this signal the end of the
     header.  */
  if (header->stream_len)
    {
      int finish = 0;
      char nlnl[2];
      nlnl[1] = nlnl[0] = '\0';
      stream_read (header->mstream, nlnl, 1, 0, NULL);
      if (nlnl[0] == '\n')
	{
	  finish = 1;
	}
      else
	{
	  stream_read (header->mstream, nlnl, 2, header->stream_len - 2, NULL);
	  if (nlnl[0] == '\n' && nlnl[1] == '\n')
	    {
	      finish = 1;
	    }
	}
      if (finish)
	{
	  char *blurb;
	  size_t len = header->stream_len;
	  blurb = calloc (1, len + 1);
	  if (blurb)
	    {
	      stream_read (header->mstream, blurb, len, 0, &len);
	      status = header_parse (header, blurb, len);
	    }
	  free (blurb);
	  stream_destroy (&header->mstream, NULL);
	  header->stream_len = 0;
	}
  }

  if (pnwrite)
    *pnwrite = buflen;
  return 0;

}

static int
header_read (stream_t is, char *buf, size_t buflen, off_t off, size_t *pnread)
{
  int len;
  header_t header = stream_get_owner (is);

  if (is == NULL || header == NULL)
    return EINVAL;

  if (buf == NULL || buflen == 0)
    {
      if (pnread)
	*pnread = 0;
      return 0;
    }

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  len = header->blurb_len - off;
  if (len > 0)
    {
      len = (buflen < (size_t)len) ? buflen : (size_t)len;
      memcpy (buf, header->blurb + off, len);
    }
  else
    len = 0;

  if (pnread)
    *pnread = len;
  return 0;
}

static int
header_readline (stream_t is, char *buf, size_t buflen, off_t off, size_t *pn)
{
  int len;
  header_t header = stream_get_owner (is);

  if (is == NULL || header == NULL)
    return EINVAL;

  if (buf == NULL || buflen == 0)
    {
      if (pn)
	*pn = 0;
      return 0;
    }

  /* Try to fill out the buffer, if we know how.  */
  if (header->blurb == NULL)
    {
      int err = fill_blurb (header);
      if (err != 0)
	return err;
    }

  buflen--; /* Space for the null.  */

  len = header->blurb_len - off;
  if (len > 0)
    {
      char *nl = memchr (header->blurb + off, '\n', len);
      if (nl)
	len = nl - (header->blurb + off) + 1;
      len = (buflen < (size_t)len) ? buflen : (size_t)len;
      memcpy (buf, header->blurb + off, len);
    }
  else
    len = 0;
  if (pn)
    *pn = len;
  buf[len] = '\0';
  return 0;
}

int
header_get_stream (header_t header, stream_t *pstream)
{
  if (header == NULL || pstream == NULL)
    return EINVAL;
  if (header->stream == NULL)
    {
      int status = stream_create (&(header->stream), MU_STREAM_RDWR, header);
      if (status != 0)
	return status;
      stream_set_read (header->stream, header_read, header);
      stream_set_readline (header->stream, header_readline, header);
      stream_set_write (header->stream, header_write, header);
    }
  *pstream = header->stream;
  return 0;
}