public static TValue?FromBytes <TValue>(this ReadOnlyMemory <byte> bytes,
                                         MessagePackSerializerOptions?options = null, CancellationToken cancellationToken = default) =>
 MessagePackHelper.FromBytes <TValue>(bytes, options, cancellationToken);
Example #2
0
 public override ValueTask WriteAsync(ReadOnlyMemory <byte> buffer, CancellationToken cancellationToken = default)
 {
     throw new NotSupportedException(SR.net_http_content_readonly_stream);
 }
Example #3
0
 internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory <byte> rebind, out EnvelopedDataAsn decoded)
 {
     Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
 }
Example #4
0
 private Task WriteAsyncCore(ReadOnlyMemory <byte> source, CancellationToken cancellationToken)
 {
     throw new PlatformNotSupportedException();
 }
Example #5
0
 internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory <byte> rebind, out RecipientKeyIdentifier decoded)
 {
     Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
 }
Example #6
0
 public void ResetMemory(ReadOnlyMemory <byte> readOnlyMemory)
 {
     _mem = readOnlyMemory;
     _pos = 0;
 }
Example #7
0
        public async ValueTask InitializeAsync(CancellationToken cancel)
        {
            await _underlying.InitializeAsync(cancel).ConfigureAwait(false);

            try
            {
                // The server waits for the client's upgrade request, the client sends the upgrade request.
                if (!_incoming)
                {
                    // Compose the upgrade request.
                    var sb = new StringBuilder();
                    sb.Append("GET " + _resource + " HTTP/1.1\r\n");
                    sb.Append("Host: " + _host + "\r\n");
                    sb.Append("Upgrade: websocket\r\n");
                    sb.Append("Connection: Upgrade\r\n");
                    sb.Append("Sec-WebSocket-Protocol: " + IceProtocol + "\r\n");
                    sb.Append("Sec-WebSocket-Version: 13\r\n");
                    sb.Append("Sec-WebSocket-Key: ");

                    // The value for Sec-WebSocket-Key is a 16-byte random number, encoded with Base64.
                    byte[] key = new byte[16];
                    _rand.NextBytes(key);
                    _key = Convert.ToBase64String(key);
                    sb.Append(_key + "\r\n\r\n"); // EOM
                    byte[] data = _utf8.GetBytes(sb.ToString());
                    _sendBuffer.Add(data);

                    await _underlying.SendAsync(_sendBuffer, cancel).ConfigureAwait(false);
                }
                _sendBuffer.Clear();

                // Try to read the client's upgrade request or the server's response.
                var httpBuffer = new ArraySegment<byte>();
                while (true)
                {
                    ReadOnlyMemory<byte> buffer = await _underlying.ReceiveAsync(0, cancel).ConfigureAwait(false);
                    if (httpBuffer.Count + buffer.Length > _communicator.IncomingFrameSizeMax)
                    {
                        throw new InvalidDataException(
                            "WebSocket frame size is greater than the configured IncomingFrameSizeMax value");
                    }

                    ArraySegment<byte> tmpBuffer = new byte[httpBuffer.Count + buffer.Length];
                    if (httpBuffer.Count > 0)
                    {
                        httpBuffer.CopyTo(tmpBuffer);
                    }
                    buffer.CopyTo(tmpBuffer.Slice(httpBuffer.Count));
                    httpBuffer = tmpBuffer;

                    // Check if we have enough data for a complete frame.
                    int endPos = HttpParser.IsCompleteMessage(httpBuffer);
                    if (endPos != -1)
                    {
                        // Add back the un-consumed data to the buffer.
                        _underlying.Rewind(httpBuffer.Count - endPos);
                        httpBuffer = httpBuffer.Slice(0, endPos);
                        break; // Done
                    }
                }

                try
                {
                    if (_parser.Parse(httpBuffer))
                    {
                        if (_incoming)
                        {
                            (bool addProtocol, string key) = ReadUpgradeRequest();

                            // Compose the response.
                            var sb = new StringBuilder();
                            sb.Append("HTTP/1.1 101 Switching Protocols\r\n");
                            sb.Append("Upgrade: websocket\r\n");
                            sb.Append("Connection: Upgrade\r\n");
                            if (addProtocol)
                            {
                                sb.Append($"Sec-WebSocket-Protocol: {IceProtocol}\r\n");
                            }

                            // The response includes:
                            //
                            // "A |Sec-WebSocket-Accept| header field.  The value of this header field is constructed
                            // by concatenating /key/, defined above in step 4 in Section 4.2.2, with the string
                            // "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", taking the SHA-1 hash of this concatenated value
                            // to obtain a 20-byte value and base64-encoding (see Section 4 of [RFC4648]) this 20-byte
                            // hash.
                            sb.Append("Sec-WebSocket-Accept: ");
                            string input = key + WsUUID;
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
                            using var sha1 = SHA1.Create();
                            byte[] hash = sha1.ComputeHash(_utf8.GetBytes(input));
#pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms
                            sb.Append(Convert.ToBase64String(hash) + "\r\n" + "\r\n"); // EOM

                            Debug.Assert(_sendBuffer.Count == 0);
                            byte[] data = _utf8.GetBytes(sb.ToString());
                            _sendBuffer.Add(data);
                            await _underlying.SendAsync(_sendBuffer, cancel).ConfigureAwait(false);
                            _sendBuffer.Clear();
                        }
                        else
                        {
                            ReadUpgradeResponse();
                        }
                    }
                    else
                    {
                        throw new InvalidDataException("incomplete WebSocket request frame");
                    }
                }
                catch (WebSocketException ex)
                {
                    throw new InvalidDataException(ex.Message, ex);
                }
            }
            catch (Exception ex)
            {
                if (_communicator.TraceLevels.Transport >= 2)
                {
                    _communicator.Logger.Trace(_communicator.TraceLevels.TransportCategory,
                        $"{_transportName} connection HTTP upgrade request failed\n{this}\n{ex}");
                }
                throw;
            }

            if (_communicator.TraceLevels.Transport >= 1)
            {
                if (_incoming)
                {
                    _communicator.Logger.Trace(_communicator.TraceLevels.TransportCategory,
                        $"accepted {_transportName} connection HTTP upgrade request\n{this}");
                }
                else
                {
                    _communicator.Logger.Trace(_communicator.TraceLevels.TransportCategory,
                        $"{_transportName} connection HTTP upgrade request accepted\n{this}");
                }
            }
        }
        public Utf8FileReader(string fileName, int initialBufferSize = 0, ReadOnlyMemory <byte>?whiteSpaces = null, ReadOnlyMemory <byte>?lineSeparators = null)
        {
            _stream         = LightFileStream.OpenRead(fileName);
            _whiteSpaces    = whiteSpaces ?? DefaultWhiteSpaces;
            _lineSeparators = lineSeparators ?? DefaultLineSeparators;

            _buffer        = new Buffer <byte>(initialBufferSize);
            _lockedStart   = -1;
            _bufferedStart = 0;
            _bufferedEnd   = 0;
            _endOfStream   = false;
        }
 private async ValueTask <(Dictionary <TInnerKey, TValue> Results, CacheGetManyStats CacheStats)> GetFromCache(
     TParams parameters, TOuterKey outerKey, ReadOnlyMemory <TInnerKey> innerKeys)
 {
     if (!_cacheEnabled)
     {
         return(default);
Example #10
0
 private void WriteBuffer(PipeWriter writer, ReadOnlyMemory <byte> buffer)
 {
     CheckChannelOpen();
     writer.Write(buffer.Span);
 }
Example #11
0
 /// <summary>Creates a <see cref="Memory{T}"/> from a <see cref="ReadOnlyMemory{T}"/>.</summary>
 /// <param name="memory">The <see cref="ReadOnlyMemory{T}"/>.</param>
 /// <returns>A <see cref="Memory{T}"/> representing the same memory as the <see cref="ReadOnlyMemory{T}"/>, but writable.</returns>
 /// <remarks>
 /// <see cref="AsMemory{T}(ReadOnlyMemory{T})"/> must be used with extreme caution.  <see cref="ReadOnlyMemory{T}"/> is used
 /// to represent immutable data and other memory that is not meant to be written to; <see cref="Memory{T}"/> instances created
 /// by <see cref="AsMemory{T}(ReadOnlyMemory{T})"/> should not be written to.  The method exists to enable variables typed
 /// as <see cref="Memory{T}"/> but only used for reading to store a <see cref="ReadOnlyMemory{T}"/>.
 /// </remarks>
 public static Memory <T> AsMemory <T>(ReadOnlyMemory <T> memory) =>
 Unsafe.As <ReadOnlyMemory <T>, Memory <T> >(ref memory);
Example #12
0
 public IntValueNode WithValue(ReadOnlyMemory<byte> value)
 {
     return new IntValueNode(Location, value);
 }
Example #13
0
 public IntValueNode(ReadOnlyMemory<byte> value)
     : this(null, value)
 {
 }
 public static object?FromBytes(this ReadOnlyMemory <byte> bytes, Type type,
                                MessagePackSerializerOptions?options = null, CancellationToken cancellationToken = default) =>
 MessagePackHelper.FromBytes(type, bytes, options, cancellationToken);
        /// <summary>
        /// Writes to response.
        /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="result">Whether or not it was implicitly handled by ServiceStack's built-in handlers.</param>
        /// <param name="defaultAction">The default action.</param>
        /// <param name="request">The serialization context.</param>
        /// <param name="bodyPrefix">Add prefix to response body if any</param>
        /// <param name="bodySuffix">Add suffix to response body if any</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <bool> WriteToResponse(this IResponse response, object result, StreamSerializerDelegateAsync defaultAction, IRequest request, byte[] bodyPrefix, byte[] bodySuffix, CancellationToken token = default(CancellationToken))
        {
            using (Profiler.Current.Step("Writing to Response"))
            {
                var  defaultContentType = request.ResponseContentType;
                var  disposableResult   = result as IDisposable;
                bool flushAsync         = false;

                try
                {
                    if (result == null)
                    {
                        response.EndRequestWithNoContent();
                        return(true);
                    }

                    ApplyGlobalResponseHeaders(response);

                    IDisposable resultScope = null;


                    if (result is Exception)
                    {
                        if (response.Request.Items.TryGetValue(Keywords.ErrorView, out var oErrorView))
                        {
                            response.Request.Items[Keywords.View] = oErrorView;
                        }
                    }

                    var httpResult = result as IHttpResult;
                    if (httpResult != null)
                    {
                        if (httpResult.ResultScope != null)
                        {
                            resultScope = httpResult.ResultScope();
                        }

                        if (httpResult.RequestContext == null)
                        {
                            httpResult.RequestContext = request;
                        }

                        var paddingLength = bodyPrefix?.Length ?? 0;
                        if (bodySuffix != null)
                        {
                            paddingLength += bodySuffix.Length;
                        }

                        httpResult.PaddingLength = paddingLength;

                        if (httpResult is IHttpError httpError)
                        {
                            response.Dto = httpError.CreateErrorResponse();
                            if (await response.HandleCustomErrorHandler(request, defaultContentType, httpError.Status, response.Dto, httpError as Exception))
                            {
                                return(true);
                            }
                        }

                        response.Dto ??= httpResult.GetDto();

                        if (!response.HasStarted)
                        {
                            response.StatusCode        = httpResult.Status;
                            response.StatusDescription = (httpResult.StatusDescription ?? httpResult.StatusCode.ToString()).Localize(request);

                            if (string.IsNullOrEmpty(httpResult.ContentType))
                            {
                                httpResult.ContentType = defaultContentType;
                            }
                            response.ContentType = httpResult.ContentType;

                            if (httpResult.Cookies != null)
                            {
                                foreach (var cookie in httpResult.Cookies)
                                {
                                    response.SetCookie(cookie);
                                }
                            }
                        }
                    }
                    else
                    {
                        response.Dto = result;
                    }

                    var config = HostContext.Config;
                    if (!response.HasStarted)
                    {
                        /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
                        if (result is IHasOptions responseOptions)
                        {
                            //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
                            const string reservedOptions = ".";

                            foreach (var responseHeaders in responseOptions.Options)
                            {
                                if (responseHeaders.Key.Contains(reservedOptions))
                                {
                                    continue;
                                }
                                if (responseHeaders.Key == HttpHeaders.ContentLength)
                                {
                                    response.SetContentLength(long.Parse(responseHeaders.Value));
                                    continue;
                                }

                                if (responseHeaders.Key.EqualsIgnoreCase(HttpHeaders.ContentType))
                                {
                                    response.ContentType = responseHeaders.Value;
                                    continue;
                                }

                                if (Log.IsDebugEnabled)
                                {
                                    Log.Debug($"Setting Custom HTTP Header: {responseHeaders.Key}: {responseHeaders.Value}");
                                }

                                response.AddHeader(responseHeaders.Key, responseHeaders.Value);
                            }
                        }

                        //ContentType='text/html' is the default for a HttpResponse
                        //Do not override if another has been set
                        if (response.ContentType == null || response.ContentType == MimeTypes.Html)
                        {
                            response.ContentType = defaultContentType == (config.DefaultContentType ?? MimeTypes.Html) && result is byte[]
                                ? MimeTypes.Binary
                                : defaultContentType;
                        }
                        if (bodyPrefix != null && response.ContentType.IndexOf(MimeTypes.Json, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            response.ContentType = MimeTypes.JavaScript;
                        }

                        if (config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType))
                        {
                            response.ContentType += ContentFormat.Utf8Suffix;
                        }
                    }

                    var jsconfig = config.AllowJsConfig ? request.QueryString[Keywords.JsConfig] : null;
                    using (resultScope)
                        using (jsconfig != null ? JsConfig.CreateScope(jsconfig) : null)
                        {
                            if (WriteToOutputStream(response, result, bodyPrefix, bodySuffix))
                            {
                                await response.FlushAsync(token); //required for Compression

                                return(true);
                            }

#if NETFX || NET472
                            //JsConfigScope uses ThreadStatic in .NET v4.5 so avoid async thread hops by writing sync to MemoryStream
                            if (resultScope != null || jsconfig != null)
                            {
                                response.UseBufferedStream = true;
                            }
#endif

                            if (await WriteToOutputStreamAsync(response, result, bodyPrefix, bodySuffix, token))
                            {
                                flushAsync = true;
                                return(true);
                            }

                            if (httpResult != null)
                            {
                                result = httpResult.Response;
                            }

                            ReadOnlyMemory <byte>?uf8Bytes = null;
                            if (result is string responseText)
                            {
                                uf8Bytes = MemoryProvider.Instance.ToUtf8(responseText.AsSpan());
                            }
                            else if (result is ReadOnlyMemory <char> rom)
                            {
                                uf8Bytes = MemoryProvider.Instance.ToUtf8(rom.Span);
                            }

                            if (uf8Bytes != null)
                            {
                                var len = (bodyPrefix?.Length).GetValueOrDefault() +
                                          uf8Bytes.Value.Length +
                                          (bodySuffix?.Length).GetValueOrDefault();

                                response.SetContentLength(len);

                                if (response.ContentType == null || response.ContentType == MimeTypes.Html)
                                {
                                    response.ContentType = defaultContentType;
                                }

                                //retain behavior with ASP.NET's response.Write(string)
                                if (response.ContentType.IndexOf(';') == -1)
                                {
                                    response.ContentType += ContentFormat.Utf8Suffix;
                                }

                                if (bodyPrefix != null)
                                {
                                    await response.OutputStream.WriteAsync(bodyPrefix, token);
                                }

                                await response.OutputStream.WriteAsync(uf8Bytes.Value, token);

                                if (bodySuffix != null)
                                {
                                    await response.OutputStream.WriteAsync(bodySuffix, token);
                                }

                                return(true);
                            }

                            if (defaultAction == null)
                            {
                                throw new ArgumentNullException(nameof(defaultAction),
                                                                $@"As result '{(result != null ? result.GetType().GetOperationName() : "")}' is not a supported responseType, a defaultAction must be supplied");
                            }

                            if (bodyPrefix != null)
                            {
                                await response.OutputStream.WriteAsync(bodyPrefix, token);
                            }

                            if (result != null)
                            {
                                await defaultAction(request, result, response.OutputStream);
                            }

                            if (bodySuffix != null)
                            {
                                await response.OutputStream.WriteAsync(bodySuffix, token);
                            }
                        }

                    return(false);
                }
                catch (Exception originalEx)
                {
                    //.NET Core prohibits some status codes from having a body
                    if (originalEx is InvalidOperationException invalidEx)
                    {
                        Log.Error(invalidEx.Message, invalidEx);
                        try
                        {
                            flushAsync = false;
                            await response.OutputStream.FlushAsync(token); // Prevent hanging clients
                        }
                        catch (Exception flushEx) { Log.Error("response.OutputStream.FlushAsync()", flushEx); }
                    }

                    await HandleResponseWriteException(originalEx, request, response, defaultContentType);

                    return(true);
                }
                finally
                {
                    if (flushAsync) // move async Thread Hop to outside JsConfigScope so .NET v4.5 disposes same scope
                    {
                        try
                        {
                            await response.FlushAsync(token);
                        }
                        catch (Exception flushEx) { Log.Error("response.FlushAsync()", flushEx); }
                    }
                    disposableResult?.Dispose();
                    await response.EndRequestAsync(skipHeaders : true);
                }
            }
        }
Example #16
0
 public static async ValueTask SendAsync(this PipeWriter writer, ReadOnlyMemory <byte> buffer, CancellationToken cancellationToken = default)
 {
     await writer.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
 }
Example #17
0
 public ReadOnlyMemoryReader(ReadOnlyMemory <byte> readOnlyMemory)
 {
     ; ResetMemory(readOnlyMemory);
 }
 /// <summary>
 /// Creates a new message from the specified payload.
 /// </summary>
 /// <param name="body">The payload of the message in bytes</param>
 internal ServiceBusReceivedMessage(ReadOnlyMemory<byte> body) :
     base(body)
 {
 }
Example #19
0
 public override Task WriteAsync(ReadOnlyMemory <byte> source, CancellationToken cancellationToken = default(CancellationToken))
 {
     _position += source.Length;
     return(_stream.WriteAsync(source, cancellationToken));
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="body"></param>
 /// <returns></returns>
 public static ServiceBusReceivedMessage Create(ReadOnlyMemory<byte> body) =>
     new ServiceBusReceivedMessage(body);
        protected override void CheckLabel(RoleMappedData data)
        {
            Contracts.AssertValue(data);
            // REVIEW: For floating point labels, this will make a pass over the data.
            // Should we instead leverage the pass made by the LBFGS base class? Ideally, it wouldn't
            // make a pass over the data...
            data.CheckMultiClassLabel(out _numClasses);

            // Initialize prior counts.
            _prior = new Double[_numClasses];

            // Try to get the label key values metedata.
            var schema            = data.Data.Schema;
            var labelIdx          = data.Schema.Label.Index;
            var labelMetadataType = schema.GetMetadataTypeOrNull(MetadataUtils.Kinds.KeyValues, labelIdx);

            if (labelMetadataType == null || !labelMetadataType.IsKnownSizeVector || !labelMetadataType.ItemType.IsText ||
                labelMetadataType.VectorSize != _numClasses)
            {
                _labelNames = null;
                return;
            }

            VBuffer <ReadOnlyMemory <char> > labelNames = default;

            schema.GetMetadata(MetadataUtils.Kinds.KeyValues, labelIdx, ref labelNames);

            // If label names is not dense or contain NA or default value, then it follows that
            // at least one class does not have a valid name for its label. If the label names we
            // try to get from the metadata are not unique, we may also not use them in model summary.
            // In both cases we set _labelNames to null and use the "Class_n", where n is the class number
            // for model summary saving instead.
            if (!labelNames.IsDense)
            {
                _labelNames = null;
                return;
            }

            _labelNames = new string[_numClasses];
            ReadOnlyMemory <char>[] values = labelNames.Values;

            // This hashset is used to verify the uniqueness of label names.
            HashSet <string> labelNamesSet = new HashSet <string>();

            for (int i = 0; i < _numClasses; i++)
            {
                ReadOnlyMemory <char> value = values[i];
                if (value.IsEmpty)
                {
                    _labelNames = null;
                    break;
                }

                var vs = values[i].ToString();
                if (!labelNamesSet.Add(vs))
                {
                    _labelNames = null;
                    break;
                }

                _labelNames[i] = vs;

                Contracts.Assert(!string.IsNullOrEmpty(_labelNames[i]));
            }

            Contracts.Assert(_labelNames == null || _labelNames.Length == _numClasses);
        }
 public static ValueTask <int> SendAsync(this Socket socket, ReadOnlyMemory <byte> buffer, SocketFlags socketFlags, CancellationToken token)
 => SocketTaskExtensions.SendAsync(socket, buffer, socketFlags, token);
Example #23
0
 internal static RecipientKeyIdentifier Decode(ReadOnlyMemory <byte> encoded, AsnEncodingRules ruleSet)
 {
     return(Decode(Asn1Tag.Sequence, encoded, ruleSet));
 }
Example #24
0
 internal static DssParms Decode(ReadOnlyMemory <byte> encoded, AsnEncodingRules ruleSet)
 {
     return(Decode(Asn1Tag.Sequence, encoded, ruleSet));
 }
Example #25
0
        private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory <byte> rebind, out RecipientKeyIdentifier decoded)
        {
            decoded = default;
            AsnValueReader      sequenceReader = reader.ReadSequence(expectedTag);
            ReadOnlySpan <byte> rebindSpan     = rebind.Span;
            int offset;
            ReadOnlySpan <byte> tmpSpan;


            if (sequenceReader.TryReadPrimitiveOctetString(out tmpSpan))
            {
                decoded.SubjectKeyIdentifier = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
            }
            else
            {
                decoded.SubjectKeyIdentifier = sequenceReader.ReadOctetString();
            }


            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.GeneralizedTime))
            {
                decoded.Date = sequenceReader.ReadGeneralizedTime();
            }


            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(Asn1Tag.Sequence))
            {
                System.Security.Cryptography.Pkcs.Asn1.OtherKeyAttributeAsn tmpOther;
                System.Security.Cryptography.Pkcs.Asn1.OtherKeyAttributeAsn.Decode(ref sequenceReader, rebind, out tmpOther);
                decoded.Other = tmpOther;
            }


            sequenceReader.ThrowIfNotEmpty();
        }
Example #26
0
        public static byte[] Percent_Decode(ReadOnlyMemory <byte> input)
        {/* Docs: https://url.spec.whatwg.org/#percent-decode */
            DataConsumer <byte> Stream = new DataConsumer <byte>(input, byte.MinValue);
            /* Create a list of memory chunks that make up the final string */
            ulong newLength  = 0;
            ulong?chunkStart = null;
            ulong chunkCount = 0;
            var   chunks     = new LinkedList <Tuple <ReadOnlyMemory <byte>, byte?> >();

            while (!Stream.atEnd)
            {
                EFilterResult filterResult = EFilterResult.FILTER_ACCEPT;
                byte?         bytePoint    = null;

                if (Stream.Next == CHAR_PERCENT && Is_Ascii_Hex_Digit((char)Stream.NextNext) && Is_Ascii_Hex_Digit((char)Stream.NextNextNext))
                {
                    filterResult = EFilterResult.FILTER_SKIP;
                    uint low  = (uint)Ascii_Hex_To_Value((char)Stream.NextNext);
                    uint high = (uint)Ascii_Hex_To_Value((char)Stream.NextNextNext);
                    bytePoint = (byte)(low | (high >> 4));
                    Stream.Consume(2);
                    break;
                }

                /* When filter result:
                 * ACCEPT: Char should be included in chunk
                 * SKIP: Char should not be included in chunk, if at chunk-start shift chunk-start past char, otherwise end chunk
                 * REJECT: Char should not be included in chunk, current chunk ends
                 */
                bool end_chunk = false;
                switch (filterResult)
                {
                case EFilterResult.FILTER_ACCEPT:    // Char should be included in the chunk
                {
                    if (!chunkStart.HasValue)
                    {
                        chunkStart = Stream.LongPosition;                              /* Start new chunk (if one isnt started yet) */
                    }
                }
                break;

                case EFilterResult.FILTER_REJECT:    // Char should not be included in chunk, current chunk ends
                {
                    end_chunk = true;
                }
                break;

                case EFilterResult.FILTER_SKIP:    // Char should not be included in chunk, if at chunk-start shift chunk-start past char, otherwise end chunk
                {
                    if (!chunkStart.HasValue)
                    {
                        chunkStart = Stream.LongPosition + 1;        /* At chunk-start */
                    }
                    else
                    {
                        end_chunk = true;
                    }
                }
                break;
                }

                if (end_chunk || Stream.Remaining <= 1)
                {
                    if (!chunkStart.HasValue)
                    {
                        chunkStart = Stream.LongPosition;
                    }

                    /* Push new chunk to our list */
                    var chunkSize = Stream.LongPosition - chunkStart.Value;
                    var Mem       = Stream.AsMemory().Slice((int)chunkStart.Value, (int)chunkSize);
                    var chunk     = new Tuple <ReadOnlyMemory <byte>, byte?>(Mem, bytePoint);
                    chunks.AddLast(chunk);

                    chunkCount++;
                    chunkStart = null;
                    newLength += chunkSize;
                    /* If we actually decoded a byte then account for it in the newLength */
                    if (filterResult != EFilterResult.FILTER_ACCEPT)
                    {
                        newLength++;
                    }
                }

                Stream.Consume();
            }

            /* Compile the string */
            var           dataPtr = new byte[newLength];
            Memory <byte> data    = new Memory <byte>(dataPtr);

            ulong index = 0;

            foreach (var tpl in chunks)
            {
                var chunk = tpl.Item1;
                /* Copy chunk data */
                chunk.CopyTo(data.Slice((int)index));
                index += (ulong)chunk.Length;

                if (tpl.Item2.HasValue)
                {
                    data.Span[(int)index] = tpl.Item2.Value;
                    index++;
                }
            }

            return(dataPtr);
        }
Example #27
0
 internal static EnvelopedDataAsn Decode(ReadOnlyMemory <byte> encoded, AsnEncodingRules ruleSet)
 {
     return(Decode(Asn1Tag.Sequence, encoded, ruleSet));
 }
Example #28
0
        public static byte[] String_Percent_Decode(ReadOnlyMemory <char> input)
        {/* Docs: https://url.spec.whatwg.org/#string-percent-decode */
            var bytes = Encoding.UTF8.GetBytes(input.ToArray());

            return(Percent_Decode(bytes));
        }
Example #29
0
        private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory <byte> rebind, out EnvelopedDataAsn decoded)
        {
            decoded = default;
            AsnValueReader sequenceReader = reader.ReadSequence(expectedTag);
            AsnValueReader collectionReader;


            if (!sequenceReader.TryReadInt32(out decoded.Version))
            {
                sequenceReader.ThrowIfNotEmpty();
            }


            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0)))
            {
                System.Security.Cryptography.Pkcs.Asn1.OriginatorInfoAsn tmpOriginatorInfo;
                System.Security.Cryptography.Pkcs.Asn1.OriginatorInfoAsn.Decode(ref sequenceReader, new Asn1Tag(TagClass.ContextSpecific, 0), rebind, out tmpOriginatorInfo);
                decoded.OriginatorInfo = tmpOriginatorInfo;
            }


            // Decode SEQUENCE OF for RecipientInfos
            {
                collectionReader = sequenceReader.ReadSetOf();
                var tmpList = new List <System.Security.Cryptography.Pkcs.Asn1.RecipientInfoAsn>();
                System.Security.Cryptography.Pkcs.Asn1.RecipientInfoAsn tmpItem;

                while (collectionReader.HasData)
                {
                    System.Security.Cryptography.Pkcs.Asn1.RecipientInfoAsn.Decode(ref collectionReader, rebind, out tmpItem);
                    tmpList.Add(tmpItem);
                }

                decoded.RecipientInfos = tmpList.ToArray();
            }

            System.Security.Cryptography.Asn1.Pkcs7.EncryptedContentInfoAsn.Decode(ref sequenceReader, rebind, out decoded.EncryptedContentInfo);

            if (sequenceReader.HasData && sequenceReader.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 1)))
            {
                // Decode SEQUENCE OF for UnprotectedAttributes
                {
                    collectionReader = sequenceReader.ReadSetOf(new Asn1Tag(TagClass.ContextSpecific, 1));
                    var tmpList = new List <System.Security.Cryptography.Asn1.AttributeAsn>();
                    System.Security.Cryptography.Asn1.AttributeAsn tmpItem;

                    while (collectionReader.HasData)
                    {
                        System.Security.Cryptography.Asn1.AttributeAsn.Decode(ref collectionReader, rebind, out tmpItem);
                        tmpList.Add(tmpItem);
                    }

                    decoded.UnprotectedAttributes = tmpList.ToArray();
                }
            }


            sequenceReader.ThrowIfNotEmpty();
        }
Example #30
0
 internal static void FromECPrivateKey(
     ReadOnlyMemory <byte> keyData,
     in AlgorithmIdentifierAsn algId,