summaryrefslogtreecommitdiffstats
path: root/mailnews/mime/src/nsStreamConverter.cpp
blob: 0d17814984b8c2f1cfb87f212dada9c2e1fe955b (plain)
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsCOMPtr.h"
#include <stdio.h>
#include "mimecom.h"
#include "modmimee.h"
#include "nscore.h"
#include "nsStreamConverter.h"
#include "prmem.h"
#include "prprf.h"
#include "prlog.h"
#include "plstr.h"
#include "mimemoz2.h"
#include "nsMimeTypes.h"
#include "nsIComponentManager.h"
#include "nsIURL.h"
#include "nsStringGlue.h"
#include "nsUnicharUtils.h"
#include "nsIServiceManager.h"
#include "nsMemory.h"
#include "nsIPipe.h"
#include "nsMimeStringResources.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsNetUtil.h"
#include "nsIMsgQuote.h"
#include "nsIScriptSecurityManager.h"
#include "nsNetUtil.h"
#include "mozITXTToHTMLConv.h"
#include "nsIMsgMailNewsUrl.h"
#include "nsIMsgWindow.h"
#include "nsICategoryManager.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIAsyncInputStream.h"
#include "nsIAsyncOutputStream.h"
#include "nsMsgUtils.h"
#include "mozilla/ArrayUtils.h"

#define PREF_MAIL_DISPLAY_GLYPH "mail.display_glyph"
#define PREF_MAIL_DISPLAY_STRUCT "mail.display_struct"

////////////////////////////////////////////////////////////////
// Bridge routines for new stream converter XP-COM interface
////////////////////////////////////////////////////////////////

extern "C" void  *
mime_bridge_create_draft_stream(nsIMimeEmitter      *newEmitter,
                                nsStreamConverter   *newPluginObj2,
                                nsIURI              *uri,
                                nsMimeOutputType    format_out);

extern "C" void  *
bridge_create_stream(nsIMimeEmitter      *newEmitter,
                     nsStreamConverter   *newPluginObj2,
                     nsIURI              *uri,
                     nsMimeOutputType    format_out,
                     uint32_t            whattodo,
                     nsIChannel          *aChannel)
{
  if  ( (format_out == nsMimeOutput::nsMimeMessageDraftOrTemplate) ||
        (format_out == nsMimeOutput::nsMimeMessageEditorTemplate) )
    return mime_bridge_create_draft_stream(newEmitter, newPluginObj2, uri, format_out);
  else
    return mime_bridge_create_display_stream(newEmitter, newPluginObj2, uri, format_out, whattodo,
                                             aChannel);
}

void
bridge_destroy_stream(void *newStream)
{
  nsMIMESession     *stream = (nsMIMESession *)newStream;
  if (!stream)
    return;

  PR_FREEIF(stream);
}

void
bridge_set_output_type(void *bridgeStream, nsMimeOutputType aType)
{
  nsMIMESession *session = (nsMIMESession *)bridgeStream;

  if (session)
  {
    // BAD ASSUMPTION!!!! NEED TO CHECK aType
    mime_stream_data *msd = (mime_stream_data *)session->data_object;
    if (msd)
      msd->format_out = aType;     // output format type
  }
}

nsresult
bridge_new_new_uri(void *bridgeStream, nsIURI *aURI, int32_t aOutputType)
{
  nsMIMESession *session = (nsMIMESession *)bridgeStream;
  const char    **fixup_pointer = nullptr;

  if (session)
  {
    if (session->data_object)
    {
      bool     *override_charset = nullptr;
      char    **default_charset = nullptr;
      char    **url_name = nullptr;

      if  ( (aOutputType == nsMimeOutput::nsMimeMessageDraftOrTemplate) ||
            (aOutputType == nsMimeOutput::nsMimeMessageEditorTemplate) )
      {
        mime_draft_data *mdd = (mime_draft_data *)session->data_object;
        if (mdd->options)
        {
          default_charset = &(mdd->options->default_charset);
          override_charset = &(mdd->options->override_charset);
          url_name = &(mdd->url_name);
        }
      }
      else
      {
        mime_stream_data *msd = (mime_stream_data *)session->data_object;

        if (msd->options)
        {
          default_charset = &(msd->options->default_charset);
          override_charset = &(msd->options->override_charset);
          url_name = &(msd->url_name);
          fixup_pointer = &(msd->options->url);
        }
      }

      if ( (default_charset) && (override_charset) && (url_name) )
      {
        //
        // set the default charset to be the folder charset if we have one associated with
        // this url...
        nsCOMPtr<nsIMsgI18NUrl> i18nUrl (do_QueryInterface(aURI));
        if (i18nUrl)
        {
          nsCString charset;

          // check to see if we have a charset override...and if we do, set that field appropriately too...
          nsresult rv = i18nUrl->GetCharsetOverRide(getter_Copies(charset));
          if (NS_SUCCEEDED(rv) && !charset.IsEmpty() ) {
            *override_charset = true;
            *default_charset = ToNewCString(charset);
          }
          else
          {
            i18nUrl->GetFolderCharset(getter_Copies(charset));
            if (!charset.IsEmpty())
              *default_charset = ToNewCString(charset);
          }

          // if there is no manual override and a folder charset exists
          // then check if we have a folder level override
          if (!(*override_charset) && *default_charset && **default_charset)
          {
            bool folderCharsetOverride;
            rv = i18nUrl->GetFolderCharsetOverride(&folderCharsetOverride);
            if (NS_SUCCEEDED(rv) && folderCharsetOverride)
              *override_charset = true;

            // notify the default to msgWindow (for the menu check mark)
            // do not set the default in case of nsMimeMessageDraftOrTemplate
            // or nsMimeMessageEditorTemplate because it is already set
            // when the message is displayed and doing it again may overwrite
            // the correct MIME charset parsed from the message header
            if (aOutputType != nsMimeOutput::nsMimeMessageDraftOrTemplate &&
                aOutputType != nsMimeOutput::nsMimeMessageEditorTemplate)
            {
              nsCOMPtr<nsIMsgMailNewsUrl> msgurl (do_QueryInterface(aURI));
              if (msgurl)
              {
                nsCOMPtr<nsIMsgWindow> msgWindow;
                msgurl->GetMsgWindow(getter_AddRefs(msgWindow));
                if (msgWindow)
                {
                  msgWindow->SetMailCharacterSet(nsDependentCString(*default_charset));
                  msgWindow->SetCharsetOverride(*override_charset);
                }
              }
            }

            // if the pref says always override and no manual override then set the folder charset to override
            if (!*override_charset) {
              nsCOMPtr<nsIPrefBranch> pPrefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
              if (pPrefBranch)
              {
                bool    force_override;
                rv = pPrefBranch->GetBoolPref("mailnews.force_charset_override", &force_override);
                if (NS_SUCCEEDED(rv) && force_override)
                {
                  *override_charset = true;
                }
              }
            }
          }
        }
        nsAutoCString urlString;
        if (NS_SUCCEEDED(aURI->GetSpec(urlString)))
        {
          if (!urlString.IsEmpty())
          {
            NS_Free(*url_name);
            *url_name = ToNewCString(urlString);
            if (!(*url_name))
              return NS_ERROR_OUT_OF_MEMORY;

            // rhp: Ugh, this is ugly...but it works.
            if (fixup_pointer)
              *fixup_pointer = (const char *)*url_name;
          }
        }
      }
    }
  }

  return NS_OK;
}

static int
mime_headers_callback ( void *closure, MimeHeaders *headers )
{
  // We get away with this because this doesn't get called on draft operations.
  mime_stream_data *msd = (mime_stream_data *)closure;

  NS_ASSERTION(msd && headers, "null mime stream data or headers");
  if ( !msd || ! headers )
    return 0;

  NS_ASSERTION(!msd->headers, "non-null mime stream data headers");
  msd->headers = MimeHeaders_copy ( headers );
  return 0;
}

nsresult
bridge_set_mime_stream_converter_listener(void *bridgeStream, nsIMimeStreamConverterListener* listener,
                                          nsMimeOutputType aOutputType)
{
  nsMIMESession *session = (nsMIMESession *)bridgeStream;

  if ( (session) && (session->data_object) )
  {
    if  ( (aOutputType == nsMimeOutput::nsMimeMessageDraftOrTemplate) ||
          (aOutputType == nsMimeOutput::nsMimeMessageEditorTemplate) )
    {
      mime_draft_data *mdd = (mime_draft_data *)session->data_object;
      if (mdd->options)
      {
        if (listener)
        {
          mdd->options->caller_need_root_headers = true;
          mdd->options->decompose_headers_info_fn = mime_headers_callback;
        }
        else
        {
          mdd->options->caller_need_root_headers = false;
          mdd->options->decompose_headers_info_fn = nullptr;
        }
      }
    }
    else
    {
      mime_stream_data *msd = (mime_stream_data *)session->data_object;

      if (msd->options)
      {
        if (listener)
        {
          msd->options->caller_need_root_headers = true;
          msd->options->decompose_headers_info_fn = mime_headers_callback;
        }
        else
        {
          msd->options->caller_need_root_headers = false;
          msd->options->decompose_headers_info_fn = nullptr;
        }
      }
    }
  }

  return NS_OK;
}

// find a query element in a url and return a pointer to its data
// (query must be in the form "query=")
static const char *
FindQueryElementData(const char * aUrl, const char * aQuery)
{
  if (aUrl && aQuery)
  {
    size_t queryLen = 0; // we don't call strlen until we need to
    aUrl = PL_strcasestr(aUrl, aQuery);
    while (aUrl)
    {
      if (!queryLen)
        queryLen = strlen(aQuery);
      if (*(aUrl-1) == '&' || *(aUrl-1) == '?')
        return aUrl + queryLen;
      aUrl = PL_strcasestr(aUrl + queryLen, aQuery);
    }
  }
  return nullptr;
}

// case-sensitive test for string prefixing. If |string| is prefixed
// by |prefix| then a pointer to the next character in |string| following
// the prefix is returned. If it is not a prefix then |nullptr| is returned.
static const char *
SkipPrefix(const char *aString, const char *aPrefix)
{
  while (*aPrefix)
    if (*aPrefix++ != *aString++)
       return nullptr;
  return aString;
}

//
// Utility routines needed by this interface
//
nsresult
nsStreamConverter::DetermineOutputFormat(const char *aUrl, nsMimeOutputType *aNewType)
{
  // sanity checking
  NS_ENSURE_ARG_POINTER(aNewType);
  if (!aUrl || !*aUrl)
  {
    // default to html for the entire document
    *aNewType = nsMimeOutput::nsMimeMessageQuoting;
    mOutputFormat = "text/html";
    return NS_OK;
  }

  // shorten the url that we test for the query strings by skipping directly
  // to the part where the query strings begin.
  const char *queryPart = PL_strchr(aUrl, '?');

  // First, did someone pass in a desired output format. They will be able to
  // pass in any content type (i.e. image/gif, text/html, etc...but the "/" will
  // have to be represented via the "%2F" value
  const char *format = FindQueryElementData(queryPart, "outformat=");
  if (format)
  {
    //NOTE: I've done a file contents search of every file (*.*) in the mozilla
    // directory tree and there is not a single location where the string "outformat"
    // is added to any URL. It appears that this code has been orphaned off by a change
    // elsewhere and is no longer required. It will be removed in the future unless
    // someone complains.
    MOZ_ASSERT(false, "Is this code actually being used?");

    while (*format == ' ')
      ++format;

    if (*format)
    {
      mOverrideFormat = "raw";

      // set mOutputFormat to the supplied format, ensure that we replace any
      // %2F strings with the slash character
      const char *nextField = PL_strpbrk(format, "&; ");
      mOutputFormat.Assign(format, nextField ? nextField - format : -1);
      MsgReplaceSubstring(mOutputFormat, "%2F", "/");
      MsgReplaceSubstring(mOutputFormat, "%2f", "/");

      // Don't muck with this data!
      *aNewType = nsMimeOutput::nsMimeMessageRaw;
      return NS_OK;
    }
  }

  // is this is a part that should just come out raw
  const char *part = FindQueryElementData(queryPart, "part=");
  if (part && !mToType.Equals("application/vnd.mozilla.xul+xml"))
  {
    // default for parts
    mOutputFormat = "raw";
    *aNewType = nsMimeOutput::nsMimeMessageRaw;

    // if we are being asked to fetch a part....it should have a
    // content type appended to it...if it does, we want to remember
    // that as mOutputFormat
    const char * typeField = FindQueryElementData(queryPart, "type=");
    if (typeField && !strncmp(typeField, "application/x-message-display", sizeof("application/x-message-display") - 1))
    {
      const char *secondTypeField = FindQueryElementData(typeField, "type=");
      if (secondTypeField)
        typeField = secondTypeField;
    }
    if (typeField)
    {
      // store the real content type...mOutputFormat gets deleted later on...
      // and make sure we only get our own value.
      char *nextField = PL_strchr(typeField, '&');
      mRealContentType.Assign(typeField, nextField ? nextField - typeField : -1);
      if (mRealContentType.Equals("message/rfc822"))
      {
        mRealContentType = "application/x-message-display";
        mOutputFormat = "text/html";
        *aNewType = nsMimeOutput::nsMimeMessageBodyDisplay;
      }
      else if (mRealContentType.Equals("application/x-message-display"))
      {
        mRealContentType = "";
        mOutputFormat = "text/html";
        *aNewType = nsMimeOutput::nsMimeMessageBodyDisplay;
      }
    }

    return NS_OK;
  }

  const char *emitter = FindQueryElementData(queryPart, "emitter=");
  if (emitter)
  {
    const char *remainder = SkipPrefix(emitter, "js");
    if (remainder && (!*remainder || *remainder == '&'))
      mOverrideFormat = "application/x-js-mime-message";
  }

  // if using the header query
  const char *header = FindQueryElementData(queryPart, "header=");
  if (header)
  {
    struct HeaderType {
      const char * headerType;
      const char * outputFormat;
      nsMimeOutputType mimeOutputType;
    };

    // place most commonly used options at the top
    static const struct HeaderType rgTypes[] =
    {
      { "filter",    "text/html",  nsMimeOutput::nsMimeMessageFilterSniffer },
      { "quotebody", "text/html",  nsMimeOutput::nsMimeMessageBodyQuoting },
      { "print",     "text/html",  nsMimeOutput::nsMimeMessagePrintOutput },
      { "only",      "text/xml",   nsMimeOutput::nsMimeMessageHeaderDisplay },
      { "none",      "text/html",  nsMimeOutput::nsMimeMessageBodyDisplay },
      { "quote",     "text/html",  nsMimeOutput::nsMimeMessageQuoting },
      { "saveas",    "text/html",  nsMimeOutput::nsMimeMessageSaveAs },
      { "src",       "text/plain", nsMimeOutput::nsMimeMessageSource },
      { "attach",    "raw",        nsMimeOutput::nsMimeMessageAttach }
    };

    // find the requested header in table, ensure that we don't match on a prefix
    // by checking that the following character is either null or the next query element
    const char * remainder;
    for (uint32_t n = 0; n < MOZ_ARRAY_LENGTH(rgTypes); ++n)
    {
      remainder = SkipPrefix(header, rgTypes[n].headerType);
      if (remainder && (*remainder == '\0' || *remainder == '&'))
      {
        mOutputFormat = rgTypes[n].outputFormat;
        *aNewType = rgTypes[n].mimeOutputType;
        return NS_OK;
      }
    }
  }

  // default to html for just the body
  mOutputFormat = "text/html";
  *aNewType = nsMimeOutput::nsMimeMessageBodyDisplay;

  return NS_OK;
}

nsresult
nsStreamConverter::InternalCleanup(void)
{
  if (mBridgeStream)
  {
    bridge_destroy_stream(mBridgeStream);
    mBridgeStream = nullptr;
  }

  return NS_OK;
}

/*
 * Inherited methods for nsMimeConverter
 */
nsStreamConverter::nsStreamConverter()
{
  // Init member variables...
  mWrapperOutput = false;
  mBridgeStream = nullptr;
  mOutputFormat = "text/html";
  mAlreadyKnowOutputType = false;
  mForwardInline = false;
  mForwardInlineFilter = false;
  mOverrideComposeFormat = false;

  mPendingRequest = nullptr;
  mPendingContext = nullptr;
}

nsStreamConverter::~nsStreamConverter()
{
  InternalCleanup();
}

NS_IMPL_ISUPPORTS(nsStreamConverter, nsIStreamListener, nsIRequestObserver,
  nsIStreamConverter, nsIMimeStreamConverter)

///////////////////////////////////////////////////////////////
// nsStreamConverter definitions....
///////////////////////////////////////////////////////////////

NS_IMETHODIMP nsStreamConverter::Init(nsIURI *aURI, nsIStreamListener * aOutListener, nsIChannel *aChannel)
{
  NS_ENSURE_ARG_POINTER(aURI);

  nsresult rv = NS_OK;
  mOutListener = aOutListener;

  // mscott --> we need to look at the url and figure out what the correct output type is...
  nsMimeOutputType newType = mOutputType;
  if (!mAlreadyKnowOutputType)
  {
    nsAutoCString urlSpec;
    rv = aURI->GetSpec(urlSpec);
    DetermineOutputFormat(urlSpec.get(), &newType);
    mAlreadyKnowOutputType = true;
    mOutputType = newType;
  }

  switch (newType)
  {
    case nsMimeOutput::nsMimeMessageSplitDisplay:    // the wrapper HTML output to produce the split header/body display
      mWrapperOutput = true;
      mOutputFormat = "text/html";
      break;
    case nsMimeOutput::nsMimeMessageHeaderDisplay:   // the split header/body display
      mOutputFormat = "text/xml";
      break;
    case nsMimeOutput::nsMimeMessageBodyDisplay:   // the split header/body display
      mOutputFormat = "text/html";
      break;

    case nsMimeOutput::nsMimeMessageQuoting:      // all HTML quoted output
    case nsMimeOutput::nsMimeMessageSaveAs:       // Save as operation
    case nsMimeOutput::nsMimeMessageBodyQuoting:  // only HTML body quoted output
    case nsMimeOutput::nsMimeMessagePrintOutput:  // all Printing output
      mOutputFormat = "text/html";
      break;

    case nsMimeOutput::nsMimeMessageAttach:
    case nsMimeOutput::nsMimeMessageDecrypt:
    case nsMimeOutput::nsMimeMessageRaw:              // the raw RFC822 data and attachments
      mOutputFormat = "raw";
      break;

    case nsMimeOutput::nsMimeMessageSource:      // the raw RFC822 data (view source) and attachments
      mOutputFormat = "text/plain";
      mOverrideFormat = "raw";
      break;

    case nsMimeOutput::nsMimeMessageDraftOrTemplate:       // Loading drafts & templates
      mOutputFormat = "message/draft";
      break;

    case nsMimeOutput::nsMimeMessageEditorTemplate:       // Loading templates into editor
      mOutputFormat = "text/html";
      break;

    case nsMimeOutput::nsMimeMessageFilterSniffer: // output all displayable part as raw
      mOutputFormat = "text/html";
      break;

    default:
      NS_ERROR("this means I made a mistake in my assumptions");
  }


  // the following output channel stream is used to fake the content type for people who later
  // call into us..
  nsCString contentTypeToUse;
  GetContentType(getter_Copies(contentTypeToUse));
  // mscott --> my theory is that we don't need this fake outgoing channel. Let's use the
  // original channel and just set our content type ontop of the original channel...

  aChannel->SetContentType(contentTypeToUse);

  //rv = NS_NewInputStreamChannel(getter_AddRefs(mOutgoingChannel), aURI, nullptr, contentTypeToUse, -1);
  //if (NS_FAILED(rv))
  //    return rv;

  // Set system principal for this document, which will be dynamically generated

  // We will first find an appropriate emitter in the repository that supports
  // the requested output format...note, the special exceptions are nsMimeMessageDraftOrTemplate
  // or nsMimeMessageEditorTemplate where we don't need any emitters
  //

  if ( (newType != nsMimeOutput::nsMimeMessageDraftOrTemplate) &&
    (newType != nsMimeOutput::nsMimeMessageEditorTemplate) )
  {
    nsAutoCString categoryName ("@mozilla.org/messenger/mimeemitter;1?type=");
    if (!mOverrideFormat.IsEmpty())
      categoryName += mOverrideFormat;
    else
      categoryName += mOutputFormat;

    nsCOMPtr<nsICategoryManager> catman = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
    if (NS_SUCCEEDED(rv))
    {
      nsCString contractID;
      catman->GetCategoryEntry("mime-emitter", categoryName.get(), getter_Copies(contractID));
      if (!contractID.IsEmpty())
        categoryName = contractID;
    }

    mEmitter = do_CreateInstance(categoryName.get(), &rv);

    if ((NS_FAILED(rv)) || (!mEmitter))
    {
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  // initialize our emitter
  if (mEmitter)
  {
    // Now we want to create a pipe which we'll use for converting the data.
    nsCOMPtr<nsIPipe> pipe = do_CreateInstance("@mozilla.org/pipe;1");
    rv = pipe->Init(true, true, 4096, 8);
    NS_ENSURE_SUCCESS(rv, rv);

    // These always succeed because the pipe is initialized above.
    MOZ_ALWAYS_SUCCEEDS(pipe->GetInputStream(getter_AddRefs(mInputStream)));
    MOZ_ALWAYS_SUCCEEDS(pipe->GetOutputStream(getter_AddRefs(mOutputStream)));

    mEmitter->Initialize(aURI, aChannel, newType);
    mEmitter->SetPipe(mInputStream, mOutputStream);
    mEmitter->SetOutputListener(aOutListener);
  }

  uint32_t whattodo = mozITXTToHTMLConv::kURLs;
  bool enable_emoticons = true;
  bool enable_structs = true;

  nsCOMPtr<nsIPrefBranch> pPrefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
  if (pPrefBranch)
  {
    rv = pPrefBranch->GetBoolPref(PREF_MAIL_DISPLAY_GLYPH,&enable_emoticons);
    if (NS_FAILED(rv) || enable_emoticons)
    {
      whattodo = whattodo | mozITXTToHTMLConv::kGlyphSubstitution;
    }
    rv = pPrefBranch->GetBoolPref(PREF_MAIL_DISPLAY_STRUCT,&enable_structs);
    if (NS_FAILED(rv) || enable_structs)
    {
      whattodo = whattodo | mozITXTToHTMLConv::kStructPhrase;
    }
  }

  if (mOutputType == nsMimeOutput::nsMimeMessageSource)
    return NS_OK;
  else
  {
    mBridgeStream = bridge_create_stream(mEmitter, this, aURI, newType, whattodo, aChannel);
    if (!mBridgeStream)
      return NS_ERROR_OUT_OF_MEMORY;
    else
    {
      SetStreamURI(aURI);

      //Do we need to setup an Mime Stream Converter Listener?
      if (mMimeStreamConverterListener)
        bridge_set_mime_stream_converter_listener((nsMIMESession *)mBridgeStream, mMimeStreamConverterListener, mOutputType);

      return NS_OK;
    }
  }
}

NS_IMETHODIMP nsStreamConverter::GetContentType(char **aOutputContentType)
{
  if (!aOutputContentType)
    return NS_ERROR_NULL_POINTER;

  // since this method passes a string through an IDL file we need to use nsMemory to allocate it
  // and not strdup!
  //  (1) check to see if we have a real content type...use it first...
  if (!mRealContentType.IsEmpty())
    *aOutputContentType = ToNewCString(mRealContentType);
  else if (mOutputFormat.Equals("raw"))
    *aOutputContentType = (char *) nsMemory::Clone(UNKNOWN_CONTENT_TYPE, sizeof(UNKNOWN_CONTENT_TYPE));
  else
    *aOutputContentType = ToNewCString(mOutputFormat);
  return NS_OK;
}

//
// This is the type of output operation that is being requested by libmime. The types
// of output are specified by nsIMimeOutputType enum
//
nsresult
nsStreamConverter::SetMimeOutputType(nsMimeOutputType aType)
{
  mAlreadyKnowOutputType = true;
  mOutputType = aType;
  if (mBridgeStream)
    bridge_set_output_type(mBridgeStream, aType);
  return NS_OK;
}

NS_IMETHODIMP nsStreamConverter::GetMimeOutputType(nsMimeOutputType *aOutFormat)
{
  nsresult rv = NS_OK;
  if (aOutFormat)
    *aOutFormat = mOutputType;
  else
    rv = NS_ERROR_NULL_POINTER;

  return rv;
}

//
// This is needed by libmime for MHTML link processing...this is the URI associated
// with this input stream
//
nsresult
nsStreamConverter::SetStreamURI(nsIURI *aURI)
{
  mURI = aURI;
  if (mBridgeStream)
    return bridge_new_new_uri((nsMIMESession *)mBridgeStream, aURI, mOutputType);
  else
    return NS_OK;
}

nsresult
nsStreamConverter::SetMimeHeadersListener(nsIMimeStreamConverterListener *listener, nsMimeOutputType aType)
{
   mMimeStreamConverterListener = listener;
   bridge_set_mime_stream_converter_listener((nsMIMESession *)mBridgeStream, listener, aType);
   return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetForwardInline(bool aForwardInline)
{
  mForwardInline = aForwardInline;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetForwardToAddress(nsAString &aAddress)
{
  aAddress = mForwardToAddress;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetForwardToAddress(const nsAString &aAddress)
{
  mForwardToAddress = aAddress;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetOverrideComposeFormat(bool *aResult)
{
  if (!aResult)
    return NS_ERROR_NULL_POINTER;
  *aResult = mOverrideComposeFormat;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetOverrideComposeFormat(bool aOverrideComposeFormat)
{
  mOverrideComposeFormat = aOverrideComposeFormat;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetForwardInline(bool *aResult)
{
  NS_ENSURE_ARG_POINTER(aResult);
  *aResult = mForwardInline;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetForwardInlineFilter(bool *aResult)
{
  NS_ENSURE_ARG_POINTER(aResult);
  *aResult = mForwardInlineFilter;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetForwardInlineFilter(bool aForwardInlineFilter)
{
  mForwardInlineFilter = aForwardInlineFilter;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetIdentity(nsIMsgIdentity * *aIdentity)
{
  if (!aIdentity) return NS_ERROR_NULL_POINTER;
  /*
  We don't have an identity for the local folders account,
    we will return null but it is not an error!
  */
    *aIdentity = mIdentity;
    NS_IF_ADDREF(*aIdentity);
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetIdentity(nsIMsgIdentity * aIdentity)
{
  mIdentity = aIdentity;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetOriginalMsgURI(const char * originalMsgURI)
{
  mOriginalMsgURI = originalMsgURI;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetOriginalMsgURI(char ** result)
{
  if (!result) return NS_ERROR_NULL_POINTER;
  *result = ToNewCString(mOriginalMsgURI);
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::SetOrigMsgHdr(nsIMsgDBHdr *aMsgHdr)
{
  mOrigMsgHdr = aMsgHdr;
  return NS_OK;
}

NS_IMETHODIMP
nsStreamConverter::GetOrigMsgHdr(nsIMsgDBHdr * *aMsgHdr)
{
  if (!aMsgHdr) return NS_ERROR_NULL_POINTER;
  NS_IF_ADDREF(*aMsgHdr = mOrigMsgHdr);
  return NS_OK;
} 

/////////////////////////////////////////////////////////////////////////////
// Methods for nsIStreamListener...
/////////////////////////////////////////////////////////////////////////////
//
// Notify the client that data is available in the input stream.  This
// method is called whenver data is written into the input stream by the
// networking library...
//
nsresult
nsStreamConverter::OnDataAvailable(nsIRequest     *request,
                                   nsISupports    *ctxt,
                                   nsIInputStream *aIStream,
                                   uint64_t       sourceOffset,
                                   uint32_t       aLength)
{
  nsresult        rc=NS_OK;     // should this be an error instead?
  uint32_t        readLen = aLength;
  uint32_t        written;

  // If this is the first time through and we are supposed to be
  // outputting the wrapper two pane URL, then do it now.
  if (mWrapperOutput)
  {
    char        outBuf[1024];
const char output[] = "\
<HTML>\
<FRAMESET ROWS=\"30%%,70%%\">\
<FRAME NAME=messageHeader SRC=\"%s?header=only\">\
<FRAME NAME=messageBody SRC=\"%s?header=none\">\
</FRAMESET>\
</HTML>";

    nsAutoCString url;
    if (NS_FAILED(mURI->GetSpec(url)))
      return NS_ERROR_FAILURE;

    PR_snprintf(outBuf, sizeof(outBuf), output, url.get(), url.get());

    if (mEmitter)
      mEmitter->Write(nsDependentCString(outBuf), &written);

    // rhp: will this stop the stream???? Not sure.
    return NS_ERROR_FAILURE;
  }

  char *buf = (char *)PR_Malloc(aLength);
  if (!buf)
    return NS_ERROR_OUT_OF_MEMORY; /* we couldn't allocate the object */

  readLen = aLength;
  aIStream->Read(buf, aLength, &readLen);

  // We need to filter out any null characters else we will have a lot of trouble
  // as we use c string everywhere in mime
  char * readPtr;
  char * endPtr = buf + readLen;

  // First let see if the stream contains null characters
  for (readPtr = buf; readPtr < endPtr && *readPtr; readPtr ++)
    ;

  // Did we find a null character? Then, we need to cleanup the stream
  if (readPtr < endPtr)
  {
    char * writePtr = readPtr;
    for (readPtr ++; readPtr < endPtr; readPtr ++)
    {
      if (!*readPtr)
        continue;

      *writePtr = *readPtr;
      writePtr ++;
    }
    readLen = writePtr - buf;
  }

  if (mOutputType == nsMimeOutput::nsMimeMessageSource)
  {
    rc = NS_OK;
    if (mEmitter)
    {
      rc = mEmitter->Write(Substring(buf, buf+readLen), &written);
    }
  }
  else if (mBridgeStream)
  {
    nsMIMESession   *tSession = (nsMIMESession *) mBridgeStream;
    // XXX Casting int to nsresult
    rc = static_cast<nsresult>(
      tSession->put_block((nsMIMESession *)mBridgeStream, buf, readLen));
  }

  PR_FREEIF(buf);
  return rc;
}

/////////////////////////////////////////////////////////////////////////////
// Methods for nsIRequestObserver
/////////////////////////////////////////////////////////////////////////////
//
// Notify the observer that the URL has started to load.  This method is
// called only once, at the beginning of a URL load.
//
nsresult
nsStreamConverter::OnStartRequest(nsIRequest *request, nsISupports *ctxt)
{
#ifdef DEBUG_rhp
    printf("nsStreamConverter::OnStartRequest()\n");
#endif

#ifdef DEBUG_mscott
  mConvertContentTime = PR_IntervalNow();
#endif

  // here's a little bit of hackery....
  // since the mime converter is now between the channel
  // and the
  if (request)
  {
    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
    if (channel)
    {
      nsCString contentType;
      GetContentType(getter_Copies(contentType));

      channel->SetContentType(contentType);
    }
  }

  // forward the start request to any listeners
  if (mOutListener)
  {
    if (mOutputType == nsMimeOutput::nsMimeMessageRaw)
    {
      //we need to delay the on start request until we have figure out the real content type
      mPendingRequest = request;
      mPendingContext = ctxt;
    }
    else
      mOutListener->OnStartRequest(request, ctxt);
  }

  return NS_OK;
}

//
// Notify the observer that the URL has finished loading.  This method is
// called once when the networking library has finished processing the
//
nsresult
nsStreamConverter::OnStopRequest(nsIRequest *request, nsISupports *ctxt, nsresult status)
{
  // Make sure we fire any pending OnStartRequest before we do OnStop.
  FirePendingStartRequest();
#ifdef DEBUG_rhp
    printf("nsStreamConverter::OnStopRequest()\n");
#endif

  //
  // Now complete the stream!
  //
  if (mBridgeStream)
  {
    nsMIMESession   *tSession = (nsMIMESession *) mBridgeStream;

    if (mMimeStreamConverterListener)
    {

      MimeHeaders    **workHeaders = nullptr;

      if  ( (mOutputType == nsMimeOutput::nsMimeMessageDraftOrTemplate) ||
            (mOutputType == nsMimeOutput::nsMimeMessageEditorTemplate) )
      {
        mime_draft_data *mdd = (mime_draft_data *)tSession->data_object;
        if (mdd)
          workHeaders = &(mdd->headers);
      }
      else
      {
        mime_stream_data *msd = (mime_stream_data *)tSession->data_object;
        if (msd)
          workHeaders = &(msd->headers);
      }

      if (workHeaders)
      {
        nsresult rv;
        nsCOMPtr<nsIMimeHeaders> mimeHeaders = do_CreateInstance(NS_IMIMEHEADERS_CONTRACTID, &rv);

        if (NS_SUCCEEDED(rv))
        {
          if (*workHeaders)
            mimeHeaders->Initialize(Substring((*workHeaders)->all_headers,
              (*workHeaders)->all_headers_fp));
          mMimeStreamConverterListener->OnHeadersReady(mimeHeaders);
        }
        else
          mMimeStreamConverterListener->OnHeadersReady(nullptr);
      }

      mMimeStreamConverterListener = nullptr; // release our reference
    }

    tSession->complete((nsMIMESession *)mBridgeStream);
  }

  //
  // Now complete the emitter and do necessary cleanup!
  //
  if (mEmitter)
  {
    mEmitter->Complete();
  }

  // First close the output stream...
  if (mOutputStream)
    mOutputStream->Close();

  // Make sure to do necessary cleanup!
  InternalCleanup();

#if 0
  // print out the mime timing information BEFORE we flush to layout
  // otherwise we'll be including layout information.
  printf("Time Spent in mime:    %d ms\n", PR_IntervalToMilliseconds(PR_IntervalNow() - mConvertContentTime));
#endif

  // forward on top request to any listeners
  if (mOutListener)
    mOutListener->OnStopRequest(request, ctxt, status);


  mAlreadyKnowOutputType = false;

  // since we are done converting data, lets close all the objects we own...
  // this helps us fix some circular ref counting problems we are running into...
  Close();

  // Time to return...
  return NS_OK;
}

nsresult nsStreamConverter::Close()
{
  mOutgoingChannel = nullptr;
  mEmitter = nullptr;
  mOutListener = nullptr;
  return NS_OK;
}

// nsIStreamConverter implementation

// No syncronous conversion at this time.
NS_IMETHODIMP nsStreamConverter::Convert(nsIInputStream  *aFromStream,
                                         const char *aFromType,
                                         const char *aToType,
                                         nsISupports     *aCtxt,
                                         nsIInputStream **_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

// Stream converter service calls this to initialize the actual stream converter (us).
NS_IMETHODIMP nsStreamConverter::AsyncConvertData(const char   *aFromType,
                                                  const char   *aToType,
                                                  nsIStreamListener *aListener,
                                                  nsISupports       *aCtxt)
{
  nsresult rv = NS_OK;
  nsCOMPtr<nsIMsgQuote> aMsgQuote = do_QueryInterface(aCtxt, &rv);
  nsCOMPtr<nsIChannel> aChannel;

  if (aMsgQuote)
  {
    nsCOMPtr<nsIMimeStreamConverterListener> quoteListener;
    rv = aMsgQuote->GetQuoteListener(getter_AddRefs(quoteListener));
    if (quoteListener)
      SetMimeHeadersListener(quoteListener, nsMimeOutput::nsMimeMessageQuoting);
    rv = aMsgQuote->GetQuoteChannel(getter_AddRefs(aChannel));
  }
  else
  {
    aChannel = do_QueryInterface(aCtxt, &rv);
  }

  mFromType = aFromType;
  mToType = aToType;

  NS_ASSERTION(aChannel && NS_SUCCEEDED(rv), "mailnews mime converter has to have the channel passed in...");
  if (NS_FAILED(rv)) return rv;

  nsCOMPtr<nsIURI> aUri;
  aChannel->GetURI(getter_AddRefs(aUri));
  return Init(aUri, aListener, aChannel);
}

NS_IMETHODIMP nsStreamConverter::FirePendingStartRequest()
{
  if (mPendingRequest && mOutListener)
  {
    mOutListener->OnStartRequest(mPendingRequest, mPendingContext);
    mPendingRequest = nullptr;
    mPendingContext = nullptr;
  }
  return NS_OK;
}