| | | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Text; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | |
| | | 11 | | namespace Azure.Core |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Provides a container for content encoded using multipart/form-data MIME type. |
| | | 15 | | /// </summary> |
| | | 16 | | internal class MultipartFormDataContent : RequestContent |
| | | 17 | | { |
| | | 18 | | #region Fields |
| | | 19 | | |
| | | 20 | | private const string CrLf = "\r\n"; |
| | | 21 | | private const string FormData = "form-data"; |
| | | 22 | | |
| | 2 | 23 | | private static readonly int s_crlfLength = GetEncodedLength(CrLf); |
| | 2 | 24 | | private static readonly int s_dashDashLength = GetEncodedLength("--"); |
| | 2 | 25 | | private static readonly int s_colonSpaceLength = GetEncodedLength(": "); |
| | | 26 | | |
| | | 27 | | private readonly List<MultipartRequestContent> _nestedContent; |
| | | 28 | | private readonly string _boundary; |
| | | 29 | | |
| | | 30 | | #endregion Fields |
| | | 31 | | |
| | | 32 | | #region Construction |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Initializes a new instance of the <see cref="MultipartFormDataContent"/> class. |
| | | 36 | | /// </summary> |
| | 18 | 37 | | public MultipartFormDataContent() : this(GetDefaultBoundary()) |
| | 18 | 38 | | { } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Initializes a new instance of the <see cref="MultipartFormDataContent"/> class. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="boundary">The boundary string for the multipart form data content.</param> |
| | 104 | 44 | | public MultipartFormDataContent(string boundary) |
| | | 45 | | { |
| | 104 | 46 | | ValidateBoundary(boundary); |
| | 68 | 47 | | _boundary = boundary; |
| | 68 | 48 | | _nestedContent = new List<MultipartRequestContent>(); |
| | 68 | 49 | | } |
| | | 50 | | |
| | | 51 | | private static void ValidateBoundary(string boundary) |
| | | 52 | | { |
| | | 53 | | // NameValueHeaderValue is too restrictive for boundary. |
| | | 54 | | // Instead validate it ourselves and then quote it. |
| | 104 | 55 | | Argument.AssertNotNullOrWhiteSpace(boundary, nameof(boundary)); |
| | | 56 | | |
| | | 57 | | // RFC 2046 Section 5.1.1 |
| | | 58 | | // boundary := 0*69<bchars> bcharsnospace |
| | | 59 | | // bchars := bcharsnospace / " " |
| | | 60 | | // bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" |
| | 100 | 61 | | if (boundary.Length > 70) |
| | | 62 | | { |
| | 2 | 63 | | throw new ArgumentOutOfRangeException(nameof(boundary), boundary, $"The field cannot be longer than {70} |
| | | 64 | | } |
| | | 65 | | // Cannot end with space. |
| | 98 | 66 | | if (boundary.EndsWith(" ", StringComparison.InvariantCultureIgnoreCase)) |
| | | 67 | | { |
| | 2 | 68 | | throw new ArgumentException($"The format of value '{boundary}' is invalid.", nameof(boundary)); |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | const string AllowedMarks = @"'()+_,-./:=? "; |
| | | 72 | | |
| | 2268 | 73 | | foreach (char ch in boundary) |
| | | 74 | | { |
| | 1052 | 75 | | if (('0' <= ch && ch <= '9') || // Digit. |
| | 1052 | 76 | | ('a' <= ch && ch <= 'z') || // alpha. |
| | 1052 | 77 | | ('A' <= ch && ch <= 'Z') || // ALPHA. |
| | 1052 | 78 | | AllowedMarks.Contains(char.ToString(ch))) // Marks. |
| | | 79 | | { |
| | | 80 | | // Valid. |
| | | 81 | | } |
| | | 82 | | else |
| | | 83 | | { |
| | 28 | 84 | | throw new ArgumentException($"The format of value '{boundary}' is invalid.", nameof(boundary)); |
| | | 85 | | } |
| | | 86 | | } |
| | 68 | 87 | | } |
| | | 88 | | |
| | | 89 | | private static string GetDefaultBoundary() |
| | | 90 | | { |
| | 18 | 91 | | return Guid.NewGuid().ToString(); |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// Add content type header to the request. |
| | | 96 | | /// </summary> |
| | | 97 | | /// <param name="request">The request.</param> |
| | | 98 | | public void ApplyToRequest(Request request) |
| | | 99 | | { |
| | 4 | 100 | | request.Headers.Add("Content-Type", $"multipart/form-data;boundary=\"{_boundary}\""); |
| | 4 | 101 | | } |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Add HTTP content to a collection of RequestContent objects that |
| | | 105 | | /// get serialized to multipart/form-data MIME type. |
| | | 106 | | /// </summary> |
| | | 107 | | /// <param name="content">The Request content to add to the collection.</param> |
| | | 108 | | public void Add(RequestContent content) |
| | | 109 | | { |
| | 8 | 110 | | Argument.AssertNotNull(content, nameof(content)); |
| | 6 | 111 | | AddInternal(content, null, null, null); |
| | 6 | 112 | | } |
| | | 113 | | |
| | | 114 | | /// <summary> |
| | | 115 | | /// Add HTTP content to a collection of RequestContent objects that |
| | | 116 | | /// get serialized to multipart/form-data MIME type. |
| | | 117 | | /// </summary> |
| | | 118 | | /// <param name="content">The Request content to add to the collection.</param> |
| | | 119 | | /// <param name="headers">The headers to add to the collection.</param> |
| | | 120 | | public void Add(RequestContent content, Dictionary<string, string> headers) |
| | | 121 | | { |
| | 6 | 122 | | Argument.AssertNotNull(content, nameof(content)); |
| | 6 | 123 | | Argument.AssertNotNull(headers, nameof(headers)); |
| | | 124 | | |
| | 6 | 125 | | AddInternal(content, headers, null, null); |
| | 6 | 126 | | } |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Add HTTP content to a collection of RequestContent objects that |
| | | 130 | | /// get serialized to multipart/form-data MIME type. |
| | | 131 | | /// </summary> |
| | | 132 | | /// <param name="content">The Request content to add to the collection.</param> |
| | | 133 | | /// <param name="name">The name for the request content to add.</param> |
| | | 134 | | /// <param name="headers">The headers to add to the collection.</param> |
| | | 135 | | public void Add(RequestContent content, string name, Dictionary<string, string>? headers) |
| | | 136 | | { |
| | 8 | 137 | | Argument.AssertNotNull(content, nameof(content)); |
| | 8 | 138 | | Argument.AssertNotNullOrWhiteSpace(name, nameof(name)); |
| | | 139 | | |
| | 4 | 140 | | AddInternal(content, headers, name, null); |
| | 4 | 141 | | } |
| | | 142 | | |
| | | 143 | | /// <summary> |
| | | 144 | | /// Add HTTP content to a collection of RequestContent objects that |
| | | 145 | | /// get serialized to multipart/form-data MIME type. |
| | | 146 | | /// </summary> |
| | | 147 | | /// <param name="content">The Request content to add to the collection.</param> |
| | | 148 | | /// <param name="name">The name for the request content to add.</param> |
| | | 149 | | /// <param name="fileName">The file name for the reuest content to add to the collection.</param> |
| | | 150 | | /// <param name="headers">The headers to add to the collection.</param> |
| | | 151 | | public void Add(RequestContent content, string name, string fileName, Dictionary<string, string>? headers) |
| | | 152 | | { |
| | 14 | 153 | | Argument.AssertNotNull(content, nameof(content)); |
| | 14 | 154 | | Argument.AssertNotNullOrWhiteSpace(name, nameof(name)); |
| | 14 | 155 | | Argument.AssertNotNullOrWhiteSpace(fileName, nameof(fileName)); |
| | | 156 | | |
| | 10 | 157 | | AddInternal(content, headers, name, fileName); |
| | 10 | 158 | | } |
| | | 159 | | |
| | | 160 | | private void AddInternal(RequestContent content, Dictionary<string, string>? headers, string? name, string? file |
| | | 161 | | { |
| | 26 | 162 | | if (headers == null) |
| | | 163 | | { |
| | 6 | 164 | | headers = new Dictionary<string, string>(); |
| | | 165 | | } |
| | | 166 | | |
| | 26 | 167 | | if (!headers.ContainsKey("Content-Disposition")) |
| | | 168 | | { |
| | 24 | 169 | | var value = FormData; |
| | | 170 | | |
| | 24 | 171 | | if (name != null) |
| | | 172 | | { |
| | 14 | 173 | | value = value + "; name=" + name; |
| | | 174 | | } |
| | 24 | 175 | | if (fileName != null) |
| | | 176 | | { |
| | 10 | 177 | | value = value + "; filename=" + fileName; |
| | | 178 | | } |
| | | 179 | | |
| | 24 | 180 | | headers.Add("Content-Disposition", value); |
| | | 181 | | } |
| | | 182 | | |
| | 26 | 183 | | _nestedContent.Add(new MultipartRequestContent(content, headers)); |
| | 26 | 184 | | } |
| | | 185 | | |
| | | 186 | | #endregion Construction |
| | | 187 | | |
| | | 188 | | #region Dispose |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Frees resources held by the <see cref="MultipartFormDataContent"/> object. |
| | | 192 | | /// </summary> |
| | | 193 | | public override void Dispose() |
| | | 194 | | { |
| | 60 | 195 | | foreach (MultipartRequestContent content in _nestedContent) |
| | | 196 | | { |
| | 14 | 197 | | content.RequestContent.Dispose(); |
| | | 198 | | } |
| | 16 | 199 | | _nestedContent.Clear(); |
| | | 200 | | |
| | 16 | 201 | | } |
| | | 202 | | |
| | | 203 | | #endregion Dispose |
| | | 204 | | |
| | | 205 | | #region Serialization |
| | | 206 | | |
| | | 207 | | // for-each content |
| | | 208 | | // write "--" + boundary |
| | | 209 | | // for-each content header |
| | | 210 | | // write header: header-value |
| | | 211 | | // write content.WriteTo[Async] |
| | | 212 | | // write "--" + boundary + "--" |
| | | 213 | | // Can't be canceled directly by the user. If the overall request is canceled |
| | | 214 | | // then the stream will be closed an exception thrown. |
| | | 215 | | /// <summary> |
| | | 216 | | /// |
| | | 217 | | /// </summary> |
| | | 218 | | /// <param name="stream"></param> |
| | | 219 | | /// <param name="cancellationToken"></param> |
| | | 220 | | /// |
| | | 221 | | public override void WriteTo(Stream stream, CancellationToken cancellationToken) |
| | | 222 | | { |
| | 0 | 223 | | Argument.AssertNotNull(stream, nameof(stream)); |
| | | 224 | | |
| | | 225 | | try |
| | | 226 | | { |
| | | 227 | | // Write start boundary. |
| | 0 | 228 | | EncodeStringToStream(stream, "--" + _boundary + CrLf); |
| | | 229 | | |
| | | 230 | | // Write each nested content. |
| | 0 | 231 | | var output = new StringBuilder(); |
| | 0 | 232 | | for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++) |
| | | 233 | | { |
| | | 234 | | // Write divider, headers, and content. |
| | 0 | 235 | | RequestContent content = _nestedContent[contentIndex].RequestContent; |
| | 0 | 236 | | Dictionary<string, string> headers = _nestedContent[contentIndex].Headers; |
| | 0 | 237 | | EncodeStringToStream(stream, SerializeHeadersToString(output, contentIndex, headers)); |
| | 0 | 238 | | content.WriteTo(stream, cancellationToken); |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | // Write footer boundary. |
| | 0 | 242 | | EncodeStringToStream(stream, CrLf + "--" + _boundary + "--" + CrLf); |
| | 0 | 243 | | } |
| | 0 | 244 | | catch (Exception) |
| | | 245 | | { |
| | 0 | 246 | | throw; |
| | | 247 | | } |
| | 0 | 248 | | } |
| | | 249 | | |
| | | 250 | | // for-each content |
| | | 251 | | // write "--" + boundary |
| | | 252 | | // for-each content header |
| | | 253 | | // write header: header-value |
| | | 254 | | // write content.WriteTo[Async] |
| | | 255 | | // write "--" + boundary + "--" |
| | | 256 | | // Can't be canceled directly by the user. If the overall request is canceled |
| | | 257 | | // then the stream will be closed an exception thrown. |
| | | 258 | | /// <summary> |
| | | 259 | | /// |
| | | 260 | | /// </summary> |
| | | 261 | | /// <param name="stream"></param> |
| | | 262 | | /// <param name="cancellation"></param> |
| | | 263 | | /// <returns></returns> |
| | | 264 | | public override Task WriteToAsync(Stream stream, CancellationToken cancellation) => |
| | 16 | 265 | | SerializeToStreamAsync(stream, cancellation); |
| | | 266 | | |
| | | 267 | | private async Task SerializeToStreamAsync(Stream stream, CancellationToken cancellationToken) |
| | | 268 | | { |
| | 16 | 269 | | Argument.AssertNotNull(stream, nameof(stream)); |
| | | 270 | | try |
| | | 271 | | { |
| | | 272 | | // Write start boundary. |
| | 16 | 273 | | await EncodeStringToStreamAsync(stream, "--" + _boundary + CrLf, cancellationToken).ConfigureAwait(false |
| | | 274 | | |
| | | 275 | | // Write each nested content. |
| | 16 | 276 | | var output = new StringBuilder(); |
| | 72 | 277 | | for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++) |
| | | 278 | | { |
| | | 279 | | // Write divider, headers, and content. |
| | 20 | 280 | | RequestContent content = _nestedContent[contentIndex].RequestContent; |
| | 20 | 281 | | Dictionary<string, string> headers = _nestedContent[contentIndex].Headers; |
| | 20 | 282 | | await EncodeStringToStreamAsync(stream, SerializeHeadersToString(output, contentIndex, headers), can |
| | 20 | 283 | | await content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); |
| | 20 | 284 | | } |
| | | 285 | | |
| | | 286 | | // Write footer boundary. |
| | 16 | 287 | | await EncodeStringToStreamAsync(stream, CrLf + "--" + _boundary + "--" + CrLf, cancellationToken).Config |
| | 16 | 288 | | } |
| | 0 | 289 | | catch (Exception) |
| | | 290 | | { |
| | 0 | 291 | | throw; |
| | | 292 | | } |
| | 16 | 293 | | } |
| | | 294 | | |
| | | 295 | | private string SerializeHeadersToString(StringBuilder scratch, int contentIndex, Dictionary<string, string> head |
| | | 296 | | { |
| | 20 | 297 | | scratch.Clear(); |
| | | 298 | | |
| | | 299 | | // Add divider. |
| | 20 | 300 | | if (contentIndex != 0) // Write divider for all but the first content. |
| | | 301 | | { |
| | 6 | 302 | | scratch.Append(CrLf + "--"); // const strings |
| | 6 | 303 | | scratch.Append(_boundary); |
| | 6 | 304 | | scratch.Append(CrLf); |
| | | 305 | | } |
| | | 306 | | |
| | | 307 | | // Add headers. |
| | 120 | 308 | | foreach (KeyValuePair<string, string> header in headers) |
| | | 309 | | { |
| | 40 | 310 | | scratch.Append(header.Key); |
| | 40 | 311 | | scratch.Append(": "); |
| | 40 | 312 | | scratch.Append(header.Value); |
| | 40 | 313 | | scratch.Append(CrLf); |
| | | 314 | | } |
| | | 315 | | |
| | | 316 | | // Extra CRLF to end headers (even if there are no headers). |
| | 20 | 317 | | scratch.Append(CrLf); |
| | | 318 | | |
| | 20 | 319 | | return scratch.ToString(); |
| | | 320 | | } |
| | | 321 | | |
| | | 322 | | private static void EncodeStringToStream(Stream stream, string input) |
| | | 323 | | { |
| | 0 | 324 | | byte[] buffer = Encoding.Default.GetBytes(input); |
| | 0 | 325 | | stream.Write(buffer, 0, buffer.Length); |
| | 0 | 326 | | } |
| | | 327 | | |
| | | 328 | | private static Task EncodeStringToStreamAsync(Stream stream, string input, CancellationToken cancellationToken) |
| | | 329 | | { |
| | 52 | 330 | | byte[] buffer = Encoding.Default.GetBytes(input); |
| | 52 | 331 | | return stream.WriteAsync(buffer, 0, buffer.Length, cancellationToken); |
| | | 332 | | } |
| | | 333 | | |
| | | 334 | | /// <summary> |
| | | 335 | | /// Attempts to compute the length of the underlying content, if available. |
| | | 336 | | /// </summary> |
| | | 337 | | /// <param name="length">The length of the underlying data.</param> |
| | | 338 | | public override bool TryComputeLength(out long length) |
| | | 339 | | { |
| | 4 | 340 | | int boundaryLength = GetEncodedLength(_boundary); |
| | | 341 | | |
| | 4 | 342 | | long currentLength = 0; |
| | 4 | 343 | | long internalBoundaryLength = s_crlfLength + s_dashDashLength + boundaryLength + s_crlfLength; |
| | | 344 | | |
| | | 345 | | // Start Boundary. |
| | 4 | 346 | | currentLength += s_dashDashLength + boundaryLength + s_crlfLength; |
| | | 347 | | |
| | 4 | 348 | | bool first = true; |
| | 24 | 349 | | foreach (MultipartRequestContent content in _nestedContent) |
| | | 350 | | { |
| | 8 | 351 | | if (first) |
| | | 352 | | { |
| | 4 | 353 | | first = false; // First boundary already written. |
| | | 354 | | } |
| | | 355 | | else |
| | | 356 | | { |
| | | 357 | | // Internal Boundary. |
| | 4 | 358 | | currentLength += internalBoundaryLength; |
| | | 359 | | } |
| | | 360 | | |
| | | 361 | | // Headers. |
| | 48 | 362 | | foreach (KeyValuePair<string, string> headerPair in content.Headers) |
| | | 363 | | { |
| | 16 | 364 | | currentLength += GetEncodedLength(headerPair.Key) + s_colonSpaceLength; |
| | 16 | 365 | | currentLength += GetEncodedLength(headerPair.Value); |
| | 16 | 366 | | currentLength += s_crlfLength; |
| | | 367 | | } |
| | | 368 | | |
| | 8 | 369 | | currentLength += s_crlfLength; |
| | | 370 | | |
| | | 371 | | // Content. |
| | 8 | 372 | | if (!content.RequestContent.TryComputeLength(out long tempContentLength)) |
| | | 373 | | { |
| | 0 | 374 | | length = 0; |
| | 0 | 375 | | return false; |
| | | 376 | | } |
| | 8 | 377 | | currentLength += tempContentLength; |
| | | 378 | | } |
| | | 379 | | |
| | | 380 | | // Terminating boundary. |
| | 4 | 381 | | currentLength += s_crlfLength + s_dashDashLength + boundaryLength + s_dashDashLength + s_crlfLength; |
| | | 382 | | |
| | 4 | 383 | | length = currentLength; |
| | 4 | 384 | | return true; |
| | 0 | 385 | | } |
| | | 386 | | |
| | | 387 | | private static int GetEncodedLength(string input) |
| | | 388 | | { |
| | 42 | 389 | | return Encoding.Default.GetByteCount(input); |
| | | 390 | | } |
| | | 391 | | |
| | | 392 | | #endregion Serialization |
| | | 393 | | |
| | | 394 | | private class MultipartRequestContent |
| | | 395 | | { |
| | | 396 | | public readonly RequestContent RequestContent; |
| | | 397 | | public Dictionary<string, string> Headers; |
| | | 398 | | |
| | 26 | 399 | | public MultipartRequestContent(RequestContent content, Dictionary<string, string> headers) |
| | | 400 | | { |
| | 26 | 401 | | RequestContent = content; |
| | 26 | 402 | | Headers = headers; |
| | 26 | 403 | | } |
| | | 404 | | } |
| | | 405 | | } |
| | | 406 | | } |