DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Untracked file

Line Code
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 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: NPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Netscape Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is 
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or 
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the NPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the NPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
 
#include "nsMsgAttachmentHandler.h"

#include "nsMsgCopy.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsMsgSend.h"
#include "nsMsgCompUtils.h"
#include "nsMsgEncoders.h"
#include "nsMsgI18N.h"
#include "nsURLFetcher.h"
#include "nsMimeTypes.h"
#include "nsIMsgStringService.h"
#include "nsMsgComposeStringBundle.h"
#include "nsMsgCompCID.h"
#include "nsXPIDLString.h"
#include "nsReadableUtils.h"
#include "nsIMsgMessageService.h"
#include "nsMsgUtils.h"
#include "nsMsgPrompts.h"
#include "nsTextFormatter.h"
#include "nsIPrompt.h"
#include "nsMsgSimulateError.h"
#include "nsITextToSubURI.h"
#include "nsEscape.h"
#include "nsIURL.h"
#include "nsNetCID.h"
#include "nsIStreamConverterService.h"
#include "nsIMimeStreamConverter.h"
#include "nsMsgMimeCID.h"
#include "nsNetUtil.h"


///////////////////////////////////////////////////////////////////////////
// Mac Specific Attachment Handling for AppleDouble Encoded Files
///////////////////////////////////////////////////////////////////////////
#if defined(XP_MAC) || defined(XP_MACOSX)

#define AD_WORKING_BUFF_SIZE                  8192


extern void         MacGetFileType(nsFileSpec *fs, PRBool *useDefault, char **type, char **encoding);

#include "nsIInternetConfigService.h"

#if defined(XP_MAC)
#include "MoreFilesExtras.h"
#else
#include "MoreFilesX.h"
#endif /* XP_MAC */

#endif /* XP_MAC */

//
// Class implementation...
//
nsMsgAttachmentHandler::nsMsgAttachmentHandler()
{
#if defined(DEBUG_ducarroz)
  printf("CREATE nsMsgAttachmentHandler: %x\n", this);
#endif
  mMHTMLPart = PR_FALSE;
  mPartUserOmissionOverride = PR_FALSE;
  mMainBody = PR_FALSE;

  m_charset = nsnull;
  m_override_type = nsnull;
  m_override_encoding = nsnull;
  m_desired_type = nsnull;
  m_description = nsnull;
  m_encoding = nsnull;
  m_real_name = nsnull;
  m_encoding = nsnull;
  m_content_id = nsnull;
  m_already_encoded_p = PR_FALSE;
  m_decrypted_p = PR_FALSE;
  
  // For analyzing the attachment file...
  m_file_analyzed = PR_FALSE;
  m_ctl_count = 0;
  m_null_count = 0;
  m_current_column = 0;
  m_max_column = 0;
  m_lines = 0;
  m_unprintable_count = 0;
  m_highbit_count = 0;

  // Mime encoder...
  m_encoder_data = nsnull;

  m_done = PR_FALSE;
  m_type = nsnull;
  m_type_param = nsnull;
  m_size = 0;

  mCompFields = nsnull;   // Message composition fields for the sender
  mFileSpec = nsnull;
  mURL = nsnull;
  mRequest = nsnull;

  m_x_mac_type = nsnull;
  m_x_mac_creator = nsnull;

#if defined(XP_MAC) || defined(XP_MACOSX)
  mAppleFileSpec = nsnull;
#endif

  mDeleteFile = PR_FALSE;
  m_uri = nsnull;
}

nsMsgAttachmentHandler::~nsMsgAttachmentHandler()
{
#if defined(DEBUG_ducarroz)
  printf("DISPOSE nsMsgAttachmentHandler: %x\n", this);
#endif
#if defined(XP_MAC) || defined(XP_MACOSX)
  if (mAppleFileSpec)
    delete mAppleFileSpec;
#endif

  if (mFileSpec && mDeleteFile)
    mFileSpec->Delete(PR_FALSE);

  delete mFileSpec;
  mFileSpec=nsnull;

  PR_Free(m_charset);
  PR_Free(m_type);
  PR_Free(m_type_param);
  PR_Free(m_content_id);
  PR_Free(m_desired_type);
  PR_Free(m_encoding);
  PR_Free(m_override_type);
  PR_Free(m_description);
  PR_Free(m_real_name);
  PR_Free(m_override_encoding);
  PR_Free(m_x_mac_type);
  PR_Free(m_x_mac_creator);
  PR_Free(m_uri);
}

void
nsMsgAttachmentHandler::AnalyzeDataChunk(const char *chunk, PRInt32 length)
{
  unsigned char *s = (unsigned char *) chunk;
  unsigned char *end = s + length;
  for (; s < end; s++)
  {
    if (*s > 126)
    {
      m_highbit_count++;
      m_unprintable_count++;
    }
    else if (*s < ' ' && *s != '\t' && *s != nsCRT::CR && *s != nsCRT::LF)
    {
      m_unprintable_count++;
      m_ctl_count++;
      if (*s == 0)
        m_null_count++;
    }

    if (*s == nsCRT::CR || *s == nsCRT::LF)
    {
      if (s+1 < end && s[0] == nsCRT::CR && s[1] == nsCRT::LF)
        s++;
      if (m_max_column < m_current_column)
        m_max_column = m_current_column;
      m_current_column = 0;
      m_lines++;
    }
    else
    {
      m_current_column++;
    }
  }
}

void
nsMsgAttachmentHandler::AnalyzeSnarfedFile(void)
{
  char chunk[256];
  PRInt32 numRead = 0;

  if (m_file_analyzed)
    return;

  if (mFileSpec)
  {
    m_size = mFileSpec->GetFileSize();
    nsInputFileStream fileHdl(*mFileSpec, PR_RDONLY, 0);
    if (fileHdl.is_open())
    {
      do
      {
        numRead = fileHdl.read(chunk, 256);
        if (numRead > 0)
          AnalyzeDataChunk(chunk, numRead);
      }
      while (numRead > 0);

      fileHdl.close();
      m_file_analyzed = PR_TRUE;
    }
  }
}

//
// Given a content-type and some info about the contents of the document,
// decide what encoding it should have.
//
int
nsMsgAttachmentHandler::PickEncoding(const char *charset, nsIMsgSend *mime_delivery_state)
{
  nsCOMPtr<nsIPrefBranch> pPrefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
  
  // use the boolean so we only have to test for uuencode vs base64 once
  PRBool needsB64 = PR_FALSE;
  PRBool forceB64 = PR_FALSE;
  
  if (m_already_encoded_p)
    goto DONE;
  
  AnalyzeSnarfedFile();

  /* Allow users to override our percentage-wise guess on whether
  the file is text or binary */
  if (pPrefBranch) 
    pPrefBranch->GetBoolPref ("mail.file_attach_binary", &forceB64);
  
  if (!mMainBody && (forceB64 || mime_type_requires_b64_p (m_type)))
  {
  /* If the content-type is "image/" or something else known to be binary,
  always use base64 (so that we don't get confused by newline
  conversions.)
     */
    needsB64 = PR_TRUE;
  }
  else
  {
  /* Otherwise, we need to pick an encoding based on the contents of
  the document.
     */
    
    PRBool encode_p;
    
    if (m_max_column > 900)
      encode_p = PR_TRUE;
    else if (UseQuotedPrintable() && m_unprintable_count)
      encode_p = PR_TRUE;
    
      else if (m_null_count)  /* If there are nulls, we must always encode,
        because sendmail will blow up. */
        encode_p = PR_TRUE;
      else
        encode_p = PR_FALSE;
      
        /* MIME requires a special case that these types never be encoded.
      */
      if (!PL_strncasecmp (m_type, "message", 7) ||
        !PL_strncasecmp (m_type, "multipart", 9))
      {
        encode_p = PR_FALSE;
        if (m_desired_type && !PL_strcasecmp (m_desired_type, TEXT_PLAIN))
        {
          PR_Free (m_desired_type);
          m_desired_type = 0;
        }
      }

      // If the Mail charset is multibyte, we force it to use Base64 for attachments.
      if ((!mMainBody && charset && nsMsgI18Nmultibyte_charset(charset)) &&
        ((PL_strcasecmp(m_type, TEXT_HTML) == 0) ||
        (PL_strcasecmp(m_type, TEXT_MDL) == 0) ||
        (PL_strcasecmp(m_type, TEXT_PLAIN) == 0) ||
        (PL_strcasecmp(m_type, TEXT_RICHTEXT) == 0) ||
        (PL_strcasecmp(m_type, TEXT_ENRICHED) == 0) ||
        (PL_strcasecmp(m_type, TEXT_VCARD) == 0) ||
        (PL_strcasecmp(m_type, APPLICATION_DIRECTORY) == 0) || /* text/x-vcard synonym */
        (PL_strcasecmp(m_type, TEXT_CSS) == 0) ||
        (PL_strcasecmp(m_type, TEXT_JSSS) == 0)))
      {
        needsB64 = PR_TRUE;
      }
      else if (charset && nsMsgI18Nstateful_charset(charset)) 
      {
        PR_FREEIF(m_encoding);
        m_encoding = PL_strdup (ENCODING_7BIT);
      }
      else if (encode_p &&
        m_unprintable_count > (m_size / 10))
        /* If the document contains more than 10% unprintable characters,
        then that seems like a good candidate for base64 instead of
        quoted-printable.
        */
        needsB64 = PR_TRUE;
      else if (encode_p) {
        PR_FREEIF(m_encoding);
        m_encoding = PL_strdup (ENCODING_QUOTED_PRINTABLE);
      }
      else if (m_highbit_count > 0) {
        PR_FREEIF(m_encoding);
        m_encoding = PL_strdup (ENCODING_8BIT);
      }
      else {
        PR_FREEIF(m_encoding);
        m_encoding = PL_strdup (ENCODING_7BIT);
      }
  }
  
  if (needsB64)
  {
    //
    // We might have to uuencode instead of base64 the binary data.
    //
    PR_FREEIF(m_encoding);
    if (UseUUEncode_p())
      m_encoding = PL_strdup (ENCODING_UUENCODE);
    else
      m_encoding = PL_strdup (ENCODING_BASE64);
  }
  
  /* Now that we've picked an encoding, initialize the filter.
  */
  NS_ASSERTION(!m_encoder_data, "not-null m_encoder_data");
  if (!PL_strcasecmp(m_encoding, ENCODING_BASE64))
  {
    m_encoder_data = MIME_B64EncoderInit(mime_encoder_output_fn,
      mime_delivery_state);
    if (!m_encoder_data) return NS_ERROR_OUT_OF_MEMORY;
  }
  else if (!PL_strcasecmp(m_encoding, ENCODING_UUENCODE))
  {
    char        *tailName = NULL;
    nsXPIDLCString turl;
    
    if (mURL)
    {
      mURL->GetSpec(turl);
      
      tailName = PL_strrchr(turl, '/');
      if (tailName) 
      {
        char * tmp = tailName;
        tailName = PL_strdup(tailName+1);
        PR_FREEIF(tmp);
      }
    }
    
    if (mURL && !tailName)
    {
      tailName = PL_strrchr(turl, '/');
      if (tailName) 
      {
        char * tmp = tailName;
        tailName = PL_strdup(tailName+1);
        PR_FREEIF(tmp);
      }
    }

    m_encoder_data = MIME_UUEncoderInit((char *)(tailName ? tailName : ""),
      mime_encoder_output_fn,
      mime_delivery_state);
    PR_FREEIF(tailName);
    if (!m_encoder_data) return NS_ERROR_OUT_OF_MEMORY;
  }
  else if (!PL_strcasecmp(m_encoding, ENCODING_QUOTED_PRINTABLE))
  {
    m_encoder_data = MIME_QPEncoderInit(mime_encoder_output_fn,
      mime_delivery_state);
    if (!m_encoder_data) return NS_ERROR_OUT_OF_MEMORY;
  }
  else
  {
    m_encoder_data = 0;
  }  
  
  /* Do some cleanup for documents with unknown content type.
    There are two issues: how they look to MIME users, and how they look to
    non-MIME users.
    
      If the user attaches a "README" file, which has unknown type because it
      has no extension, we still need to send it with no encoding, so that it
      is readable to non-MIME users.
      
        But if the user attaches some random binary file, then base64 encoding
        will have been chosen for it (above), and in this case, it won't be
        immediately readable by non-MIME users.  However, if we type it as
        text/plain instead of application/octet-stream, it will show up inline
        in a MIME viewer, which will probably be ugly, and may possibly have
        bad charset things happen as well.
        
          So, the heuristic we use is, if the type is unknown, then the type is
          set to application/octet-stream for data which needs base64 (binary data)
          and is set to text/plain for data which didn't need base64 (unencoded or
          lightly encoded data.)
  */
DONE:
  if (!m_type || !*m_type || !PL_strcasecmp(m_type, UNKNOWN_CONTENT_TYPE))
  {
    PR_FREEIF(m_type);
    if (m_already_encoded_p)
      m_type = PL_strdup (APPLICATION_OCTET_STREAM);
    else if (m_encoding &&
         (!PL_strcasecmp(m_encoding, ENCODING_BASE64) ||
         !PL_strcasecmp(m_encoding, ENCODING_UUENCODE)))
         m_type = PL_strdup (APPLICATION_OCTET_STREAM);
    else
      m_type = PL_strdup (TEXT_PLAIN);
  }
  return 0;
}

static nsresult
FetcherURLDoneCallback(nsresult aStatus, 
                       const char *aContentType,
                       const char *aCharset,
                       PRInt32 totalSize, 
                       const PRUnichar* aMsg, void *tagData)
{
  nsMsgAttachmentHandler *ma = (nsMsgAttachmentHandler *) tagData;
  NS_ASSERTION(ma != nsnull, "not-null mime attachment");

  if (ma != nsnull)
  {
    ma->m_size = totalSize;
    if (aContentType)
    {
#if defined(XP_MAC) || defined(XP_MACOSX)
      //Do not change the type if we are dealing with an apple double file
      if (!ma->mAppleFileSpec)
#endif
      {
        PR_FREEIF(ma->m_type);
        ma->m_type = PL_strdup(aContentType);
      }
    }

    if (aCharset)
    {
      PR_FREEIF(ma->m_charset);
      ma->m_charset = PL_strdup(aCharset);
    }

    return ma->UrlExit(aStatus, aMsg);
  }
  else
    return NS_OK;
}

nsresult 
nsMsgAttachmentHandler::SnarfMsgAttachment(nsMsgCompFields *compFields)
{
  nsresult rv = NS_ERROR_INVALID_ARG;
  nsCOMPtr <nsIMsgMessageService> messageService;

  if (PL_strcasestr(m_uri, "-message:"))
  {
    mFileSpec = nsMsgCreateTempFileSpec("nsmail.tmp");
    mDeleteFile = PR_TRUE;
    mCompFields = compFields;
    PR_FREEIF(m_type);
    m_type = PL_strdup(MESSAGE_RFC822);
    PR_FREEIF(m_override_type);
    m_override_type = PL_strdup(MESSAGE_RFC822);
    if (!mFileSpec) 
    {
      rv = NS_ERROR_FAILURE;
      goto done;
    }

    nsCOMPtr<nsILocalFile> localFile;
    nsCOMPtr<nsIOutputStream> outputStream;
    NS_FileSpecToIFile(mFileSpec, getter_AddRefs(localFile));
    rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), localFile, -1, 00600);
    if (NS_FAILED(rv) || !outputStream || CHECK_SIMULATED_ERROR(SIMULATED_SEND_ERROR_3))
    {
      if (m_mime_delivery_state)
      {
        nsCOMPtr<nsIMsgSendReport> sendReport;
        m_mime_delivery_state->GetSendReport(getter_AddRefs(sendReport));
        if (sendReport)
        {
          nsAutoString error_msg;
          nsAutoString path;
          nsMsgGetNativePathString(mFileSpec->GetNativePathCString(),path);
          nsMsgBuildErrorMessageByID(NS_MSG_UNABLE_TO_OPEN_TMP_FILE, error_msg, &path, nsnull);
          sendReport->SetMessage(nsIMsgSendReport::process_Current, error_msg.get(), PR_FALSE);
        }
      }
      rv =  NS_MSG_UNABLE_TO_OPEN_TMP_FILE;
      goto done;
    }
    mOutFile = do_QueryInterface(outputStream);
    
    nsCOMPtr<nsIURLFetcher> fetcher = do_CreateInstance(NS_URLFETCHER_CONTRACTID, &rv);
    if (NS_FAILED(rv) || !fetcher)
    {
      if (NS_SUCCEEDED(rv))
        rv =  NS_ERROR_UNEXPECTED;
      goto done;
    }

    rv = fetcher->Initialize(localFile, mOutFile, FetcherURLDoneCallback, this);
    rv = GetMessageServiceFromURI(m_uri, getter_AddRefs(messageService));
    if (NS_SUCCEEDED(rv) && messageService)
    {
      nsCAutoString uri(m_uri);
      uri.Append("?fetchCompleteMessage=true");
      nsCOMPtr<nsIStreamListener> strListener;
      fetcher->QueryInterface(NS_GET_IID(nsIStreamListener), getter_AddRefs(strListener));

      // initialize a new stream converter, that uses the strListener as its input
      // obtain the input stream listener from the new converter,
      // and pass the converter's input stream listener to DisplayMessage

      m_mime_parser = do_CreateInstance(NS_MAILNEWS_MIME_STREAM_CONVERTER_CONTRACTID, &rv);
      if (NS_FAILED(rv))
        goto done;

      // Set us as the output stream for HTML data from libmime...
      nsCOMPtr<nsIMimeStreamConverter> mimeConverter = do_QueryInterface(m_mime_parser);
      if (mimeConverter)
      {
        mimeConverter->SetMimeOutputType(nsMimeOutput::nsMimeMessageDecrypt);
        mimeConverter->SetForwardInline(PR_FALSE);
        mimeConverter->SetIdentity(nsnull);
        mimeConverter->SetOriginalMsgURI(nsnull);
      }

      nsCOMPtr<nsIStreamListener> convertedListener = do_QueryInterface(m_mime_parser, &rv);
      if (NS_FAILED(rv))
        goto done;

      nsCOMPtr<nsIURI> aURL;
      rv = messageService->GetUrlForUri(uri.get(), getter_AddRefs(aURL), nsnull);
      if (aURL)
        aURL->SetSpec(nsDependentCString(uri.get()));

      rv = NS_NewInputStreamChannel(getter_AddRefs(m_converter_channel), aURL, nsnull);
      if (NS_FAILED(rv))
        goto done;

      rv = m_mime_parser->AsyncConvertData(
		    NS_LITERAL_STRING("message/rfc822").get(),
		    NS_LITERAL_STRING("message/rfc822").get(),
		    strListener, m_converter_channel);
      if (NS_FAILED(rv))
        goto done;

      rv = messageService->DisplayMessage(uri.get(), convertedListener, nsnull, nsnull, nsnull, nsnull);
    }
  }
done:
  if (NS_FAILED(rv))
  {
      if (mOutFile)
      {
        mOutFile->Close();
        mOutFile = nsnull;
      }

      if (mFileSpec)
      {
        mFileSpec->Delete(PR_FALSE);
        delete mFileSpec;
        mFileSpec = nsnull;
      }
  }

  return rv;
}

#if defined(XP_MAC) || defined(XP_MACOSX)
PRBool nsMsgAttachmentHandler::HasResourceFork(FSSpec *fsSpec)
{
  FSRef fsRef;
  if (::FSpMakeFSRef(fsSpec, &fsRef) == noErr)
  {
    FSCatalogInfo catalogInfo;
    OSErr err = ::FSGetCatalogInfo(&fsRef, kFSCatInfoDataSizes + kFSCatInfoRsrcSizes, &catalogInfo, nsnull, nsnull, nsnull);
    return (err == noErr && catalogInfo.rsrcLogicalSize != 0);
  }
  return PR_FALSE;
}
#endif

nsresult
nsMsgAttachmentHandler::SnarfAttachment(nsMsgCompFields *compFields)
{
  nsresult      status = 0;
  nsXPIDLCString url_string;

  NS_ASSERTION (! m_done, "Already done");

  if (!mURL)
    return SnarfMsgAttachment(compFields);

  mCompFields = compFields;

  // First, get as file spec and create the stream for the
  // temp file where we will save this data
    mFileSpec = nsMsgCreateTempFileSpec("nsmail.tmp");
  if (! mFileSpec )
    return (NS_ERROR_FAILURE);
  mDeleteFile = PR_TRUE;

  nsCOMPtr<nsILocalFile> localFile;
  nsCOMPtr<nsIOutputStream> outputStream;
  NS_FileSpecToIFile(mFileSpec, getter_AddRefs(localFile));
  status = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), localFile, -1, 00600);
  if (NS_FAILED(status) || !outputStream || CHECK_SIMULATED_ERROR(SIMULATED_SEND_ERROR_3))
  {
    if (m_mime_delivery_state)
    {
      nsCOMPtr<nsIMsgSendReport> sendReport;
      m_mime_delivery_state->GetSendReport(getter_AddRefs(sendReport));
      if (sendReport)
      {
        nsAutoString error_msg;
        nsAutoString path;
        nsMsgGetNativePathString(mFileSpec->GetNativePathCString(),path);
        nsMsgBuildErrorMessageByID(NS_MSG_UNABLE_TO_OPEN_TMP_FILE, error_msg, &path, nsnull);
        sendReport->SetMessage(nsIMsgSendReport::process_Current, error_msg.get(), PR_FALSE);
      }
    }
    mFileSpec->Delete(PR_FALSE);
    delete mFileSpec;
    mFileSpec = nsnull;
    return NS_MSG_UNABLE_TO_OPEN_TMP_FILE; 
  }
  mOutFile = do_QueryInterface(outputStream);

  mURL->GetSpec(url_string);

#if defined(XP_MAC) || defined(XP_MACOSX)
  if ( !m_bogus_attachment && nsMsgIsLocalFile(url_string))
  {
    // convert the apple file to AppleDouble first, and then patch the
    // address in the url.
    char *src_filename = nsMsgGetLocalFileFromURL (url_string);
    if (!src_filename)
      return NS_ERROR_OUT_OF_MEMORY;

    // Unescape the name before making FSSpec
    nsCAutoString escapedFilename(src_filename);
    nsUnescape(escapedFilename.BeginWriting());

    //We need to retrieve the file type and creator...
    nsFileSpec scr_fileSpec(escapedFilename.get());
    FSSpec fsSpec;
#if defined(XP_MAC)
    fsSpec = scr_fileSpec.GetFSSpec();
#elif defined(XP_MACOSX)
    Boolean isDir;
    FSPathMakeFSSpec((UInt8 *)escapedFilename.get(), &fsSpec, &isDir);
#endif
    FInfo info;
    if (FSpGetFInfo (&fsSpec, &info) == noErr)
    {
      char filetype[32];
      PR_snprintf(filetype, sizeof(filetype), "%X", info.fdType);
      PR_FREEIF(m_x_mac_type);
      m_x_mac_type = PL_strdup(filetype);

      PR_snprintf(filetype, sizeof(filetype), "%X", info.fdCreator);
      PR_FREEIF(m_x_mac_creator);
      m_x_mac_creator = PL_strdup(filetype);
    }

    PRBool sendResourceFork = PR_TRUE;
    PRBool icGaveNeededInfo = PR_FALSE;
    nsCOMPtr<nsIInternetConfigService> icService (do_GetService(NS_INTERNETCONFIGSERVICE_CONTRACTID));
    if (icService)
    {
      PRInt32 icFlags;
      // be sure to look up by extension first (so pass in PR_TRUE). See Bug #229855
      nsresult rv = icService->GetFileMappingFlags(&fsSpec, PR_TRUE, &icFlags);
      if (NS_SUCCEEDED(rv) && icFlags != -1 && !(icFlags & nsIInternetConfigService::eIICMapFlag_NotOutgoingMask))
      {
        sendResourceFork = (icFlags & nsIInternetConfigService::eIICMapFlag_ResourceForkMask);

        if (sendResourceFork)
        {
          // before deciding to send the resource fork along the data fork, check if we have one,
          // else don't need to use apple double.
#if defined(XP_MAC) || defined(XP_MACOSX)
          sendResourceFork = HasResourceFork(&fsSpec);
#endif
        }
        
        icGaveNeededInfo = PR_TRUE;
      }
    }
    
    if (! icGaveNeededInfo)
    {
      // If InternetConfig cannot help us, then just try our best...
      // first check if we have a resource fork
      sendResourceFork = HasResourceFork(&fsSpec);

      // then, if we have a resource fork, check the filename extension, maybe we don't need the resource fork!
      if (sendResourceFork)
      {
        nsCOMPtr<nsIURL> fileUrl(do_CreateInstance(NS_STANDARDURL_CONTRACTID));
        if (fileUrl)
        {
          nsresult rv = fileUrl->SetSpec(url_string);
          if (NS_SUCCEEDED(rv))
          {
            nsCAutoString ext;
            rv = fileUrl->GetFileExtension(ext);
            if (NS_SUCCEEDED(rv) && !ext.IsEmpty())
            {
              sendResourceFork =
                 PL_strcasecmp(ext.get(), "TXT") &&
                 PL_strcasecmp(ext.get(), "JPG") &&
                 PL_strcasecmp(ext.get(), "GIF") &&
                 PL_strcasecmp(ext.get(), "TIF") &&
                 PL_strcasecmp(ext.get(), "HTM") &&
                 PL_strcasecmp(ext.get(), "HTML") &&
                 PL_strcasecmp(ext.get(), "ART") &&
                 PL_strcasecmp(ext.get(), "XUL") &&
                 PL_strcasecmp(ext.get(), "XML") &&
                 PL_strcasecmp(ext.get(), "CSS") &&
                 PL_strcasecmp(ext.get(), "JS");
            }
          }
        }
      }
    }

    // Only use appledouble if we aren't uuencoding.
    if( sendResourceFork && (! UseUUEncode_p()) )
    {
      char                *separator;
      nsInputFileStream   *myInputFile = new nsInputFileStream(scr_fileSpec);

      if ((!myInputFile) || (!myInputFile->is_open()))
        return NS_ERROR_OUT_OF_MEMORY;

      separator = mime_make_separator("ad");
      if (!separator)
      {
        delete myInputFile;
        PR_FREEIF(src_filename);
        return NS_ERROR_OUT_OF_MEMORY;
      }
            
      mAppleFileSpec = nsMsgCreateTempFileSpec("appledouble");
      if (!mAppleFileSpec) 
      {
        delete myInputFile;
        PR_FREEIF(separator);
        PR_FREEIF(src_filename);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      //
      // RICHIE_MAC - ok, here's the deal, we have a file that we need
      // to encode in appledouble encoding for the resource fork and put that
      // into the mAppleFileSpec location. Then, we need to patch the new file 
      // spec into the array and send this as part of the 2 part appledouble/mime
      // encoded mime part. 
      // 
      AppleDoubleEncodeObject     *obj = new (AppleDoubleEncodeObject);
      if (obj == NULL) 
      {
        delete mAppleFileSpec;
        PR_FREEIF(src_filename);
        PR_FREEIF(separator);
        return NS_ERROR_OUT_OF_MEMORY;
      }
   
      obj->fileStream = new nsIOFileStream(*mAppleFileSpec, (PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE));
      if ( (!obj->fileStream) || (!obj->fileStream->is_open()) )
      {
        delete myInputFile;
        PR_FREEIF(src_filename);
        PR_FREEIF(separator);
        delete obj;
        return NS_ERROR_OUT_OF_MEMORY;
      }

      PRInt32     bSize = AD_WORKING_BUFF_SIZE;

      char  *working_buff = nsnull;
      while (!working_buff && (bSize >= 512))
      {
        working_buff = (char *)PR_CALLOC(bSize);
        if (!working_buff)
          bSize /= 2;
      }

      if (!working_buff)
      {
        PR_FREEIF(src_filename);
        PR_FREEIF(separator);
        delete obj;
        return NS_ERROR_OUT_OF_MEMORY;
      }

      obj->buff = working_buff;
      obj->s_buff = bSize;  

      //
      //  Setup all the need information on the apple double encoder.
      //
      ap_encode_init(&(obj->ap_encode_obj), escapedFilename.get(), separator);

      PRInt32 count;

      status = noErr;
      m_size = 0;
      while (status == noErr)
      {      
        status = ap_encode_next(&(obj->ap_encode_obj), obj->buff, bSize, &count);
        if (status == noErr || status == errDone)
        {
          //
          // we got the encode data, so call the next stream to write it to the disk.
          //
          if (obj->fileStream->write(obj->buff, count) != count)
            status = NS_MSG_ERROR_WRITING_FILE;
        }
      } 
      
      delete myInputFile;  
      ap_encode_end(&(obj->ap_encode_obj), (status >= 0)); // if this is true, ok, false abort
      if (obj->fileStream)
        obj->fileStream->close();

      PR_FREEIF(obj->buff);               /* free the working buff.   */
      PR_FREEIF(obj);

      char *newURLSpec = nsMsgPlatformFileToURL(*mAppleFileSpec);

      if (!newURLSpec) 
      {
        PR_FREEIF(src_filename);
        PR_FREEIF(separator);
        return NS_ERROR_OUT_OF_MEMORY;
      }

      if (NS_FAILED(nsMsgNewURL(getter_AddRefs(mURL), newURLSpec)))
      {
        PR_FREEIF(src_filename);
        PR_FREEIF(separator);
        PR_FREEIF(newURLSpec);
        return NS_ERROR_OUT_OF_MEMORY;
      }
  
      PR_FREEIF(newURLSpec);
      
      // Now after conversion, also patch the types.
      char        tmp[128];
      PR_snprintf(tmp, sizeof(tmp), MULTIPART_APPLEDOUBLE ";\r\n boundary=\"%s\"", separator);
      PR_FREEIF(separator);
      PR_FREEIF (m_type);
      m_type = PL_strdup(tmp);
    }
    else
    {
      if ( sendResourceFork )
      {
        // The only time we want to send just the data fork of a two-fork
        // Mac file is if uuencoding has been requested.
        NS_ASSERTION(UseUUEncode_p(), "not UseUUEncode_p");

        // For now, just do the encoding, but in the old world we would ask the
        // user about doing this conversion
        printf("...we could ask the user about this conversion, but for now, nahh..\n");
      }

      PRBool    useDefault;
      char      *macType, *macEncoding;
      if (m_type == NULL || !PL_strcasecmp (m_type, TEXT_PLAIN))
      {
# define TEXT_TYPE  0x54455854  /* the characters 'T' 'E' 'X' 'T' */
# define text_TYPE  0x74657874  /* the characters 't' 'e' 'x' 't' */

        if (info.fdType != TEXT_TYPE && info.fdType != text_TYPE)
        {
          MacGetFileType(&scr_fileSpec, &useDefault, &macType, &macEncoding);
          PR_FREEIF(m_type);
          m_type = macType;
        }
      }
      // don't bother to set the types if we failed in getting the file info.
    }

    PR_FREEIF(src_filename);
  }
#endif /* XP_MAC */

  //
  // Ok, here we are, we need to fire the URL off and get the data
  // in the temp file
  //
  // Create a fetcher for the URL attachment...

  nsresult rv;
  nsCOMPtr<nsIURLFetcher> fetcher = do_CreateInstance(NS_URLFETCHER_CONTRACTID, &rv);
  if (NS_FAILED(rv) || !fetcher)
  {
    if (NS_SUCCEEDED(rv))
      return NS_ERROR_UNEXPECTED;
    else
      return rv;
  }

  return fetcher->FireURLRequest(mURL, localFile, mOutFile, FetcherURLDoneCallback, this);
}

nsresult
nsMsgAttachmentHandler::LoadDataFromFile(nsFileSpec& fSpec, nsString &sigData, PRBool charsetConversion)
{
  PRInt32       readSize;
  char          *readBuf;

  nsInputFileStream tempFile(fSpec);
  if (!tempFile.is_open())
    return NS_MSG_ERROR_WRITING_FILE;        
  
  readSize = fSpec.GetFileSize();
  readBuf = (char *)PR_Malloc(readSize + 1);
  if (!readBuf)
    return NS_ERROR_OUT_OF_MEMORY;
  memset(readBuf, 0, readSize + 1);

  readSize = tempFile.read(readBuf, readSize);
  tempFile.close();

  if (charsetConversion)
  {
    if (NS_FAILED(ConvertToUnicode(m_charset, readBuf, sigData)))
      sigData.AssignWithConversion(readBuf);
  }
  else
      sigData.AssignWithConversion(readBuf);

  PR_FREEIF(readBuf);
  return NS_OK;
}

nsresult
nsMsgAttachmentHandler::Abort()
{
  NS_ASSERTION(m_mime_delivery_state != nsnull, "not-null m_mime_delivery_state");

  if (m_done)
    return NS_OK;

  if (mRequest)
    return mRequest->Cancel(NS_ERROR_ABORT);
  else
    if (m_mime_delivery_state)
    {
      m_mime_delivery_state->SetStatus(NS_ERROR_ABORT);
      m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, NS_ERROR_ABORT, 0, nsnull);
    }

  return NS_OK;

}

nsresult
nsMsgAttachmentHandler::UrlExit(nsresult status, const PRUnichar* aMsg)
{
  NS_ASSERTION(m_mime_delivery_state != nsnull, "not-null m_mime_delivery_state");

  // Close the file, but don't delete the disk file (or the file spec.) 
  if (mOutFile)
  {
    mOutFile->Close();
    mOutFile = nsnull;
  }
  
  mRequest = nsnull;

  // First things first, we are now going to see if this is an HTML
  // Doc and if it is, we need to see if we can determine the charset 
  // for this part by sniffing the HTML file.
  // This is needed only when the charset is not set already.
  // (e.g. a charset may be specified in HTTP header)
  //
  if ( (m_type) &&  (*m_type) &&
       (!m_charset || !(*m_charset)) ) 
  {
    if (PL_strcasecmp(m_type, TEXT_HTML) == 0)
    {
      char *tmpCharset = (char *)nsMsgI18NParseMetaCharset(mFileSpec);
      if (tmpCharset[0] != '\0')
      {
        PR_FREEIF(m_charset);
        m_charset = PL_strdup(tmpCharset);
      }
    }
  }

  nsresult mimeDeliveryStatus;
  m_mime_delivery_state->GetStatus(&mimeDeliveryStatus);
  
  if (mimeDeliveryStatus == NS_ERROR_ABORT)
    status = NS_ERROR_ABORT;
 
  if (NS_FAILED(status) && status != NS_ERROR_ABORT && NS_SUCCEEDED(mimeDeliveryStatus))
  {
    // At this point, we should probably ask a question to the user 
    // if we should continue without this attachment.
    //
    PRBool            keepOnGoing = PR_TRUE;
    nsXPIDLCString    turl;
    nsXPIDLString     msg;
    PRUnichar         *printfString = nsnull;
    nsCOMPtr<nsIMsgStringService> composebundle (do_GetService(NS_MSG_COMPOSESTRINGSERVICE_CONTRACTID));

    nsMsgDeliverMode mode = nsIMsgSend::nsMsgDeliverNow;
    m_mime_delivery_state->GetDeliveryMode(&mode);
    if (mode == nsIMsgSend::nsMsgSaveAsDraft || mode == nsIMsgSend::nsMsgSaveAsTemplate)
      composebundle->GetStringByID(NS_MSG_FAILURE_ON_OBJ_EMBED_WHILE_SAVING, getter_Copies(msg));
    else
      composebundle->GetStringByID(NS_MSG_FAILURE_ON_OBJ_EMBED_WHILE_SENDING, getter_Copies(msg));
 
    if (m_real_name && *m_real_name)
      printfString = nsTextFormatter::smprintf(msg, m_real_name);
    else
    if (NS_SUCCEEDED(mURL->GetSpec(turl)) && (turl))
      {
        nsCAutoString unescapeUrl(turl);
        nsUnescape(unescapeUrl.BeginWriting());
        if (unescapeUrl.IsEmpty())
          printfString = nsTextFormatter::smprintf(msg, turl.get());
        else
          printfString = nsTextFormatter::smprintf(msg, unescapeUrl.get());
      }
    else
      printfString = nsTextFormatter::smprintf(msg, "?");

    nsCOMPtr<nsIPrompt> aPrompt;
    if (m_mime_delivery_state)
      m_mime_delivery_state->GetDefaultPrompt(getter_AddRefs(aPrompt));
    nsMsgAskBooleanQuestionByString(aPrompt, printfString, &keepOnGoing);
    PR_FREEIF(printfString);

    if (keepOnGoing)
    {
      status = 0;
      m_bogus_attachment = PR_TRUE; //That will cause this attachment to be ignored.
    }
    else
    {
      status = NS_ERROR_ABORT;
      m_mime_delivery_state->SetStatus(status);
      nsresult ignoreMe;
      m_mime_delivery_state->Fail(status, nsnull, &ignoreMe);
      m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, 0, nsnull);
      SetMimeDeliveryState(nsnull);
      return status;
    }
  }

  m_done = PR_TRUE;

  //
  // Ok, now that we have the file here on disk, we need to see if there was 
  // a need to do conversion to plain text...if so, the magic happens here,
  // otherwise, just move on to other attachments...
  //
  if (NS_SUCCEEDED(status) && m_type && PL_strcasecmp(m_type, TEXT_PLAIN) ) 
  {
    if (m_desired_type && !PL_strcasecmp(m_desired_type, TEXT_PLAIN) )
    {
      //
      // Conversion to plain text desired.
      //
      PRInt32       width = 72;
      nsCOMPtr<nsIPrefBranch> pPrefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID));
      if (pPrefBranch)
        pPrefBranch->GetIntPref("mailnews.wraplength", &width);
      // Let sanity reign!
      if (width == 0) 
        width = 72;
      else if (width < 10) 
        width = 10;
      else if (width > 30000) 
        width = 30000;

      //
      // Now use the converter service here to do the right 
      // thing and convert this data to plain text for us!
      //
      nsString      conData;

      if (NS_SUCCEEDED(LoadDataFromFile(*mFileSpec, conData, PR_TRUE)))
      {
        if (NS_SUCCEEDED(ConvertBufToPlainText(conData, UseFormatFlowed(m_charset))))
        {
          if (mDeleteFile)
          mFileSpec->Delete(PR_FALSE);

          nsOutputFileStream tempfile(*mFileSpec, PR_WRONLY | PR_CREATE_FILE, 00600);
          if (tempfile.is_open()) 
          {
            char    *tData = nsnull;
            if (NS_FAILED(ConvertFromUnicode(m_charset, conData, &tData)))
              tData = ToNewCString(conData);
            if (tData)
            {
              (void) tempfile.write(tData, strlen(tData));
              PR_FREEIF(tData);
            }
            tempfile.close();
          }
        }
      }

      PR_FREEIF(m_type);
      m_type = m_desired_type;
      m_desired_type = nsnull;
      PR_FREEIF(m_encoding);
      m_encoding = nsnull;
    }
  }

  PRUint32 pendingAttachmentCount = 0;
  m_mime_delivery_state->GetPendingAttachmentCount(&pendingAttachmentCount);
  NS_ASSERTION (pendingAttachmentCount > 0, "no more pending attachment");
  
  m_mime_delivery_state->SetPendingAttachmentCount(pendingAttachmentCount - 1);

  PRBool processAttachmentsSynchronously = PR_FALSE;
  m_mime_delivery_state->GetProcessAttachmentsSynchronously(&processAttachmentsSynchronously);
  if (NS_SUCCEEDED(status) && processAttachmentsSynchronously)
  {
    /* Find the next attachment which has not yet been loaded,
     if any, and start it going.
     */
    PRUint32 i;
    nsMsgAttachmentHandler *next = 0;
    nsMsgAttachmentHandler *attachments = nsnull;
    PRUint32 attachmentCount = 0;
    
    m_mime_delivery_state->GetAttachmentCount(&attachmentCount);
    if (attachmentCount)
      m_mime_delivery_state->GetAttachmentHandlers(&attachments);
      
    for (i = 0; i < attachmentCount; i++)
    {
      if (!attachments[i].m_done)
      {
        next = &attachments[i];
        //
        // rhp: We need to get a little more understanding to failed URL 
        // requests. So, at this point if most of next is NULL, then we
        // should just mark it fetched and move on! We probably ignored
        // this earlier on in the send process.
        //
        if ( (!next->mURL) && (!next->m_uri) )
        {
          attachments[i].m_done = PR_TRUE;
          m_mime_delivery_state->GetPendingAttachmentCount(&pendingAttachmentCount);
          m_mime_delivery_state->SetPendingAttachmentCount(pendingAttachmentCount - 1);
          next->mPartUserOmissionOverride = PR_TRUE;
          next = nsnull;
          continue;
        }

        break;
      }
    }

    if (next)
    {
      int status = next->SnarfAttachment(mCompFields);
      if (NS_FAILED(status))
      {
        nsresult ignoreMe;
        m_mime_delivery_state->Fail(status, nsnull, &ignoreMe);
        m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, 0, nsnull);
        SetMimeDeliveryState(nsnull);
        return NS_ERROR_UNEXPECTED;
      }
    }
  }

  m_mime_delivery_state->GetPendingAttachmentCount(&pendingAttachmentCount);
  if (pendingAttachmentCount == 0)
  {
    // If this is the last attachment, then either complete the
    // delivery (if successful) or report the error by calling
    // the exit routine and terminating the delivery.
    if (NS_FAILED(status))
    {
      nsresult ignoreMe;
      m_mime_delivery_state->Fail(status, aMsg, &ignoreMe);
      m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, aMsg, nsnull);
      SetMimeDeliveryState(nsnull);
      return NS_ERROR_UNEXPECTED;
    }
    else
    {
      status = m_mime_delivery_state->GatherMimeAttachments ();
      if (NS_FAILED(status))
      {
        nsresult ignoreMe;
        m_mime_delivery_state->Fail(status, aMsg, &ignoreMe);
        m_mime_delivery_state->NotifyListenerOnStopSending(nsnull, status, aMsg, nsnull);
        SetMimeDeliveryState(nsnull);
        return NS_ERROR_UNEXPECTED;
      }
    }
  }
  else
  {
    // If this is not the last attachment, but it got an error,
    // then report that error and continue 
    if (NS_FAILED(status))
    {
      nsresult ignoreMe;
      m_mime_delivery_state->Fail(status, aMsg, &ignoreMe);
    }
  }

  SetMimeDeliveryState(nsnull);
  return NS_OK;
}

PRBool 
nsMsgAttachmentHandler::UseUUEncode_p(void)
{
  if (mCompFields)
    return mCompFields->GetUuEncodeAttachments();
  else
    return PR_FALSE;
}

nsresult
nsMsgAttachmentHandler::GetMimeDeliveryState(nsIMsgSend** _retval)
{
  NS_ENSURE_ARG(_retval);
  *_retval = m_mime_delivery_state;
  NS_IF_ADDREF(*_retval);
  return NS_OK;
}

nsresult
nsMsgAttachmentHandler::SetMimeDeliveryState(nsIMsgSend* mime_delivery_state)
{
  /*
    Because setting m_mime_delivery_state to null could destroy ourself as
    m_mime_delivery_state it's our parent, we need to protect ourself against
    that!

    This extra comptr is necessary,
    see bug http://bugzilla.mozilla.org/show_bug.cgi?id=78967
  */
  nsCOMPtr<nsIMsgSend> temp = m_mime_delivery_state; /* Should lock our parent until the end of the function */
  m_mime_delivery_state = mime_delivery_state;
  return NS_OK;
}