| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Net.Http.Headers; |
| | | 9 | | using System.Text; |
| | | 10 | | using System.Threading; |
| | | 11 | | using System.Threading.Tasks; |
| | | 12 | | |
| | | 13 | | namespace System.Net.Http |
| | | 14 | | { |
| | | 15 | | public class MultipartContent : HttpContent, IEnumerable<HttpContent> |
| | | 16 | | { |
| | | 17 | | #region Fields |
| | | 18 | | |
| | | 19 | | private const string CrLf = "\r\n"; |
| | | 20 | | |
| | | 21 | | private const int CrLfLength = 2; |
| | | 22 | | private const int DashDashLength = 2; |
| | | 23 | | private const int ColonSpaceLength = 2; |
| | | 24 | | private const int CommaSpaceLength = 2; |
| | | 25 | | |
| | 0 | 26 | | private static readonly SearchValues<char> s_allowedBoundaryChars = |
| | 0 | 27 | | SearchValues.Create(" '()+,-./0123456789:=?ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"); |
| | | 28 | | |
| | | 29 | | private readonly List<HttpContent> _nestedContent; |
| | | 30 | | private readonly string _boundary; |
| | | 31 | | |
| | | 32 | | #endregion Fields |
| | | 33 | | |
| | | 34 | | #region Construction |
| | | 35 | | |
| | | 36 | | public MultipartContent() |
| | 0 | 37 | | : this("mixed", GetDefaultBoundary()) |
| | 0 | 38 | | { } |
| | | 39 | | |
| | | 40 | | public MultipartContent(string subtype) |
| | 0 | 41 | | : this(subtype, GetDefaultBoundary()) |
| | 0 | 42 | | { } |
| | | 43 | | |
| | 0 | 44 | | public MultipartContent(string subtype, string boundary) |
| | 0 | 45 | | { |
| | 0 | 46 | | ArgumentException.ThrowIfNullOrWhiteSpace(subtype); |
| | 0 | 47 | | ValidateBoundary(boundary); |
| | | 48 | | |
| | 0 | 49 | | _boundary = boundary; |
| | | 50 | | |
| | 0 | 51 | | string quotedBoundary = boundary; |
| | 0 | 52 | | if (!quotedBoundary.StartsWith('\"')) |
| | 0 | 53 | | { |
| | 0 | 54 | | quotedBoundary = "\"" + quotedBoundary + "\""; |
| | 0 | 55 | | } |
| | | 56 | | |
| | 0 | 57 | | MediaTypeHeaderValue contentType = new MediaTypeHeaderValue("multipart/" + subtype); |
| | 0 | 58 | | contentType.Parameters.Add(new NameValueHeaderValue(nameof(boundary), quotedBoundary)); |
| | 0 | 59 | | Headers.ContentType = contentType; |
| | | 60 | | |
| | 0 | 61 | | _nestedContent = new List<HttpContent>(); |
| | 0 | 62 | | } |
| | | 63 | | |
| | | 64 | | private static void ValidateBoundary(string boundary) |
| | 0 | 65 | | { |
| | | 66 | | // NameValueHeaderValue is too restrictive for boundary. |
| | | 67 | | // Instead validate it ourselves and then quote it. |
| | 0 | 68 | | ArgumentException.ThrowIfNullOrWhiteSpace(boundary); |
| | | 69 | | |
| | | 70 | | // RFC 2046 Section 5.1.1 |
| | | 71 | | // boundary := 0*69<bchars> bcharsnospace |
| | | 72 | | // bchars := bcharsnospace / " " |
| | | 73 | | // bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" |
| | 0 | 74 | | if (boundary.Length > 70) |
| | 0 | 75 | | { |
| | 0 | 76 | | throw new ArgumentOutOfRangeException(nameof(boundary), boundary, |
| | 0 | 77 | | SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70) |
| | | 78 | | } |
| | | 79 | | // Cannot end with space. |
| | 0 | 80 | | if (boundary.EndsWith(' ')) |
| | 0 | 81 | | { |
| | 0 | 82 | | throw new ArgumentException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_hea |
| | | 83 | | } |
| | | 84 | | |
| | 0 | 85 | | if (boundary.AsSpan().ContainsAnyExcept(s_allowedBoundaryChars)) |
| | 0 | 86 | | { |
| | 0 | 87 | | throw new ArgumentException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_hea |
| | | 88 | | } |
| | 0 | 89 | | } |
| | | 90 | | |
| | | 91 | | private static string GetDefaultBoundary() |
| | 0 | 92 | | { |
| | 0 | 93 | | return Guid.NewGuid().ToString(); |
| | 0 | 94 | | } |
| | | 95 | | |
| | | 96 | | public virtual void Add(HttpContent content) |
| | 0 | 97 | | { |
| | 0 | 98 | | ArgumentNullException.ThrowIfNull(content); |
| | | 99 | | |
| | 0 | 100 | | _nestedContent.Add(content); |
| | 0 | 101 | | } |
| | | 102 | | |
| | | 103 | | #endregion Construction |
| | | 104 | | |
| | | 105 | | #region Dispose |
| | | 106 | | |
| | | 107 | | protected override void Dispose(bool disposing) |
| | 0 | 108 | | { |
| | 0 | 109 | | if (disposing) |
| | 0 | 110 | | { |
| | 0 | 111 | | foreach (HttpContent content in _nestedContent) |
| | 0 | 112 | | { |
| | 0 | 113 | | content.Dispose(); |
| | 0 | 114 | | } |
| | 0 | 115 | | _nestedContent.Clear(); |
| | 0 | 116 | | } |
| | 0 | 117 | | base.Dispose(disposing); |
| | 0 | 118 | | } |
| | | 119 | | |
| | | 120 | | #endregion Dispose |
| | | 121 | | |
| | | 122 | | #region IEnumerable<HttpContent> Members |
| | | 123 | | |
| | | 124 | | public IEnumerator<HttpContent> GetEnumerator() |
| | 0 | 125 | | { |
| | 0 | 126 | | return _nestedContent.GetEnumerator(); |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | #endregion |
| | | 130 | | |
| | | 131 | | #region IEnumerable Members |
| | | 132 | | |
| | | 133 | | Collections.IEnumerator Collections.IEnumerable.GetEnumerator() |
| | 0 | 134 | | { |
| | 0 | 135 | | return _nestedContent.GetEnumerator(); |
| | 0 | 136 | | } |
| | | 137 | | |
| | | 138 | | #endregion |
| | | 139 | | |
| | | 140 | | #region Serialization |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Gets or sets a callback that returns the <see cref="Encoding"/> to decode the value for the specified respon |
| | | 144 | | /// or <see langword="null"/> to use the default behavior. |
| | | 145 | | /// </summary> |
| | 0 | 146 | | public HeaderEncodingSelector<HttpContent>? HeaderEncodingSelector { get; set; } |
| | | 147 | | |
| | | 148 | | // for-each content |
| | | 149 | | // write "--" + boundary |
| | | 150 | | // for-each content header |
| | | 151 | | // write header: header-value |
| | | 152 | | // write content.CopyTo[Async] |
| | | 153 | | // write "--" + boundary + "--" |
| | | 154 | | // Can't be canceled directly by the user. If the overall request is canceled |
| | | 155 | | // then the stream will be closed an exception thrown. |
| | | 156 | | protected override void SerializeToStream(Stream stream, TransportContext? context, CancellationToken cancellati |
| | 0 | 157 | | { |
| | 0 | 158 | | Debug.Assert(stream != null); |
| | | 159 | | try |
| | 0 | 160 | | { |
| | | 161 | | // Write start boundary. |
| | 0 | 162 | | WriteToStream(stream, "--" + _boundary + CrLf); |
| | | 163 | | |
| | | 164 | | // Write each nested content. |
| | 0 | 165 | | for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++) |
| | 0 | 166 | | { |
| | | 167 | | // Write divider, headers, and content. |
| | 0 | 168 | | HttpContent content = _nestedContent[contentIndex]; |
| | 0 | 169 | | SerializeHeadersToStream(stream, content, writeDivider: contentIndex != 0); |
| | 0 | 170 | | content.CopyTo(stream, context, cancellationToken); |
| | 0 | 171 | | } |
| | | 172 | | |
| | | 173 | | // Write footer boundary. |
| | 0 | 174 | | WriteToStream(stream, CrLf + "--" + _boundary + "--" + CrLf); |
| | 0 | 175 | | } |
| | 0 | 176 | | catch (Exception ex) |
| | 0 | 177 | | { |
| | 0 | 178 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, ex); |
| | 0 | 179 | | throw; |
| | | 180 | | } |
| | 0 | 181 | | } |
| | | 182 | | |
| | | 183 | | // for-each content |
| | | 184 | | // write "--" + boundary |
| | | 185 | | // for-each content header |
| | | 186 | | // write header: header-value |
| | | 187 | | // write content.CopyTo[Async] |
| | | 188 | | // write "--" + boundary + "--" |
| | | 189 | | // Can't be canceled directly by the user. If the overall request is canceled |
| | | 190 | | // then the stream will be closed an exception thrown. |
| | | 191 | | protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => |
| | 0 | 192 | | SerializeToStreamAsyncCore(stream, context, default); |
| | | 193 | | |
| | | 194 | | protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cance |
| | | 195 | | // Only skip the original protected virtual SerializeToStreamAsync if this |
| | | 196 | | // isn't a derived type that may have overridden the behavior. |
| | 0 | 197 | | GetType() == typeof(MultipartContent) ? SerializeToStreamAsyncCore(stream, context, cancellationToken) : |
| | 0 | 198 | | base.SerializeToStreamAsync(stream, context, cancellationToken); |
| | | 199 | | |
| | | 200 | | private protected async Task SerializeToStreamAsyncCore(Stream stream, TransportContext? context, CancellationTo |
| | 0 | 201 | | { |
| | 0 | 202 | | Debug.Assert(stream != null); |
| | | 203 | | try |
| | 0 | 204 | | { |
| | | 205 | | // Write start boundary. |
| | 0 | 206 | | await EncodeStringToStreamAsync(stream, "--" + _boundary + CrLf, cancellationToken).ConfigureAwait(false |
| | | 207 | | |
| | | 208 | | // Write each nested content. |
| | 0 | 209 | | var output = new MemoryStream(); |
| | 0 | 210 | | for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++) |
| | 0 | 211 | | { |
| | | 212 | | // Write divider, headers, and content. |
| | 0 | 213 | | HttpContent content = _nestedContent[contentIndex]; |
| | | 214 | | |
| | 0 | 215 | | output.SetLength(0); |
| | 0 | 216 | | SerializeHeadersToStream(output, content, writeDivider: contentIndex != 0); |
| | 0 | 217 | | output.Position = 0; |
| | 0 | 218 | | await output.CopyToAsync(stream, cancellationToken).ConfigureAwait(false); |
| | | 219 | | |
| | 0 | 220 | | await content.CopyToAsync(stream, context, cancellationToken).ConfigureAwait(false); |
| | 0 | 221 | | } |
| | | 222 | | |
| | | 223 | | // Write footer boundary. |
| | 0 | 224 | | await EncodeStringToStreamAsync(stream, CrLf + "--" + _boundary + "--" + CrLf, cancellationToken).Config |
| | 0 | 225 | | } |
| | 0 | 226 | | catch (Exception ex) |
| | 0 | 227 | | { |
| | 0 | 228 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, ex); |
| | 0 | 229 | | throw; |
| | | 230 | | } |
| | 0 | 231 | | } |
| | | 232 | | |
| | | 233 | | protected override Stream CreateContentReadStream(CancellationToken cancellationToken) |
| | 0 | 234 | | { |
| | 0 | 235 | | ValueTask<Stream> task = CreateContentReadStreamAsyncCore(async: false, cancellationToken); |
| | 0 | 236 | | Debug.Assert(task.IsCompleted); |
| | 0 | 237 | | return task.GetAwaiter().GetResult(); |
| | 0 | 238 | | } |
| | | 239 | | |
| | | 240 | | protected override Task<Stream> CreateContentReadStreamAsync() => |
| | 0 | 241 | | CreateContentReadStreamAsyncCore(async: true, CancellationToken.None).AsTask(); |
| | | 242 | | |
| | | 243 | | protected override Task<Stream> CreateContentReadStreamAsync(CancellationToken cancellationToken) => |
| | | 244 | | // Only skip the original protected virtual CreateContentReadStreamAsync if this |
| | | 245 | | // isn't a derived type that may have overridden the behavior. |
| | 0 | 246 | | GetType() == typeof(MultipartContent) ? CreateContentReadStreamAsyncCore(async: true, cancellationToken).AsT |
| | 0 | 247 | | base.CreateContentReadStreamAsync(cancellationToken); |
| | | 248 | | |
| | | 249 | | private async ValueTask<Stream> CreateContentReadStreamAsyncCore(bool async, CancellationToken cancellationToken |
| | 0 | 250 | | { |
| | | 251 | | try |
| | 0 | 252 | | { |
| | 0 | 253 | | var streams = new Stream[2 + (_nestedContent.Count * 2)]; |
| | 0 | 254 | | int streamIndex = 0; |
| | | 255 | | |
| | | 256 | | // Start boundary. |
| | 0 | 257 | | streams[streamIndex++] = EncodeStringToNewStream("--" + _boundary + CrLf); |
| | | 258 | | |
| | | 259 | | // Each nested content. |
| | 0 | 260 | | for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++) |
| | 0 | 261 | | { |
| | 0 | 262 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 263 | | |
| | 0 | 264 | | HttpContent nestedContent = _nestedContent[contentIndex]; |
| | 0 | 265 | | streams[streamIndex++] = EncodeHeadersToNewStream(nestedContent, writeDivider: contentIndex != 0); |
| | | 266 | | |
| | | 267 | | Stream readStream; |
| | 0 | 268 | | if (async) |
| | 0 | 269 | | { |
| | 0 | 270 | | readStream = nestedContent.TryReadAsStream() ?? await nestedContent.ReadAsStreamAsync(cancellati |
| | 0 | 271 | | } |
| | | 272 | | else |
| | 0 | 273 | | { |
| | 0 | 274 | | readStream = nestedContent.ReadAsStream(cancellationToken); |
| | 0 | 275 | | } |
| | | 276 | | // Cannot be null, at least an empty stream is necessary. |
| | 0 | 277 | | readStream ??= new MemoryStream(); |
| | | 278 | | |
| | 0 | 279 | | if (!readStream.CanSeek) |
| | 0 | 280 | | { |
| | | 281 | | // Seekability impacts whether HttpClientHandlers are able to rewind. To maintain compat |
| | | 282 | | // and to allow such use cases when a nested stream isn't seekable (which should be rare), |
| | | 283 | | // we fall back to the base behavior. We don't dispose of the streams already obtained |
| | | 284 | | // as we don't necessarily own them yet. |
| | | 285 | | |
| | | 286 | | #pragma warning disable CA2016 |
| | | 287 | | // Do not pass a cancellationToken to base.CreateContentReadStreamAsync() as it would trigger an |
| | 0 | 288 | | return async ? await base.CreateContentReadStreamAsync().ConfigureAwait(false) : base.CreateCont |
| | | 289 | | #pragma warning restore CA2016 |
| | | 290 | | } |
| | 0 | 291 | | streams[streamIndex++] = readStream; |
| | 0 | 292 | | } |
| | | 293 | | |
| | | 294 | | // Footer boundary. |
| | 0 | 295 | | streams[streamIndex] = EncodeStringToNewStream(CrLf + "--" + _boundary + "--" + CrLf); |
| | | 296 | | |
| | 0 | 297 | | return new ContentReadStream(streams); |
| | | 298 | | } |
| | 0 | 299 | | catch (Exception ex) |
| | 0 | 300 | | { |
| | 0 | 301 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, ex); |
| | 0 | 302 | | throw; |
| | | 303 | | } |
| | 0 | 304 | | } |
| | | 305 | | |
| | | 306 | | private void SerializeHeadersToStream(Stream stream, HttpContent content, bool writeDivider) |
| | 0 | 307 | | { |
| | | 308 | | // Add divider. |
| | 0 | 309 | | if (writeDivider) // Write divider for all but the first content. |
| | 0 | 310 | | { |
| | 0 | 311 | | WriteToStream(stream, CrLf + "--"); // const strings |
| | 0 | 312 | | WriteToStream(stream, _boundary); |
| | 0 | 313 | | WriteToStream(stream, CrLf); |
| | 0 | 314 | | } |
| | | 315 | | |
| | | 316 | | // Add headers. |
| | 0 | 317 | | foreach (KeyValuePair<string, HeaderStringValues> headerPair in content.Headers.NonValidated) |
| | 0 | 318 | | { |
| | 0 | 319 | | Encoding headerValueEncoding = HeaderEncodingSelector?.Invoke(headerPair.Key, content) ?? HttpRuleParser |
| | | 320 | | |
| | 0 | 321 | | WriteToStream(stream, headerPair.Key); |
| | 0 | 322 | | WriteToStream(stream, ": "); |
| | 0 | 323 | | string delim = string.Empty; |
| | 0 | 324 | | foreach (string value in headerPair.Value) |
| | 0 | 325 | | { |
| | 0 | 326 | | WriteToStream(stream, delim); |
| | 0 | 327 | | WriteToStream(stream, value, headerValueEncoding); |
| | 0 | 328 | | delim = ", "; |
| | 0 | 329 | | } |
| | 0 | 330 | | WriteToStream(stream, CrLf); |
| | 0 | 331 | | } |
| | | 332 | | |
| | | 333 | | // Extra CRLF to end headers (even if there are no headers). |
| | 0 | 334 | | WriteToStream(stream, CrLf); |
| | 0 | 335 | | } |
| | | 336 | | |
| | | 337 | | private static ValueTask EncodeStringToStreamAsync(Stream stream, string input, CancellationToken cancellationTo |
| | 0 | 338 | | { |
| | 0 | 339 | | byte[] buffer = HttpRuleParser.DefaultHttpEncoding.GetBytes(input); |
| | 0 | 340 | | return stream.WriteAsync(new ReadOnlyMemory<byte>(buffer), cancellationToken); |
| | 0 | 341 | | } |
| | | 342 | | |
| | | 343 | | private static MemoryStream EncodeStringToNewStream(string input) |
| | 0 | 344 | | { |
| | 0 | 345 | | return new MemoryStream(HttpRuleParser.DefaultHttpEncoding.GetBytes(input), writable: false); |
| | 0 | 346 | | } |
| | | 347 | | |
| | | 348 | | private MemoryStream EncodeHeadersToNewStream(HttpContent content, bool writeDivider) |
| | 0 | 349 | | { |
| | 0 | 350 | | var stream = new MemoryStream(); |
| | 0 | 351 | | SerializeHeadersToStream(stream, content, writeDivider); |
| | 0 | 352 | | stream.Position = 0; |
| | 0 | 353 | | return stream; |
| | 0 | 354 | | } |
| | | 355 | | |
| | 0 | 356 | | internal override bool AllowDuplex => false; |
| | | 357 | | |
| | | 358 | | protected internal override bool TryComputeLength(out long length) |
| | 0 | 359 | | { |
| | | 360 | | // Start Boundary. |
| | 0 | 361 | | long currentLength = DashDashLength + _boundary.Length + CrLfLength; |
| | | 362 | | |
| | 0 | 363 | | if (_nestedContent.Count > 1) |
| | 0 | 364 | | { |
| | | 365 | | // Internal boundaries |
| | 0 | 366 | | currentLength += (_nestedContent.Count - 1) * (CrLfLength + DashDashLength + _boundary.Length + CrLfLeng |
| | 0 | 367 | | } |
| | | 368 | | |
| | 0 | 369 | | foreach (HttpContent content in _nestedContent) |
| | 0 | 370 | | { |
| | | 371 | | // Headers. |
| | 0 | 372 | | foreach (KeyValuePair<string, HeaderStringValues> headerPair in content.Headers.NonValidated) |
| | 0 | 373 | | { |
| | 0 | 374 | | currentLength += headerPair.Key.Length + ColonSpaceLength; |
| | | 375 | | |
| | 0 | 376 | | Encoding headerValueEncoding = HeaderEncodingSelector?.Invoke(headerPair.Key, content) ?? HttpRulePa |
| | | 377 | | |
| | 0 | 378 | | int valueCount = 0; |
| | 0 | 379 | | foreach (string value in headerPair.Value) |
| | 0 | 380 | | { |
| | 0 | 381 | | currentLength += headerValueEncoding.GetByteCount(value); |
| | 0 | 382 | | valueCount++; |
| | 0 | 383 | | } |
| | | 384 | | |
| | 0 | 385 | | if (valueCount > 1) |
| | 0 | 386 | | { |
| | 0 | 387 | | currentLength += (valueCount - 1) * CommaSpaceLength; |
| | 0 | 388 | | } |
| | | 389 | | |
| | 0 | 390 | | currentLength += CrLfLength; |
| | 0 | 391 | | } |
| | | 392 | | |
| | 0 | 393 | | currentLength += CrLfLength; |
| | | 394 | | |
| | | 395 | | // Content. |
| | 0 | 396 | | if (!content.TryComputeLength(out long tempContentLength)) |
| | 0 | 397 | | { |
| | 0 | 398 | | length = 0; |
| | 0 | 399 | | return false; |
| | | 400 | | } |
| | 0 | 401 | | currentLength += tempContentLength; |
| | 0 | 402 | | } |
| | | 403 | | |
| | | 404 | | // Terminating boundary. |
| | 0 | 405 | | currentLength += CrLfLength + DashDashLength + _boundary.Length + DashDashLength + CrLfLength; |
| | | 406 | | |
| | 0 | 407 | | length = currentLength; |
| | 0 | 408 | | return true; |
| | 0 | 409 | | } |
| | | 410 | | |
| | | 411 | | private sealed class ContentReadStream : Stream |
| | | 412 | | { |
| | | 413 | | private readonly Stream[] _streams; |
| | | 414 | | private readonly long _length; |
| | | 415 | | |
| | | 416 | | private int _next; |
| | | 417 | | private Stream? _current; |
| | | 418 | | private long _position; |
| | | 419 | | |
| | 0 | 420 | | internal ContentReadStream(Stream[] streams) |
| | 0 | 421 | | { |
| | 0 | 422 | | Debug.Assert(streams != null); |
| | 0 | 423 | | _streams = streams; |
| | 0 | 424 | | foreach (Stream stream in streams) |
| | 0 | 425 | | { |
| | 0 | 426 | | _length += stream.Length; |
| | 0 | 427 | | } |
| | 0 | 428 | | } |
| | | 429 | | |
| | | 430 | | protected override void Dispose(bool disposing) |
| | 0 | 431 | | { |
| | 0 | 432 | | if (disposing) |
| | 0 | 433 | | { |
| | 0 | 434 | | foreach (Stream s in _streams) |
| | 0 | 435 | | { |
| | 0 | 436 | | s.Dispose(); |
| | 0 | 437 | | } |
| | 0 | 438 | | } |
| | 0 | 439 | | } |
| | | 440 | | |
| | | 441 | | public override async ValueTask DisposeAsync() |
| | 0 | 442 | | { |
| | 0 | 443 | | foreach (Stream s in _streams) |
| | 0 | 444 | | { |
| | 0 | 445 | | await s.DisposeAsync().ConfigureAwait(false); |
| | 0 | 446 | | } |
| | 0 | 447 | | } |
| | | 448 | | |
| | 0 | 449 | | public override bool CanRead => true; |
| | 0 | 450 | | public override bool CanSeek => true; |
| | 0 | 451 | | public override bool CanWrite => false; |
| | | 452 | | |
| | | 453 | | public override int Read(byte[] buffer, int offset, int count) |
| | 0 | 454 | | { |
| | 0 | 455 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 456 | | if (count == 0) |
| | 0 | 457 | | { |
| | 0 | 458 | | return 0; |
| | | 459 | | } |
| | | 460 | | |
| | 0 | 461 | | while (true) |
| | 0 | 462 | | { |
| | 0 | 463 | | if (_current != null) |
| | 0 | 464 | | { |
| | 0 | 465 | | int bytesRead = _current.Read(buffer, offset, count); |
| | 0 | 466 | | if (bytesRead != 0) |
| | 0 | 467 | | { |
| | 0 | 468 | | _position += bytesRead; |
| | 0 | 469 | | return bytesRead; |
| | | 470 | | } |
| | | 471 | | |
| | 0 | 472 | | _current = null; |
| | 0 | 473 | | } |
| | | 474 | | |
| | 0 | 475 | | if (_next >= _streams.Length) |
| | 0 | 476 | | { |
| | 0 | 477 | | return 0; |
| | | 478 | | } |
| | | 479 | | |
| | 0 | 480 | | _current = _streams[_next++]; |
| | 0 | 481 | | } |
| | 0 | 482 | | } |
| | | 483 | | |
| | | 484 | | public override int ReadByte() |
| | 0 | 485 | | { |
| | 0 | 486 | | byte b = 0; |
| | 0 | 487 | | return Read(new Span<byte>(ref b)) == 1 ? b : -1; |
| | 0 | 488 | | } |
| | | 489 | | |
| | | 490 | | public override int Read(Span<byte> buffer) |
| | 0 | 491 | | { |
| | 0 | 492 | | if (buffer.Length == 0) |
| | 0 | 493 | | { |
| | 0 | 494 | | return 0; |
| | | 495 | | } |
| | | 496 | | |
| | 0 | 497 | | while (true) |
| | 0 | 498 | | { |
| | 0 | 499 | | if (_current != null) |
| | 0 | 500 | | { |
| | 0 | 501 | | int bytesRead = _current.Read(buffer); |
| | 0 | 502 | | if (bytesRead != 0) |
| | 0 | 503 | | { |
| | 0 | 504 | | _position += bytesRead; |
| | 0 | 505 | | return bytesRead; |
| | | 506 | | } |
| | | 507 | | |
| | 0 | 508 | | _current = null; |
| | 0 | 509 | | } |
| | | 510 | | |
| | 0 | 511 | | if (_next >= _streams.Length) |
| | 0 | 512 | | { |
| | 0 | 513 | | return 0; |
| | | 514 | | } |
| | | 515 | | |
| | 0 | 516 | | _current = _streams[_next++]; |
| | 0 | 517 | | } |
| | 0 | 518 | | } |
| | | 519 | | |
| | | 520 | | public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToke |
| | 0 | 521 | | { |
| | 0 | 522 | | ValidateBufferArguments(buffer, offset, count); |
| | 0 | 523 | | return ReadAsyncPrivate(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask(); |
| | 0 | 524 | | } |
| | | 525 | | |
| | | 526 | | public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) |
| | 0 | 527 | | ReadAsyncPrivate(buffer, cancellationToken); |
| | | 528 | | |
| | | 529 | | public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback? asyncCallback, ob |
| | 0 | 530 | | TaskToAsyncResult.Begin(ReadAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncSta |
| | | 531 | | |
| | | 532 | | public override int EndRead(IAsyncResult asyncResult) => |
| | 0 | 533 | | TaskToAsyncResult.End<int>(asyncResult); |
| | | 534 | | |
| | | 535 | | public async ValueTask<int> ReadAsyncPrivate(Memory<byte> buffer, CancellationToken cancellationToken) |
| | 0 | 536 | | { |
| | 0 | 537 | | if (buffer.Length == 0) |
| | 0 | 538 | | { |
| | 0 | 539 | | return 0; |
| | | 540 | | } |
| | | 541 | | |
| | 0 | 542 | | while (true) |
| | 0 | 543 | | { |
| | 0 | 544 | | if (_current != null) |
| | 0 | 545 | | { |
| | 0 | 546 | | int bytesRead = await _current.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); |
| | 0 | 547 | | if (bytesRead != 0) |
| | 0 | 548 | | { |
| | 0 | 549 | | _position += bytesRead; |
| | 0 | 550 | | return bytesRead; |
| | | 551 | | } |
| | | 552 | | |
| | 0 | 553 | | _current = null; |
| | 0 | 554 | | } |
| | | 555 | | |
| | 0 | 556 | | if (_next >= _streams.Length) |
| | 0 | 557 | | { |
| | 0 | 558 | | return 0; |
| | | 559 | | } |
| | | 560 | | |
| | 0 | 561 | | _current = _streams[_next++]; |
| | 0 | 562 | | } |
| | 0 | 563 | | } |
| | | 564 | | |
| | | 565 | | public override long Position |
| | | 566 | | { |
| | 0 | 567 | | get { return _position; } |
| | | 568 | | set |
| | 0 | 569 | | { |
| | 0 | 570 | | ArgumentOutOfRangeException.ThrowIfNegative(value); |
| | | 571 | | |
| | 0 | 572 | | long previousStreamsLength = 0; |
| | 0 | 573 | | for (int i = 0; i < _streams.Length; i++) |
| | 0 | 574 | | { |
| | 0 | 575 | | Stream curStream = _streams[i]; |
| | 0 | 576 | | long curLength = curStream.Length; |
| | | 577 | | |
| | 0 | 578 | | if (value < previousStreamsLength + curLength) |
| | 0 | 579 | | { |
| | 0 | 580 | | _current = curStream; |
| | 0 | 581 | | i++; |
| | 0 | 582 | | _next = i; |
| | | 583 | | |
| | 0 | 584 | | curStream.Position = value - previousStreamsLength; |
| | 0 | 585 | | for (; i < _streams.Length; i++) |
| | 0 | 586 | | { |
| | 0 | 587 | | _streams[i].Position = 0; |
| | 0 | 588 | | } |
| | | 589 | | |
| | 0 | 590 | | _position = value; |
| | 0 | 591 | | return; |
| | | 592 | | } |
| | | 593 | | |
| | 0 | 594 | | previousStreamsLength += curLength; |
| | 0 | 595 | | } |
| | | 596 | | |
| | 0 | 597 | | _current = null; |
| | 0 | 598 | | _next = _streams.Length; |
| | 0 | 599 | | _position = value; |
| | 0 | 600 | | } |
| | | 601 | | } |
| | | 602 | | |
| | | 603 | | public override long Seek(long offset, SeekOrigin origin) |
| | 0 | 604 | | { |
| | 0 | 605 | | switch (origin) |
| | | 606 | | { |
| | | 607 | | case SeekOrigin.Begin: |
| | 0 | 608 | | Position = offset; |
| | 0 | 609 | | break; |
| | | 610 | | |
| | | 611 | | case SeekOrigin.Current: |
| | 0 | 612 | | Position += offset; |
| | 0 | 613 | | break; |
| | | 614 | | |
| | | 615 | | case SeekOrigin.End: |
| | 0 | 616 | | Position = _length + offset; |
| | 0 | 617 | | break; |
| | | 618 | | |
| | | 619 | | default: |
| | 0 | 620 | | throw new ArgumentOutOfRangeException(nameof(origin)); |
| | | 621 | | } |
| | | 622 | | |
| | 0 | 623 | | return Position; |
| | 0 | 624 | | } |
| | | 625 | | |
| | 0 | 626 | | public override long Length => _length; |
| | | 627 | | |
| | 0 | 628 | | public override void Flush() { } |
| | 0 | 629 | | public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; |
| | | 630 | | |
| | 0 | 631 | | public override void SetLength(long value) { throw new NotSupportedException(); } |
| | 0 | 632 | | public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } |
| | 0 | 633 | | public override void Write(ReadOnlySpan<byte> buffer) { throw new NotSupportedException(); } |
| | 0 | 634 | | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { |
| | 0 | 635 | | public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = defa |
| | | 636 | | } |
| | | 637 | | |
| | | 638 | | |
| | | 639 | | private static void WriteToStream(Stream stream, string content) => |
| | 0 | 640 | | WriteToStream(stream, content, HttpRuleParser.DefaultHttpEncoding); |
| | | 641 | | |
| | | 642 | | private static void WriteToStream(Stream stream, string content, Encoding encoding) |
| | 0 | 643 | | { |
| | | 644 | | const int StackallocThreshold = 1024; |
| | | 645 | | |
| | 0 | 646 | | int maxLength = encoding.GetMaxByteCount(content.Length); |
| | | 647 | | |
| | 0 | 648 | | byte[]? rentedBuffer = null; |
| | 0 | 649 | | Span<byte> buffer = maxLength <= StackallocThreshold |
| | 0 | 650 | | ? stackalloc byte[StackallocThreshold] |
| | 0 | 651 | | : (rentedBuffer = ArrayPool<byte>.Shared.Rent(maxLength)); |
| | | 652 | | |
| | | 653 | | try |
| | 0 | 654 | | { |
| | 0 | 655 | | int written = encoding.GetBytes(content, buffer); |
| | 0 | 656 | | stream.Write(buffer.Slice(0, written)); |
| | 0 | 657 | | } |
| | | 658 | | finally |
| | 0 | 659 | | { |
| | 0 | 660 | | if (rentedBuffer != null) |
| | 0 | 661 | | { |
| | 0 | 662 | | ArrayPool<byte>.Shared.Return(rentedBuffer); |
| | 0 | 663 | | } |
| | 0 | 664 | | } |
| | 0 | 665 | | } |
| | | 666 | | |
| | | 667 | | #endregion Serialization |
| | | 668 | | } |
| | | 669 | | } |