using System; using System.Linq; namespace EmbedIO.Utilities { partial class Validate { private static readonly char[] ValidRfc2616TokenChars = GetValidRfc2616TokenChars(); /// /// Ensures that a argument is valid as a token as defined by /// RFC2616, Section 2.2. /// RFC2616 tokens are used, for example, as: /// /// cookie names, as stated in RFC6265, Section 4.1.1; /// WebSocket protocol names, as stated in RFC6455, Section 4.3. /// /// Only a restricted set of characters are allowed in tokens, including: /// /// upper- and lower-case letters of the English alphabet; /// decimal digits; /// the following non-alphanumeric characters: /// !, #, $, %, &, ', *, +, /// -, ., ^, _, `, |, ~. /// /// /// The name of the argument to validate. /// The value to validate. /// , if it is a valid token. /// is . /// /// is the empty string. /// - or - /// contains one or more characters that are not allowed in a token. /// public static string Rfc2616Token(string argumentName, string value) { value = NotNullOrEmpty(argumentName, value); if (!IsRfc2616Token(value)) throw new ArgumentException("Token contains one or more invalid characters.", argumentName); return value; } internal static bool IsRfc2616Token(string value) => !string.IsNullOrEmpty(value) && !value.Any(c => c < '\x21' || c > '\x7E' || Array.BinarySearch(ValidRfc2616TokenChars, c) < 0); private static char[] GetValidRfc2616TokenChars() => "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&'*+-.^_`|~" .OrderBy(c => c) .ToArray(); } }