mbx_imap.c 30.1 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
/* GNU mailutils - a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU Library General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program 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 Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

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

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

#include <mailutils/address.h>
#include <mailbox0.h>
#include <registrar0.h>
#include <imap0.h>

/* Functions to overload the mailbox_t API.  */
static void mailbox_imap_destroy (mailbox_t);
static int mailbox_imap_open (mailbox_t, int);
static int mailbox_imap_close (mailbox_t);
static int imap_expunge (mailbox_t);
static int imap_get_message (mailbox_t, size_t, message_t *);
static int imap_messages_count (mailbox_t, size_t *);
static int imap_scan (mailbox_t, size_t, size_t *);
static int imap_is_updated (mailbox_t);
static int imap_append_message (mailbox_t, message_t);

/* Message API.  */

static int imap_message_size (message_t, size_t *);
static int imap_message_lines (message_t, size_t *);
static int imap_message_fd (stream_t, int *);
static int imap_message_read (stream_t , char *, size_t, off_t, size_t *);
static int imap_message_uid (message_t, char *, size_t, size_t *);

/* Mime handling.  */
static int imap_is_multipart (message_t, int *);
static int imap_get_num_parts (message_t, size_t *);
static int imap_get_part (message_t, size_t, message_t *);

/* Envelope.  */
static int imap_envelope_sender (envelope_t, char *, size_t, size_t *);
static int imap_envelope_date (envelope_t, char *, size_t, size_t *);

/* Attributes.  */
static int imap_attr_flags (attribute_t, int *);

/* Header.  */
static int imap_header_read (stream_t, char*, size_t, off_t, size_t *);
static int imap_header_get_value (header_t, const char*, char *, size_t, size_t *);
static int imap_header_fd (stream_t, int *);

/* Body.  */
static int imap_body_read (stream_t, char *, size_t, off_t, size_t *);
static int imap_body_size (body_t, size_t *);
static int imap_body_lines (body_t, size_t *);
static int imap_body_fd (stream_t, int *);

/* Private. */
static int imap_get_fd (msg_imap_t, int *);
static int imap_get_message0 (msg_imap_t, message_t *);
static int message_operation (f_imap_t, msg_imap_t, enum imap_state, char *,
			      size_t, size_t *);
static void free_subparts (msg_imap_t);

/* Initialize the concrete object mailbox_t by overloading the function of the
   structure.  */
int
_mailbox_imap_init (mailbox_t mailbox)
{
  m_imap_t m_imap;
  size_t name_len = 0;
  m_imap = mailbox->data = calloc (1, sizeof (*m_imap));
  if (m_imap == NULL)
    return ENOMEM;

  /* Retrieve the name of the mailbox from the URL.  */
  url_get_path (mailbox->url, NULL, 0, &name_len);
  if (name_len == 0)
    {
      /* name "INBOX" is the default.  */
      m_imap->name = calloc (6, sizeof (char));
      strcpy (m_imap->name, "INBOX");
    }
  else
    {
      m_imap->name = calloc (name_len + 1, sizeof (char));
      url_get_path (mailbox->url, m_imap->name, name_len + 1, NULL);
    }

  /* Overload the functions.  */
  mailbox->_destroy = mailbox_imap_destroy;

  mailbox->_open = mailbox_imap_open;
  mailbox->_close = mailbox_imap_close;

  /* Messages.  */
  mailbox->_get_message = imap_get_message;
  mailbox->_append_message = imap_append_message;
  mailbox->_messages_count = imap_messages_count;
  mailbox->_expunge = imap_expunge;

  mailbox->_scan = imap_scan;
  mailbox->_is_updated = imap_is_updated;

  /* Get the back pointer of the concrete folder. */
  if (mailbox->folder)
    m_imap->f_imap = mailbox->folder->data;
  /* maibox back pointer.  */
  m_imap->mailbox = mailbox;

  return 0;
}

/* Recursive call to free all the subparts of a message.  */
static void
free_subparts (msg_imap_t msg_imap)
{
  size_t i;
  for (i = 0; i < msg_imap->num_parts; i++)
    if (msg_imap->parts[i])
      free_subparts (msg_imap->parts[i]);

  if (msg_imap->message)
    message_destroy (&(msg_imap->message), msg_imap);
  if (msg_imap->uid)
    free (msg_imap->uid);
  if (msg_imap->parts)
    free (msg_imap->parts);
  free(msg_imap);
}

/* Give back all the resources. But is does not mean to shutdown the channel
   this is done on the folder.  */
static void
mailbox_imap_destroy (mailbox_t mailbox)
{
  if (mailbox->data)
    {
      m_imap_t m_imap = mailbox->data;
      f_imap_t f_imap = m_imap->f_imap;
      size_t i;

      /* Deselect.  */
      if (m_imap != f_imap->selected)
	f_imap->selected = NULL;

      monitor_wrlock (mailbox->monitor);
      /* Destroy the imap messages and ressources associated to them.  */
      for (i = 0; i < m_imap->imessages_count; i++)
	if (m_imap->imessages[i])
	  free_subparts (m_imap->imessages[i]);
      if (m_imap->imessages)
	free (m_imap->imessages);
      if (m_imap->name)
	free (m_imap->name);
      free (m_imap);
      mailbox->data = NULL;
      monitor_unlock (mailbox->monitor);
    }
}

/* If the connection was not up it is open by the folder.  It is not necessary
   to set this mailbox selected on the folder, there maybe on going operation.
   But on any operation, if is not selected will send the SELECT.  */
static int
mailbox_imap_open (mailbox_t mailbox, int flags)
{
  return folder_open (mailbox->folder, flags);
}

/* We can not close the folder in term of shuting down the connection but if
   we were the selected mailbox we send the close and deselect ourself.  */
static int
mailbox_imap_close (mailbox_t mailbox)
{
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* It was not selected.  */
  if (m_imap != f_imap->selected)
    return 0;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      status = imap_writeline (f_imap, "g%d CLOSE\r\n", f_imap->seq++);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_CLOSE;

    case IMAP_CLOSE:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_CLOSE_ACK;

    case IMAP_CLOSE_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);

    default:
      break;
    }

  /* Deselect.  */
  f_imap->selected = NULL;

  f_imap->state = IMAP_NO_STATE;
  return status;
}

/* Construction of the message_t, nothing else is done then this setup.  To
   clarify this is different from say message_get_part().  This call is for the
   mailbox and we are setting up the message_t structure.  */
static int
imap_get_message (mailbox_t mailbox, size_t msgno, message_t *pmsg)
{
  m_imap_t m_imap = mailbox->data;
  msg_imap_t msg_imap;
  int status = 0;
  size_t i;

  if (pmsg == NULL)
    return EINVAL;

  monitor_rdlock (mailbox->monitor);
  /* See if we have already this message.  */
  for (i = 0; i < m_imap->imessages_count; i++)
    {
      if (m_imap->imessages[i])
        {
          if (m_imap->imessages[i]->num == msgno)
            {
              *pmsg = m_imap->imessages[i]->message;
              monitor_unlock (mailbox->monitor);
              return 0;
            }
        }
    }
  monitor_unlock (mailbox->monitor);

  /* Allocate a concrete imap message.  */
  msg_imap = calloc (1, sizeof (*msg_imap));
  if (msg_imap == NULL)
    return ENOMEM;
  /* Back pointer.  */
  msg_imap->m_imap = m_imap;
  msg_imap->num = msgno;
  status = imap_get_message0 (msg_imap, pmsg);
  if (status == 0)
    {
      /* Add it to the list.  */
      monitor_wrlock (mailbox->monitor);
      {
	msg_imap_t *m ;
	m = realloc (m_imap->imessages,
		     (m_imap->imessages_count + 1) * sizeof (*m));
	if (m == NULL)
	  {
	    message_destroy (pmsg, msg_imap);
	    monitor_unlock (mailbox->monitor);
	    return ENOMEM;
	  }
	m_imap->imessages = m;
	m_imap->imessages[m_imap->imessages_count] = msg_imap;
	m_imap->imessages_count++;
      }
      monitor_unlock (mailbox->monitor);

      msg_imap->message = *pmsg;
      msg_imap->m_imap = m_imap;
    }
  else
    free (msg_imap);
  return status;
}

/* Set all the message_t functions and parts.  */
static int
imap_get_message0 (msg_imap_t msg_imap, message_t *pmsg)
{
  int status = 0;
  message_t msg = NULL;
  mailbox_t mailbox = msg_imap->m_imap->mailbox;

  /* Create the message.  */
  {
    stream_t stream = NULL;
    if ((status = message_create (&msg, msg_imap)) != 0
        || (status = stream_create (&stream, mailbox->flags, msg)) != 0)
      {
        stream_destroy (&stream, msg);
        message_destroy (&msg, msg_imap);
        return status;
      }
    /* We want the buffering.  */
    stream_setbufsiz (stream, BUFSIZ);
    stream_set_read (stream, imap_message_read, msg);
    stream_set_fd (stream, imap_message_fd, msg);
    message_set_stream (msg, stream, msg_imap);
    message_set_size (msg, imap_message_size, msg_imap);
    message_set_lines (msg, imap_message_lines, msg_imap);
  }

  /* Create the header.  */
  {
    header_t header = NULL;
    stream_t stream = NULL;
    if ((status = header_create (&header, NULL, 0,  msg)) != 0
        || (status = stream_create (&stream, mailbox->flags, header)) != 0)
      {
        stream_destroy (&stream, header);
        header_destroy (&header, msg);
        message_destroy (&msg, msg_imap);
        return status;
      }
    stream_set_read (stream, imap_header_read, header);
    stream_set_fd (stream, imap_header_fd, header);
    header_set_stream (header, stream, msg);
    header_set_get_value (header, imap_header_get_value, msg);
    message_set_header (msg, header, msg_imap);
  }

  /* Create the attribute.  */
  {
    attribute_t attribute;
    status = attribute_create (&attribute, msg);
    if (status != 0)
      {
        message_destroy (&msg, msg_imap);
        return status;
      }
    attribute_set_get_flags (attribute, imap_attr_flags, msg);
    message_set_attribute (msg, attribute, msg_imap);
  }

  /* Create the body and its stream.  */
  {
    body_t body = NULL;
    stream_t stream = NULL;
    if ((status = body_create (&body, msg)) != 0
        || (status = stream_create (&stream, mailbox->flags, body)) != 0)
      {
        body_destroy (&body, msg);
        stream_destroy (&stream, body);
        message_destroy (&msg, msg_imap);
        return status;
      }
    /* We want the buffering.  */
    stream_setbufsiz (stream, BUFSIZ);
    stream_set_read (stream, imap_body_read, body);
    stream_set_fd (stream, imap_body_fd, body);
    body_set_size (body, imap_body_size, msg);
    body_set_lines (body, imap_body_lines, msg);
    body_set_stream (body, stream, msg);
    message_set_body (msg, body, msg_imap);
  }

  /* Set the envelope.  */
  {
    envelope_t envelope= NULL;
    status = envelope_create (&envelope, msg);
    if (status != 0)
      {
        message_destroy (&msg, msg_imap);
        return status;
      }
    envelope_set_sender (envelope, imap_envelope_sender, msg);
    envelope_set_date (envelope, imap_envelope_date, msg);
    message_set_envelope (msg, envelope, msg_imap);
  }

  /* Set the mime handling.  */
  message_set_is_multipart (msg, imap_is_multipart, msg_imap);
  message_set_get_num_parts (msg, imap_get_num_parts, msg_imap);
  message_set_get_part (msg, imap_get_part, msg_imap);

  /* Set the UIDL call on the message. */
  message_set_uid (msg, imap_message_uid, msg_imap);

  *pmsg = msg;
  return 0;
}

/* There is no explicit call to get the message count.  The count is send on
   a SELECT/EXAMINE command it is also sent async, meaning it will be piggy
   back on other server response as an untag "EXIST" response.  But we still
   send a SELECT.  */

static int
imap_messages_count (mailbox_t mailbox, size_t *pnum)
{
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* Are we already selected ? */
  if (m_imap == (f_imap->selected))
    {
      if (pnum)
	*pnum = m_imap->messages_count;
      return 0;
    }

  /*  Put the mailbox as selected.  */
  f_imap->selected = m_imap;

  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      status = imap_writeline (f_imap, "g%d SELECT %s\r\n",
			       f_imap->seq++, m_imap->name);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_SELECT;

    case IMAP_SELECT:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      if (status != 0)
	f_imap->selected = NULL;
      f_imap->state = IMAP_SELECT_ACK;

    case IMAP_SELECT_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);

    default:
      break;
    }

  if (pnum)
    *pnum = m_imap->messages_count;

  f_imap->state = IMAP_NO_STATE;
  return status;
}

/* We simulate by sending a notification for the total of msgno.  */
static int
imap_scan (mailbox_t mailbox, size_t msgno, size_t *pcount)
{
  int status;
  size_t i;
  size_t count = 0;

  /* Selected.  */
  status = imap_messages_count (mailbox, &count);
  if (pcount)
    *pcount = count;
  if (status != 0)
    return status;
  if (mailbox->observable == NULL)
    return 0;
  for (i = msgno; i <= *pcount; i++)
    if (observable_notify (mailbox->observable, MU_EVT_MESSAGE_ADD) != 0)
      break;
  return 0;
}

/* Send a NOOP and see if the count has change.  */
static int
imap_is_updated (mailbox_t mailbox)
{
  m_imap_t m_imap = mailbox->data;
  size_t oldcount = m_imap->messages_count;
  f_imap_t f_imap = m_imap->f_imap;
  int status = 0;

  /* Send a noop, and let imap piggy pack the information.  */
  switch (f_imap->state)
    {
    case IMAP_NO_STATE:
      /* Selected.  */
      status = imap_messages_count (mailbox, &oldcount);
      if (status != 0)
	return status;
      status = imap_writeline (f_imap, "g%d NOOP\r\n", f_imap->seq++);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_NOOP;

    case IMAP_NOOP:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      f_imap->state = IMAP_NOOP_ACK;

    case IMAP_NOOP_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (mailbox, MU_DEBUG_PROT, f_imap->buffer);

    default:
      break;
    }
  f_imap->state = IMAP_NO_STATE;
  return (oldcount == m_imap->messages_count);
}


static int
imap_expunge (mailbox_t mailbox)
{
  size_t i;
  int status;
  attribute_t attr;
  m_imap_t m_imap = mailbox->data;
  f_imap_t f_imap = m_imap->f_imap;

  /* Select first.  */
  status = imap_messages_count (mailbox, &i);
  if (status != 0)
    return status;

  for (i = 0; i < m_imap->imessages_count; ++i)
    {
      if (message_get_attribute (m_imap->imessages[i]->message, &attr) == 0
	  && attribute_is_deleted (attr))
	{
	  switch (f_imap->state)
	    {
	    case IMAP_NO_STATE:
	      status = imap_writeline (f_imap,
				       "g%d STORE %d +FLAGS (\\Delete)\r\n",
				       f_imap->seq++,
				       m_imap->imessages[i]->num);
	      CHECK_ERROR (f_imap, status);
	      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
	      f_imap->state = IMAP_STORE;

	    case IMAP_STORE:
	      /* Send DELETE.  */
	      status = imap_send (f_imap);
	      CHECK_EAGAIN (f_imap, status);
	      f_imap->state = IMAP_STORE_ACK;

	    case IMAP_STORE_ACK:
	      status = imap_parse (f_imap);
	      CHECK_EAGAIN (f_imap, status);
	      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
	      f_imap->state = IMAP_NO_STATE;

	    default:
	      /* fprintf (stderr, "imap_expunge: unknow state\n"); */
	      break;
	    } /* switch (state) */
        } /* message_get_attribute() */
    } /* for */

  /* Tell the server to delete the messages but without sending the
     EXPUNGE response.  We can do the calculations.  */
  status = mailbox_imap_close (mailbox);
  return status;
}

static int
imap_append_message (mailbox_t mailbox, message_t msg)
{
  (void)mailbox; (void)msg;
  return 0;
}

/* Message.  */
static int
imap_message_read (stream_t stream, char *buffer, size_t buflen,
		   off_t offset, size_t *plen)
{
  message_t msg = stream_get_owner (stream);
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;

  /* Select first.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      int status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      /* We strip the \r, but the offset/size on the imap server is with that
	 octet so add it in the offset, since it's the number of lines.  */
      if (msg_imap->part)
	{
	  char *section = section_name (msg_imap);
	  status = imap_writeline (f_imap,
				   "g%d FETCH %d BODY.PEEK[%s]<%d.%d>\r\n",
				   f_imap->seq++, msg_imap->num,
				   (section) ? section : "",
				   offset + msg_imap->message_lines, buflen);
	  if (section)
	    free (section);
	}
      else
	status = imap_writeline (f_imap,
				 "g%d FETCH %d BODY.PEEK[]<%d.%d>\r\n",
				 f_imap->seq++, msg_imap->num,
				 offset + msg_imap->message_lines, buflen);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  return message_operation (f_imap, msg_imap, IMAP_MESSAGE, buffer, buflen,
			    plen);
}

static int
imap_message_lines (message_t msg, size_t *plines)
{
  msg_imap_t msg_imap = message_get_owner (msg);
  if (plines && msg_imap)
    *plines = msg_imap->message_lines;
  return 0;
}

static int
imap_message_size (message_t msg, size_t *psize)
{
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;

  /* Select first.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      /* We strip the \r, but the offset/size on the imap server is with that
	 octet so add it in the offset, since it's the number of lines.  */
      status = imap_writeline (f_imap,
			       "g%d FETCH %d RFC822.SIZE\r\n",
			       f_imap->seq++, msg_imap->num);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  status = message_operation (f_imap, msg_imap, 0, 0, 0, 0);
  if (status == 0)
    {
      if (psize)
	*psize = msg_imap->message_size - msg_imap->message_lines;
    }
  return status;
}

static int
imap_message_uid (message_t msg, char *buffer, size_t buflen, size_t *pnwriten)
{
  (void)msg; (void)buffer; (void)buflen;
  if (pnwriten)
    *pnwriten = 0;
  return ENOSYS;
}

static int
imap_message_fd (stream_t stream, int * pfd)
{
  message_t msg = stream_get_owner (stream);
  msg_imap_t msg_imap = message_get_owner (msg);
  return imap_get_fd (msg_imap, pfd);
}

/* Mime.  */
static int
imap_is_multipart (message_t msg, int *ismulti)
{
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;

  /* Select first.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      if (msg_imap->num_parts || msg_imap->part)
	{
	  if (ismulti)
	    *ismulti = (msg_imap->num_parts > 1);
	  return 0;
	}
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      status = imap_writeline (f_imap,
			       "g%d FETCH %d BODY\r\n",
			       f_imap->seq++, msg_imap->num);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  status = message_operation (f_imap, msg_imap, 0, 0, 0, 0);
  if (status != 0)
    return status;
  if (ismulti)
    *ismulti = (msg_imap->num_parts > 1);
  return 0;
}

static int
imap_get_num_parts (message_t msg, size_t *nparts)
{
  msg_imap_t msg_imap = message_get_owner (msg);
  if (msg_imap)
    {
      if (msg_imap->num_parts == 0)
	{
	  int status = imap_is_multipart (msg, NULL);
	  if (status != 0)
	    return status;
	}
      if (nparts)
	*nparts = (msg_imap->num_parts == 0) ? 1 : msg_imap->num_parts;
    }
  return 0;
}

static int
imap_get_part (message_t msg, size_t partno, message_t *pmsg)
{
  msg_imap_t msg_imap = message_get_owner (msg);
  int status = 0;
  if (msg_imap->num_parts == 0)
    {
      status = imap_get_num_parts (msg, NULL);
      if (status != 0)
	return status;
    }

  if (partno <= msg_imap->num_parts)
    {
      if (msg_imap->parts[partno - 1]->message)
	{
	  if (pmsg)
	    *pmsg = msg_imap->parts[partno - 1]->message;
	}
      else
	{
	  message_t message;
	  status = imap_get_message0 (msg_imap->parts[partno - 1], &message);
	  if (status == 0)
	    {
	      header_t header;
	      message_get_header (message, &header);
	      header_set_get_value (header, NULL, message);
	      message_set_size (*pmsg, NULL, msg_imap->parts[partno - 1]);
	      msg_imap->parts[partno - 1]->message = message;
	      if (pmsg)
		*pmsg = message;
	    }
	}
    }
  else
    {
      if (pmsg)
	*pmsg = msg_imap->message;
    }
  return status;
}

/* Envelope.  */
static int
imap_envelope_sender (envelope_t envelope, char *buffer, size_t buflen,
		      size_t *plen)
{
  message_t msg = envelope_get_owner (envelope);
  header_t header;
  int status;

  message_get_header (msg, &header);
  status = imap_header_get_value (header, MU_HEADER_SENDER, buffer,
					  buflen, plen);
  if (status == EAGAIN)
    return status;
  else if (status != 0)
    status = imap_header_get_value (header, MU_HEADER_FROM, buffer,
					    buflen, plen);
  if (status == 0)
    {
      address_t address;
      if (address_create (&address, buffer) == 0)
	{
	  address_get_email (address, 1, buffer, buflen, plen);
	  address_destroy (&address);
	}
    }
  return status;
}

static int
imap_envelope_date (envelope_t envelope, char *buffer, size_t buflen,
		    size_t *plen)
{
  message_t msg = envelope_get_owner (envelope);
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;
  if (f_imap->state == IMAP_NO_STATE)
    {
      /* Select first.  */
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      status = imap_writeline (f_imap,
			       "g%d FETCH %d INTERNALDATE\r\n",
			       f_imap->seq++, msg_imap->num);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;
    }
  return message_operation (f_imap, msg_imap, 0, buffer, buflen, plen);
}

/* Attributes.  */
static int
imap_attr_flags (attribute_t attribute, int *pflags)
{
  (void)attribute; (void)pflags;
  return 0;
}

/* Header.  */
static int
imap_header_get_value (header_t header, const char *field, char * buffer,
		       size_t buflen, size_t *plen)
{
  message_t msg = header_get_owner (header);
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  int status;
  size_t len = 0;
  char *value;

  len = strlen (field) + buflen + 4;
  value = alloca (len);
  /*memset (value, '0', len); */

  if (f_imap->state == IMAP_NO_STATE)
    {
      /* Select first.  */
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      status = imap_writeline (f_imap,
			       "g%d FETCH %d BODY.PEEK[HEADER.FIELDS (%s)]<0.%d>\r\n",
			       f_imap->seq++, msg_imap->num, field, len);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }
  status = message_operation (f_imap, msg_imap, IMAP_HEADER_FIELD, value, len,
			      &len);
  if (status == 0)
    {
      char *colon;
      /* The field-matching is case-insensitive but otherwise exact.  In all
	 cases, the delimiting blank line between the header and the body is
	 always included.  */
      value[len - 1] = '\0';
      colon = strchr (value, ':');
      if (colon)
	{
	  colon++;
	  if (*colon == ' ')
	    colon++;
	}
      else
	colon = value;

      while (colon[strlen (colon) - 1] == '\n')
	colon[strlen (colon) - 1] = '\0';

      if (buffer && buflen)
	{
	  strncpy (buffer, colon, buflen);
	  colon[buflen - 1] = '\0';
	}
      len = strlen (colon);
      if (plen)
	*plen = len;
      if (len == 0)
	status = ENOENT;
    }
  return status;

}

static int
imap_header_read (stream_t stream, char *buffer, size_t buflen, off_t offset,
		  size_t *plen)
{
  header_t header = stream_get_owner (stream);
  message_t msg = header_get_owner (header);
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;

  /* Select first.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      int status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      /* We strip the \r, but the offset/size on the imap server is with that
	 octet so add it in the offset, since it's the number of lines.  */
      if (msg_imap->part)
	{
	  char *section = section_name (msg_imap);
	  status = imap_writeline (f_imap,
				   "g%d FETCH %d BODY.PEEK[%s.MIME]<%d.%d>\r\n",
				   f_imap->seq++, msg_imap->num,
				   (section) ? section : "",
				   offset + msg_imap->header_lines, buflen);
	  if (section)
	    free (section);
	}
      else
	status = imap_writeline (f_imap,
				 "g%d FETCH %d BODY.PEEK[HEADER]<%d.%d>\r\n",
				 f_imap->seq++, msg_imap->num,
				 offset + msg_imap->header_lines, buflen);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }
  return message_operation (f_imap, msg_imap, IMAP_HEADER, buffer, buflen,
			    plen);
}

static int
imap_header_fd (stream_t stream, int *pfd)
{
  header_t header = stream_get_owner (stream);
  message_t msg = header_get_owner (header);
  msg_imap_t msg_imap = message_get_owner (msg);
  return imap_get_fd (msg_imap, pfd);
}


/* Body.  */
static int
imap_body_size (body_t body, size_t *psize)
{
  message_t msg = body_get_owner (body);
  msg_imap_t msg_imap = message_get_owner (msg);
  if (psize && msg_imap)
    *psize = msg_imap->body_size;
  return 0;
}

static int
imap_body_lines (body_t body, size_t *plines)
{
  message_t msg = body_get_owner (body);
  msg_imap_t msg_imap = message_get_owner (msg);
  if (plines && msg_imap)
    *plines = msg_imap->body_lines;
  return 0;
}

static int
imap_body_read (stream_t stream, char *buffer, size_t buflen, off_t offset,
		size_t *plen)
{
  body_t body = stream_get_owner (stream);
  message_t msg = body_get_owner (body);
  msg_imap_t msg_imap = message_get_owner (msg);
  m_imap_t m_imap = msg_imap->m_imap;
  f_imap_t f_imap = m_imap->f_imap;
  char *oldbuf = NULL;
  char newbuf[2];
  int status = 0;

  /* This so F*$&#g annoying, a buffer len of 1 is a killer.
     If you have for example "\n", IMAP servers will transform
     this to "\r\n" and since you ask for only 1 sends '\r' only.
     '\r' will be stripped and the number of char read will be 0
     which means we're done.  So we guard to at least ask for 2 chars.  */
  if (buflen == 1)
    {
      oldbuf = buffer;
      buffer = newbuf;
      buflen = 2;
    }
  /* Select first.  */
  if (f_imap->state == IMAP_NO_STATE)
    {
      status = imap_messages_count (m_imap->mailbox, NULL);
      if (status != 0)
	return status;
      /* We strip the \r, but the offset/size on the imap server is with that
	 octet so add it in the offset, since it's the number of lines.  */
      if (msg_imap->part)
	{
	  char *section = section_name (msg_imap);
	  status = imap_writeline (f_imap,
				   "g%d FETCH %d BODY.PEEK[%s]<%d.%d>\r\n",
				   f_imap->seq++, msg_imap->num,
				   (section) ? section: "",
				   offset + msg_imap->body_lines, buflen);
	  if (section)
	    free (section);
	}
      else
	status = imap_writeline (f_imap,
				 "g%d FETCH %d BODY.PEEK[TEXT]<%d.%d>\r\n",
				 f_imap->seq++, msg_imap->num,
				 offset + msg_imap->body_lines, buflen);
      CHECK_ERROR (f_imap, status);
      MAILBOX_DEBUG0 (m_imap->mailbox, MU_DEBUG_PROT, f_imap->buffer);
      f_imap->state = IMAP_FETCH;

    }
  status = message_operation (f_imap, msg_imap, IMAP_BODY, buffer, buflen, plen);
  if (oldbuf)
    oldbuf[0] = buffer[0];
  return status;
}

static int
imap_body_fd (stream_t stream, int *pfd)
{
  body_t body = stream_get_owner (stream);
  message_t msg = body_get_owner (body);
  msg_imap_t msg_imap = message_get_owner (msg);
  return imap_get_fd (msg_imap, pfd);
}


static int
imap_get_fd (msg_imap_t msg_imap, int *pfd)
{
  if (   msg_imap
      && msg_imap->m_imap
      && msg_imap->m_imap->f_imap
      && msg_imap->m_imap->f_imap->folder)
    return stream_get_fd (msg_imap->m_imap->f_imap->folder->stream, pfd);
  return EINVAL;
}

static int
message_operation (f_imap_t f_imap, msg_imap_t msg_imap, enum imap_state type,
		   char *buffer, size_t buflen, size_t *plen)
{
  int status = 0;

  switch (f_imap->state)
    {
    case IMAP_FETCH:
      status = imap_send (f_imap);
      CHECK_EAGAIN (f_imap, status);
      /* Set the callback,  we want the results.  */
      f_imap->callback.buffer = buffer;
      f_imap->callback.buflen = buflen;
      f_imap->callback.total = 0;
      f_imap->callback.type = type;
      f_imap->callback.msg_imap = msg_imap;
      f_imap->state = IMAP_FETCH_ACK;

    case IMAP_FETCH_ACK:
      status = imap_parse (f_imap);
      CHECK_EAGAIN (f_imap, status);
      MAILBOX_DEBUG0 (f_imap->selected->mailbox, MU_DEBUG_PROT,
		      f_imap->buffer);

    default:
      break;
    }
  if (plen)
    *plen = f_imap->callback.total;
  /* Clear the callback.  */
  f_imap->callback.buffer = NULL;
  f_imap->callback.buflen = 0;
  f_imap->callback.total = 0;
  f_imap->callback.type = 0;
  f_imap->callback.msg_imap = NULL;
  f_imap->state = IMAP_NO_STATE;
  return status;
}