| | | 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.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | |
| | | 7 | | namespace System.Net.Http.Headers |
| | | 8 | | { |
| | | 9 | | // Don't derive from BaseHeaderParser since parsing the Base64 string is delegated to Convert.FromBase64String() |
| | | 10 | | // which will remove leading, trailing, and whitespace in the middle of the string. |
| | | 11 | | internal sealed class ByteArrayHeaderParser : HttpHeaderParser |
| | | 12 | | { |
| | 1 | 13 | | internal static readonly ByteArrayHeaderParser Parser = new ByteArrayHeaderParser(); |
| | | 14 | | |
| | | 15 | | private ByteArrayHeaderParser() |
| | 1 | 16 | | : base(false) |
| | 1 | 17 | | { |
| | 1 | 18 | | } |
| | | 19 | | |
| | | 20 | | public override string ToString(object value) |
| | 6 | 21 | | { |
| | 6 | 22 | | Debug.Assert(value is byte[]); |
| | | 23 | | |
| | 6 | 24 | | return Convert.ToBase64String((byte[])value); |
| | 6 | 25 | | } |
| | | 26 | | |
| | | 27 | | public override bool TryParseValue([NotNullWhen(true)] string? value, object? storeValue, ref int index, [NotNul |
| | 18 | 28 | | { |
| | 18 | 29 | | parsedValue = null; |
| | | 30 | | |
| | | 31 | | // Some headers support empty/null values. This one doesn't. |
| | 18 | 32 | | if (string.IsNullOrEmpty(value) || (index == value.Length)) |
| | 6 | 33 | | { |
| | 6 | 34 | | return false; |
| | | 35 | | } |
| | | 36 | | |
| | 12 | 37 | | string base64String = value; |
| | 12 | 38 | | if (index > 0) |
| | 0 | 39 | | { |
| | 0 | 40 | | base64String = value.Substring(index); |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | // Try convert the string (we assume it's a valid Base64 string) to byte[]. |
| | | 44 | | try |
| | 12 | 45 | | { |
| | 12 | 46 | | parsedValue = Convert.FromBase64String(base64String); |
| | 4 | 47 | | index = value.Length; |
| | 4 | 48 | | return true; |
| | | 49 | | } |
| | 8 | 50 | | catch (FormatException e) |
| | 8 | 51 | | { |
| | 8 | 52 | | if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, SR.Format(SR.net_http_parser_invalid_base |
| | 8 | 53 | | } |
| | | 54 | | |
| | 8 | 55 | | return false; |
| | 18 | 56 | | } |
| | | 57 | | } |
| | | 58 | | } |