aboutsummaryrefslogtreecommitdiffstats
path: root/src/body.cpp
blob: 8d6bab3f16bcd4fd90b7266dd351794ea18209da (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
//
// VMime library (http://www.vmime.org)
// Copyright (C) 2002-2013 Vincent Richard <[email protected]>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 3 of
// the License, 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
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library.  Thus, the terms and conditions of
// the GNU General Public License cover the whole combination.
//

#include "vmime/bodyPart.hpp"
#include "vmime/body.hpp"

#include "vmime/contentTypeField.hpp"
#include "vmime/text.hpp"

#include "vmime/utility/random.hpp"

#include "vmime/utility/seekableInputStreamRegionAdapter.hpp"
#include "vmime/utility/outputStreamAdapter.hpp"

#include "vmime/parserHelpers.hpp"

#include "vmime/emptyContentHandler.hpp"
#include "vmime/stringContentHandler.hpp"
#include "vmime/streamContentHandler.hpp"


namespace vmime
{


body::body()
	: m_contents(make_shared <emptyContentHandler>())
{
}


body::~body()
{
}


// static
utility::stream::size_type body::findNextBoundaryPosition
	(shared_ptr <utility::parserInputStreamAdapter> parser, const string& boundary,
	 const utility::stream::size_type position, const utility::stream::size_type end,
	 utility::stream::size_type* boundaryStart, utility::stream::size_type* boundaryEnd)
{
	utility::stream::size_type pos = position;

	while (pos != utility::stream::npos && pos < end)
	{
		pos = parser->findNext(boundary, pos);

		if (pos == utility::stream::npos)
			break;  // not found

		if (pos != 0)
		{
			// Skip transport padding bytes (SPACE or HTAB), if any
			utility::stream::size_type advance = 0;

			while (pos != 0)
			{
				parser->seek(pos - advance - 1);

				const utility::stream::value_type c = parser->peekByte();

				if (c == ' ' || c == '\t')
					++advance;
				else
					break;
			}

			// Ensure the bytes before boundary are "[LF]--": boundary should be
			// at the beginning of a line, and should start with "--"
			if (pos - advance >= 3)
			{
				parser->seek(pos - advance - 3);

				if (parser->matchBytes("\n--", 3))
				{
					parser->seek(pos + boundary.length());

					const utility::stream::value_type next = parser->peekByte();

					// Boundary should be followed by a new line or a dash
					if (next == '\r' || next == '\n' || next == '-')
					{
						// Get rid of the "[CR]" just before "[LF]--", if any
						if (pos - advance >= 4)
						{
							parser->seek(pos - advance - 4);

							if (parser->peekByte() == '\r')
								advance++;
						}

						*boundaryStart = pos - advance - 3;
						*boundaryEnd = pos + boundary.length();

						return pos;
					}
				}
			}
		}

		// Boundary is a prefix of another, continue the search
		pos++;
	}

	return pos;
}


void body::parseImpl
	(const parsingContext& /* ctx */,
	 shared_ptr <utility::parserInputStreamAdapter> parser,
	 const utility::stream::size_type position,
	 const utility::stream::size_type end,
	 utility::stream::size_type* newPosition)
{
	removeAllParts();

	m_prologText.clear();
	m_epilogText.clear();

	if (end == position)
	{

		setParsedBounds(position, end);

		if (newPosition)
			*newPosition = end;

		return;
	}

	// Check whether the body is a MIME-multipart
	bool isMultipart = false;
	string boundary;

	try
	{
		const shared_ptr <const contentTypeField> ctf =
			m_part->getHeader()->findField <contentTypeField>(fields::CONTENT_TYPE);

		const mediaType type = *ctf->getValue <mediaType>();

		if (type.getType() == mediaTypes::MULTIPART)
		{
			isMultipart = true;

			try
			{
				boundary = ctf->getBoundary();
			}
			catch (exceptions::no_such_parameter&)
			{
				// No "boundary" parameter specified: we can try to
				// guess it by scanning the body contents...
				utility::stream::size_type pos = position;

				parser->seek(pos);

				if (pos + 2 < end && parser->matchBytes("--", 2))
				{
					pos += 2;
				}
				else
				{
					pos = parser->findNext("\n--", position);

					if ((pos != utility::stream::npos) && (pos + 3 < end))
						pos += 3;  // skip \n--
				}

				if ((pos != utility::stream::npos) && (pos < end))
				{
					parser->seek(pos);

					// Read some bytes after boundary separator
					utility::stream::value_type buffer[256];
					const utility::stream::size_type bufferLen =
						parser->read(buffer, std::min(end - pos, sizeof(buffer) / sizeof(buffer[0])));

					buffer[sizeof(buffer) / sizeof(buffer[0]) - 1] = '\0';

					// Skip transport padding bytes (SPACE or HTAB), if any
					utility::stream::size_type boundarySkip = 0;

					while (boundarySkip < bufferLen && parserHelpers::isSpace(buffer[boundarySkip]))
						++boundarySkip;

					// Extract boundary from buffer (stop at first CR or LF).
					// We have to stop after a reasonnably long boundary length (100)
					// not to take the whole body contents for a boundary...
					string::value_type boundaryBytes[100];
					string::size_type boundaryLen = 0;

					for (string::value_type c = buffer[boundarySkip] ;
					     boundaryLen < bufferLen && boundaryLen < 100 && !(c == '\r' || c == '\n') ;
					     ++boundaryLen, c = buffer[boundarySkip + boundaryLen])
					{
						boundaryBytes[boundaryLen] = c;
					}

					if (boundaryLen >= 1 && boundaryLen < 100)
					{
						// RFC #1521, Page 31:
						// "...the boundary parameter, which consists of 1 to 70
						//  characters from a set of characters known to be very
						//  robust through email gateways, and NOT ending with
						//  white space..."
						while (boundaryLen != 0 &&
						       parserHelpers::isSpace(boundaryBytes[boundaryLen - 1]))
						{
							boundaryLen--;
						}

						if (boundaryLen >= 1)
							boundary = string(boundaryBytes, boundaryBytes + boundaryLen);
					}
				}
			}
		}
 	}
	catch (exceptions::no_such_field&)
	{
		// No "Content-Type" field...
	}

	// This is a multi-part body
	if (isMultipart && !boundary.empty())
	{
		utility::stream::size_type partStart = position;
		utility::stream::size_type pos = position;

		bool lastPart = false;

		// Find the first boundary
		utility::stream::size_type boundaryStart, boundaryEnd;
		pos = findNextBoundaryPosition(parser, boundary, pos, end, &boundaryStart, &boundaryEnd);

		for (int index = 0 ; !lastPart && (pos != utility::stream::npos) && (pos < end) ; ++index)
		{
			utility::stream::size_type partEnd = boundaryStart;

			// Check whether it is the last part (boundary terminated by "--")
			parser->seek(boundaryEnd);

			if (boundaryEnd + 1 < end && parser->matchBytes("--", 2))
			{
				lastPart = true;
				boundaryEnd += 2;
			}

			// RFC #1521, Page 31:
			// "...(If a boundary appears to end with white space, the
			//  white space must be presumed to have been added by a
			//  gateway, and must be deleted.)..."
			parser->seek(boundaryEnd);
			boundaryEnd += parser->skipIf(parserHelpers::isSpaceOrTab, end);

			// End of boundary line
			if (boundaryEnd + 1 < end && parser->matchBytes("\r\n", 2))
			{
				boundaryEnd += 2;
			}
			else if (boundaryEnd < end && parser->peekByte() == '\n')
			{
				++boundaryEnd;
			}

			if (index == 0)
			{
				if (partEnd > partStart)
				{
					vmime::text text;
					text.parse(parser, partStart, partEnd);

					m_prologText = text.getWholeBuffer();
				}
				else
				{
					m_prologText = "";
				}
			}
			else // index > 0
			{
				shared_ptr <bodyPart> part = m_part->createChildPart();

				// End before start may happen on empty bodyparts (directly
				// successive boundaries without even a line-break)
				if (partEnd < partStart)
					std::swap(partStart, partEnd);

				part->parse(parser, partStart, partEnd, NULL);

				m_parts.push_back(part);
			}

			partStart = boundaryEnd;

			// Find the next boundary
			pos = findNextBoundaryPosition
				(parser, boundary, boundaryEnd, end, &boundaryStart, &boundaryEnd);
		}

		m_contents = make_shared <emptyContentHandler>();

		// Last part was not found: recover from missing boundary
		if (!lastPart && pos == utility::stream::npos)
		{
			shared_ptr <bodyPart> part = m_part->createChildPart();

			try
			{
				part->parse(parser, partStart, end);
			}
			catch (std::exception&)
			{
				throw;
			}

			m_parts.push_back(part);
		}
		// Treat remaining text as epilog
		else if (partStart < end)
		{
			vmime::text text;
			text.parse(parser, partStart, end);

			m_epilogText = text.getWholeBuffer();
		}
	}
	// Treat the contents as 'simple' data
	else
	{
		encoding enc;

		try
		{
			const shared_ptr <headerField> cef =
				m_part->getHeader()->findField(fields::CONTENT_TRANSFER_ENCODING);

			enc = *cef->getValue <encoding>();
		}
		catch (exceptions::no_such_field&)
		{
			// Defaults to "7bit" (RFC-1521)
			enc = vmime::encoding(encodingTypes::SEVEN_BIT);
		}

		// Extract the (encoded) contents
		const utility::stream::size_type length = end - position;

		shared_ptr <utility::inputStream> contentStream =
			make_shared <utility::seekableInputStreamRegionAdapter>
				(parser->getUnderlyingStream(), position, length);

		m_contents = make_shared <streamContentHandler>(contentStream, length, enc);
	}

	setParsedBounds(position, end);

	if (newPosition)
		*newPosition = end;
}


text body::getActualPrologText(const generationContext& ctx) const
{
	const string& prologText =
		m_prologText.empty()
			? (isRootPart()
				? ctx.getPrologText()
				: NULL_STRING
			  )
			: m_prologText;

	if (prologText.empty())
		return text();
	else
		return text(prologText, vmime::charset("us-ascii"));
}


text body::getActualEpilogText(const generationContext& ctx) const
{
	const string& epilogText =
		m_epilogText.empty()
			? (isRootPart()
				? ctx.getEpilogText()
				: NULL_STRING
			  )
			: m_epilogText;

	if (epilogText.empty())
		return text();
	else
		return text(epilogText, vmime::charset("us-ascii"));
}


void body::generateImpl
	(const generationContext& ctx, utility::outputStream& os,
	 const string::size_type /* curLinePos */, string::size_type* newLinePos) const
{
	// MIME-Multipart
	if (getPartCount() != 0)
	{
		string boundary;

		if (!m_part)
		{
			boundary = generateRandomBoundaryString();
		}
		else
		{
			try
			{
				shared_ptr <contentTypeField> ctf =
					m_part->getHeader()->findField <contentTypeField>(fields::CONTENT_TYPE);

				boundary = ctf->getBoundary();
			}
			catch (exceptions::no_such_field&)
			{
				// Warning: no content-type and no boundary string specified!
				boundary = generateRandomBoundaryString();
			}
			catch (exceptions::no_such_parameter&)
			{
				// Warning: no boundary string specified!
				boundary = generateRandomBoundaryString();
			}
		}

		const text prologText = getActualPrologText(ctx);
		const text epilogText = getActualEpilogText(ctx);

		if (!prologText.isEmpty())
		{
			prologText.encodeAndFold(ctx, os, 0,
				NULL, text::FORCE_NO_ENCODING | text::NO_NEW_LINE_SEQUENCE);

			os << CRLF;
		}

		os << "--" << boundary;

		for (size_t p = 0 ; p < getPartCount() ; ++p)
		{
			os << CRLF;

			getPartAt(p)->generate(ctx, os, 0);

			os << CRLF << "--" << boundary;
		}

		os << "--" << CRLF;

		if (!epilogText.isEmpty())
		{
			epilogText.encodeAndFold(ctx, os, 0,
				NULL, text::FORCE_NO_ENCODING | text::NO_NEW_LINE_SEQUENCE);

			os << CRLF;
		}

		if (newLinePos)
			*newLinePos = 0;
	}
	// Simple body
	else
	{
		// Generate the contents
		shared_ptr <contentHandler> contents = m_contents->clone();
		contents->setContentTypeHint(getContentType());

		contents->generate(os, getEncoding(), ctx.getMaxLineLength());
	}
}


utility::stream::size_type body::getGeneratedSize(const generationContext& ctx)
{
	// MIME-Multipart
	if (getPartCount() != 0)
	{
		utility::stream::size_type size = 0;

		// Size of parts and boundaries
		for (size_t p = 0 ; p < getPartCount() ; ++p)
		{
			size += 100;  // boundary, CRLF...
			size += getPartAt(p)->getGeneratedSize(ctx);
		}

		// Size of prolog/epilog text
		const text prologText = getActualPrologText(ctx);

		if (!prologText.isEmpty())
		{
			std::ostringstream oss;
			utility::outputStreamAdapter osa(oss);

			prologText.encodeAndFold(ctx, osa, 0,
				NULL, text::FORCE_NO_ENCODING | text::NO_NEW_LINE_SEQUENCE);

			size += oss.str().size();
		}

		const text epilogText = getActualEpilogText(ctx);

		if (!epilogText.isEmpty())
		{
			std::ostringstream oss;
			utility::outputStreamAdapter osa(oss);

			epilogText.encodeAndFold(ctx, osa, 0,
				NULL, text::FORCE_NO_ENCODING | text::NO_NEW_LINE_SEQUENCE);

			size += oss.str().size();
		}

		return size;
	}
	// Simple body
	else
	{
		shared_ptr <utility::encoder::encoder> srcEncoder = m_contents->getEncoding().getEncoder();
		shared_ptr <utility::encoder::encoder> dstEncoder = getEncoding().getEncoder();

		return dstEncoder->getEncodedSize(srcEncoder->getDecodedSize(m_contents->getLength()));
	}
}


/*
   RFC #1521, Page 32:
   7.2.1. Multipart: The common syntax

   "...Encapsulation boundaries must not appear within the
   encapsulations, and must be no longer than 70 characters..."


   boundary := 0*69<bchars> bcharsnospace

   bchars := bcharsnospace / " "

   bcharsnospace :=    DIGIT / ALPHA / "'" / "(" / ")" / "+" /"_"
                 / "," / "-" / "." / "/" / ":" / "=" / "?"
*/

const string body::generateRandomBoundaryString()
{
	// 64 characters that can be _safely_ used in a boundary string
	static const char bchars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-+";

	/*
		RFC #1521, Page 19:

		Since the hyphen character ("-") is represented as itself in the
		Quoted-Printable encoding, care must be taken, when encapsulating a
		quoted-printable encoded body in a multipart entity, to ensure that
		the encapsulation boundary does not appear anywhere in the encoded
		body.  (A good strategy is to choose a boundary that includes a
		character sequence such as "=_" which can never appear in a quoted-
		printable body.  See the definition of multipart messages later in
		this document.)
	*/

	string::value_type boundary[2 + 48 + 1] = { 0 };

	boundary[0] = '=';
	boundary[1] = '_';

	// Generate a string of random characters
	unsigned int r = utility::random::getTime();
	unsigned int m = static_cast <unsigned int>(sizeof(unsigned int));

	for (size_t i = 2 ; i < (sizeof(boundary) / sizeof(boundary[0]) - 1) ; ++i)
	{
			boundary[i] = bchars[r & 63];
			r >>= 6;

			if (--m == 0)
			{
				r = utility::random::getNext();
				m = static_cast <unsigned int>(sizeof(unsigned int));
			}
	}

	return (string(boundary));
}


bool body::isValidBoundary(const string& boundary)
{
	static const string validChars("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'()+_,-./:=?");

	const string::const_iterator end = boundary.end();
	bool valid = false;

	if (boundary.length() > 0 && boundary.length() < 70)
	{
		const string::value_type last = *(end - 1);

		if (!(last == ' ' || last == '\t' || last == '\n'))
		{
			valid = true;

			for (string::const_iterator i = boundary.begin() ; valid && i != end ; ++i)
				valid = (validChars.find_first_of(*i) != string::npos);
		}
	}

	return (valid);
}


//
// Quick-access functions
//


void body::setContentType(const mediaType& type, const charset& chset)
{
	shared_ptr <contentTypeField> ctf =
		dynamicCast <contentTypeField>(m_part->getHeader()->ContentType());

	ctf->setValue(type);
	ctf->setCharset(chset);
}


void body::setContentType(const mediaType& type)
{
	m_part->getHeader()->ContentType()->setValue(type);
}


const mediaType body::getContentType() const
{
	try
	{
		shared_ptr <const contentTypeField> ctf =
			m_part->getHeader()->findField <contentTypeField>(fields::CONTENT_TYPE);

		return (*ctf->getValue <mediaType>());
	}
	catch (exceptions::no_such_field&)
	{
		// Defaults to "text/plain" (RFC-1521)
		return (mediaType(mediaTypes::TEXT, mediaTypes::TEXT_PLAIN));
	}
}


void body::setCharset(const charset& chset)
{
	// If a Content-Type field exists, set charset
	try
	{
		shared_ptr <contentTypeField> ctf =
			m_part->getHeader()->findField <contentTypeField>(fields::CONTENT_TYPE);

		ctf->setCharset(chset);
	}
	// Else, create a new Content-Type field of default type "text/plain"
	// and set charset on it
	catch (exceptions::no_such_field&)
	{
		setContentType(mediaType(mediaTypes::TEXT, mediaTypes::TEXT_PLAIN), chset);
	}
}


const charset body::getCharset() const
{
	try
	{
		const shared_ptr <const contentTypeField> ctf =
			m_part->getHeader()->findField <contentTypeField>(fields::CONTENT_TYPE);

		return (ctf->getCharset());
	}
	catch (exceptions::no_such_parameter&)
	{
		// Defaults to "us-ascii" (RFC-1521)
		return (vmime::charset(charsets::US_ASCII));
	}
	catch (exceptions::no_such_field&)
	{
		// Defaults to "us-ascii" (RFC-1521)
		return (vmime::charset(charsets::US_ASCII));
	}
}


void body::setEncoding(const encoding& enc)
{
	m_part->getHeader()->ContentTransferEncoding()->setValue(enc);
}


const encoding body::getEncoding() const
{
	try
	{
		const shared_ptr <const headerField> cef =
			m_part->getHeader()->findField(fields::CONTENT_TRANSFER_ENCODING);

		return *cef->getValue <encoding>();
	}
	catch (exceptions::no_such_field&)
	{
		if (m_contents->isEncoded())
		{
			return m_contents->getEncoding();
		}
		else
		{
			// Defaults to "7bit" (RFC-1521)
			return vmime::encoding(encodingTypes::SEVEN_BIT);
		}
	}
}


void body::setParentPart(bodyPart* parent)
{
	m_part = parent;

	for (std::vector <shared_ptr <bodyPart> >::iterator it = m_parts.begin() ;
	     it != m_parts.end() ; ++it)
	{
		shared_ptr <bodyPart> childPart = *it;
		parent->importChildPart(childPart);
	}
}


bool body::isRootPart() const
{
	return (m_part == NULL || m_part->getParentPart() == NULL);
}


shared_ptr <component> body::clone() const
{
	shared_ptr <body> bdy = make_shared <body>();

	bdy->copyFrom(*this);

	return (bdy);
}


void body::copyFrom(const component& other)
{
	const body& bdy = dynamic_cast <const body&>(other);

	m_prologText = bdy.m_prologText;
	m_epilogText = bdy.m_epilogText;

	m_contents = bdy.m_contents;

	removeAllParts();

	for (size_t p = 0 ; p < bdy.getPartCount() ; ++p)
	{
		shared_ptr <bodyPart> part = m_part->createChildPart();

		part->copyFrom(*bdy.getPartAt(p));

		m_parts.push_back(part);
	}
}


body& body::operator=(const body& other)
{
	copyFrom(other);
	return (*this);
}


const string& body::getPrologText() const
{
	return (m_prologText);
}


void body::setPrologText(const string& prologText)
{
	m_prologText = prologText;
}


const string& body::getEpilogText() const
{
	return (m_epilogText);
}


void body::setEpilogText(const string& epilogText)
{
	m_epilogText = epilogText;
}


const shared_ptr <const contentHandler> body::getContents() const
{
	return (m_contents);
}


void body::setContents(shared_ptr <const contentHandler> contents)
{
	m_contents = contents;
}


void body::setContents(shared_ptr <const contentHandler> contents, const mediaType& type)
{
	m_contents = contents;

	setContentType(type);
}


void body::setContents(shared_ptr <const contentHandler> contents, const mediaType& type, const charset& chset)
{
	m_contents = contents;

	setContentType(type, chset);
}


void body::setContents(shared_ptr <const contentHandler> contents, const mediaType& type,
	const charset& chset, const encoding& enc)
{
	m_contents = contents;

	setContentType(type, chset);
	setEncoding(enc);
}


void body::initNewPart(shared_ptr <bodyPart> part)
{
	// A part can be in only one body at the same time: if part is
	// already attached to a parent part, remove it from the current
	// parent part
	if (part->getParentPart())
		part->getParentPart()->getBody()->removePart(part);

	if (m_part != NULL)
	{
		m_part->importChildPart(part);

		shared_ptr <header> hdr = m_part->getHeader();

		// Check whether we have a boundary string
		try
		{
			shared_ptr <contentTypeField> ctf =
				hdr->findField <contentTypeField>(fields::CONTENT_TYPE);

			try
			{
				const string boundary = ctf->getBoundary();

				if (boundary.empty() || !isValidBoundary(boundary))
					ctf->setBoundary(generateRandomBoundaryString());
			}
			catch (exceptions::no_such_parameter&)
			{
				// No "boundary" parameter: generate a random one.
				ctf->setBoundary(generateRandomBoundaryString());
			}

			if (ctf->getValue <mediaType>()->getType() != mediaTypes::MULTIPART)
			{
				// Warning: multi-part body but the Content-Type is
				// not specified as "multipart/..."
			}
		}
		catch (exceptions::no_such_field&)
		{
			// No "Content-Type" field: create a new one and generate
			// a random boundary string.
			shared_ptr <contentTypeField> ctf =
				hdr->getField <contentTypeField>(fields::CONTENT_TYPE);

			ctf->setValue(mediaType(mediaTypes::MULTIPART, mediaTypes::MULTIPART_MIXED));
			ctf->setBoundary(generateRandomBoundaryString());
		}
	}
}


void body::appendPart(shared_ptr <bodyPart> part)
{
	initNewPart(part);

	m_parts.push_back(part);
}


void body::insertPartBefore(shared_ptr <bodyPart> beforePart, shared_ptr <bodyPart> part)
{
	initNewPart(part);

	const std::vector <shared_ptr <bodyPart> >::iterator it = std::find
		(m_parts.begin(), m_parts.end(), beforePart);

	if (it == m_parts.end())
		throw exceptions::no_such_part();

	m_parts.insert(it, part);
}


void body::insertPartBefore(const size_t pos, shared_ptr <bodyPart> part)
{
	initNewPart(part);

	m_parts.insert(m_parts.begin() + pos, part);
}


void body::insertPartAfter(shared_ptr <bodyPart> afterPart, shared_ptr <bodyPart> part)
{
	initNewPart(part);

	const std::vector <shared_ptr <bodyPart> >::iterator it = std::find
		(m_parts.begin(), m_parts.end(), afterPart);

	if (it == m_parts.end())
		throw exceptions::no_such_part();

	m_parts.insert(it + 1, part);
}


void body::insertPartAfter(const size_t pos, shared_ptr <bodyPart> part)
{
	initNewPart(part);

	m_parts.insert(m_parts.begin() + pos + 1, part);
}


void body::removePart(shared_ptr <bodyPart> part)
{
	const std::vector <shared_ptr <bodyPart> >::iterator it = std::find
		(m_parts.begin(), m_parts.end(), part);

	if (it == m_parts.end())
		throw exceptions::no_such_part();

	m_parts.erase(it);
}


void body::removePart(const size_t pos)
{
	m_parts.erase(m_parts.begin() + pos);
}


void body::removeAllParts()
{
	m_parts.clear();
}


size_t body::getPartCount() const
{
	return (m_parts.size());
}


bool body::isEmpty() const
{
	return (m_parts.size() == 0);
}


shared_ptr <bodyPart> body::getPartAt(const size_t pos)
{
	return (m_parts[pos]);
}


const shared_ptr <const bodyPart> body::getPartAt(const size_t pos) const
{
	return (m_parts[pos]);
}


const std::vector <shared_ptr <const bodyPart> > body::getPartList() const
{
	std::vector <shared_ptr <const bodyPart> > list;

	list.reserve(m_parts.size());

	for (std::vector <shared_ptr <bodyPart> >::const_iterator it = m_parts.begin() ;
	     it != m_parts.end() ; ++it)
	{
		list.push_back(*it);
	}

	return (list);
}


const std::vector <shared_ptr <bodyPart> > body::getPartList()
{
	return (m_parts);
}


const std::vector <shared_ptr <component> > body::getChildComponents()
{
	std::vector <shared_ptr <component> > list;

	copy_vector(m_parts, list);

	return (list);
}


} // vmime