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