5 // Marek Safar <marek.safar@gmail.com>
7 // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Threading.Tasks;
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Globalization;
34 using System.Net.Http.Headers;
38 namespace System.Net.Http
40 public class MultipartContent : HttpContent, IEnumerable<HttpContent>
42 List<HttpContent> nested_content;
43 readonly string boundary;
45 public MultipartContent ()
50 public MultipartContent (string subtype)
51 : this (subtype, Guid.NewGuid ().ToString ("D", CultureInfo.InvariantCulture))
55 public MultipartContent (string subtype, string boundary)
57 if (string.IsNullOrWhiteSpace (subtype))
58 throw new ArgumentException ("boundary");
61 // The only mandatory parameter for the multipart Content-Type is the boundary parameter, which consists
62 // of 1 to 70 characters from a set of characters known to be very robust through email gateways,
63 // and NOT ending with white space
65 if (string.IsNullOrWhiteSpace (boundary))
66 throw new ArgumentException ("boundary");
68 if (boundary.Length > 70)
69 throw new ArgumentOutOfRangeException ("boundary");
71 if (boundary.Last () == ' ' || !IsValidRFC2049 (boundary))
72 throw new ArgumentException ("boundary");
74 this.boundary = boundary;
75 this.nested_content = new List<HttpContent> (2);
77 Headers.ContentType = new MediaTypeHeaderValue ("multipart/" + subtype) {
78 Parameters = { new NameValueHeaderValue ("boundary", "\"" + boundary + "\"") }
82 static bool IsValidRFC2049 (string s)
84 foreach (char c in s) {
85 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
89 case '\'': case '(': case ')': case '+': case ',':
90 case '-': case '.': case '/': case ':': case '=':
101 public virtual void Add (HttpContent content)
104 throw new ArgumentNullException ("content");
106 if (nested_content == null)
107 nested_content = new List<HttpContent> ();
109 nested_content.Add (content);
112 protected override void Dispose (bool disposing)
115 foreach (var item in nested_content) {
119 nested_content = null;
122 base.Dispose (disposing);
125 protected internal override async Task SerializeToStreamAsync (Stream stream, TransportContext context)
129 // The Content-Type field for multipart entities requires one parameter,
130 // "boundary". The boundary delimiter line is then defined as a line
131 // consisting entirely of two hyphen characters ("-", decimal value 45)
132 // followed by the boundary parameter value from the Content-Type header
133 // field, optional linear whitespace, and a terminating CRLF.
137 var sb = new StringBuilder ();
138 sb.Append ('-').Append ('-');
139 sb.Append (boundary);
140 sb.Append ('\r').Append ('\n');
142 for (int i = 0; i < nested_content.Count; i++) {
143 var c = nested_content [i];
145 foreach (var h in c.Headers) {
147 sb.Append (':').Append (' ');
148 foreach (var v in h.Value) {
151 sb.Append ('\r').Append ('\n');
153 sb.Append ('\r').Append ('\n');
155 buffer = Encoding.ASCII.GetBytes (sb.ToString ());
157 await stream.WriteAsync (buffer, 0, buffer.Length).ConfigureAwait (false);
159 await c.SerializeToStreamAsync (stream, context).ConfigureAwait (false);
161 if (i != nested_content.Count - 1) {
162 sb.Append ('\r').Append ('\n');
163 sb.Append ('-').Append ('-');
164 sb.Append (boundary);
165 sb.Append ('\r').Append ('\n');
169 sb.Append ('\r').Append ('\n');
170 sb.Append ('-').Append ('-');
171 sb.Append (boundary);
172 sb.Append ('-').Append ('-');
173 sb.Append ('\r').Append ('\n');
175 buffer = Encoding.ASCII.GetBytes (sb.ToString ());
176 await stream.WriteAsync (buffer, 0, buffer.Length).ConfigureAwait (false);
179 protected internal override bool TryComputeLength (out long length)
181 length = 12 + 2 * boundary.Length;
183 for (int i = 0; i < nested_content.Count; i++) {
184 var c = nested_content [i];
185 foreach (var h in c.Headers) {
186 length += h.Key.Length;
189 foreach (var v in h.Value) {
195 if (!c.TryComputeLength (out l))
201 if (i != nested_content.Count - 1) {
203 length += boundary.Length;
210 public IEnumerator<HttpContent> GetEnumerator ()
212 return nested_content.GetEnumerator ();
215 IEnumerator IEnumerable.GetEnumerator ()
217 return nested_content.GetEnumerator ();