Esempio n. 1
1
        internal void HandleTcpReceived(uint sequenceNumber, ArraySegment<byte> data)
        {
            var dataPosition = SequenceNumberToBytesReceived(sequenceNumber);
            if (dataPosition == BytesReceived)
            {
                OnDataReceived(data);
                BytesReceived += data.Count;
            }
            else
            {
                var dataArray = new byte[data.Count];
                Array.Copy(data.Array, data.Offset, dataArray, 0, data.Count);
                if (!_bufferedPackets.ContainsKey(dataPosition) || _bufferedPackets[dataPosition].Length < dataArray.Length)
                {
                    _bufferedPackets[dataPosition] = dataArray;
                }
            }

            long firstBufferedPosition;
            while (_bufferedPackets.Any() && ((firstBufferedPosition = _bufferedPackets.Keys.First()) <= BytesReceived))
            {
                var dataArray = _bufferedPackets[firstBufferedPosition];
                _bufferedPackets.Remove(firstBufferedPosition);

                var alreadyReceivedBytes = BytesReceived - firstBufferedPosition;
                Debug.Assert(alreadyReceivedBytes >= 0);

                if (alreadyReceivedBytes < dataArray.Length)
                {
                    var count = dataArray.Length - alreadyReceivedBytes;
                    OnDataReceived(new ArraySegment<byte>(dataArray, (int)alreadyReceivedBytes, (int)count));
                    BytesReceived += count;
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// constructor of SecsMessage
        /// </summary>
        /// <param name="stream">message stream number</param>
        /// <param name="function">message function number</param>
        /// <param name="replyExpected">expect reply message</param>
        /// <param name="name"></param>
        /// <param name="item">root item</param>
        public SecsMessage(byte stream, byte function, bool replyExpected = true, string name = null, Item item = null)
        {
            if (stream > 0x7F)
                throw new ArgumentOutOfRangeException(nameof(stream), stream, "Stream number must be less than 127");

            S = stream;
            F = function;
            Name = name;
            ReplyExpected = replyExpected;
            SecsItem = item;
            RawDatas = new Lazy<List<ArraySegment<byte>>>(() =>
            {
                if (SecsItem == null)
                    return emptyMsgDatas;

                var result = new List<ArraySegment<byte>> {
                    default(ArraySegment<byte>),    // total length
                    new ArraySegment<byte>(Array.Empty<byte>())     // header
                    // item
                };

                uint length = 10 + SecsItem.EncodeTo(result); // total length = item + header

                byte[] msgLengthByte = BitConverter.GetBytes(length);
                Array.Reverse(msgLengthByte);
                result[0] = new ArraySegment<byte>(msgLengthByte);

                return result;
            });
        }
Esempio n. 3
0
        public virtual Task SendAsync(ArraySegment<byte> message, WebSocketMessageType messageType, bool endOfMessage = true)
        {
            if (WebSocket.State != WebSocketState.Open)
            {
                return TaskAsyncHelper.Empty;
            }

            var sendContext = new SendContext(this, message, messageType, endOfMessage);

            return _sendQueue.Enqueue(async state =>
            {
                var context = (SendContext)state;

                if (context.Handler.WebSocket.State != WebSocketState.Open)
                {
                    return;
                }

                try
                {
                    await context.Handler.WebSocket.SendAsync(context.Message, context.MessageType, context.EndOfMessage, CancellationToken.None);
                }
                catch (Exception ex)
                {
                    // Swallow exceptions on send
                    Trace.TraceError("Error while sending: " + ex);
                }
            },
            sendContext);
        }
Esempio n. 4
0
		public DnsHeader (ArraySegment<byte> segment)
		{
			if (segment.Count != DnsHeaderLength)
				throw new ArgumentException ("Count must be 12", "segment");

			bytes = segment;
		}
		protected override object DeserializeObject(ArraySegment<byte> value)
		{
			var ds = new NetDataContractSerializer();

			using (var ms = new MemoryStream(value.Array, value.Offset, value.Count))
				return ds.Deserialize(ms);
		}
        public void Encrypt_KnownKey()
        {
            // Arrange
            Secret kdk = new Secret(Encoding.UTF8.GetBytes("master key"));
            GcmAuthenticatedEncryptor encryptor = new GcmAuthenticatedEncryptor(kdk, CachedAlgorithmHandles.AES_GCM, symmetricAlgorithmKeySizeInBytes: 128 / 8, genRandom: new SequentialGenRandom());
            ArraySegment<byte> plaintext = new ArraySegment<byte>(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, 2, 3);
            ArraySegment<byte> aad = new ArraySegment<byte>(new byte[] { 7, 6, 5, 4, 3, 2, 1, 0 }, 1, 4);

            // Act
            byte[] retVal = encryptor.Encrypt(
                plaintext: plaintext,
                additionalAuthenticatedData: aad,
                preBufferSize: 3,
                postBufferSize: 4);

            // Assert

            // retVal := 00 00 00 (preBuffer)
            //         | 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F (keyModifier)
            //         | 10 11 12 13 14 15 16 17 18 19 1A 1B (nonce)
            //         | 43 B6 91 (encryptedData)
            //         | 8D 0D 66 D9 A1 D9 44 2D 5D 8E 41 DA 39 60 9C E8 (authTag)
            //         | 00 00 00 00 (postBuffer)

            string retValAsString = Convert.ToBase64String(retVal);
            Assert.Equal("AAAAAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaG0O2kY0NZtmh2UQtXY5B2jlgnOgAAAAA", retValAsString);
        }
Esempio n. 7
0
        /// <summary>
        /// Creates a new Secret from the provided input value, where the input value
        /// is specified as an array segment.
        /// </summary>
        public Secret(ArraySegment<byte> value)
        {
            value.Validate();

            _localAllocHandle = Protect(value);
            _plaintextLength = (uint)value.Count;
        }
Esempio n. 8
0
        static int MinimumSubsequenceProduct(ArraySegment<int> Sequence)
        {
            if (Sequence.Count == 1)
                return Sequence.Array[Sequence.Offset];
            int Middle = Sequence.Count / 2;
            int LeftProduct = MinimumSubsequenceProduct(new ArraySegment<int>(Sequence.Array, Sequence.Offset, Middle));
            int RightProduct = MinimumSubsequenceProduct(new ArraySegment<int>(Sequence.Array, Sequence.Offset + Middle, Middle));

            int MiddleProduct = 1;
            int MiddleLeftProduct = 1;
            int TempLeftProduct = 1;
            for (int i = Middle; i >= Sequence.Offset; i--) {
                TempLeftProduct *= Sequence.Array[i];
                if (TempLeftProduct < MiddleLeftProduct)
                    MiddleLeftProduct = TempLeftProduct;
            }

            int MiddleRightProduct = 1;
            int TempRightProduct = 1;
            for (int i = Middle + 1; i < Sequence.Offset + Sequence.Count; i++) {
                TempRightProduct *= Sequence.Array[i];
                if (TempRightProduct < MiddleRightProduct)
                    MiddleRightProduct = TempRightProduct;
            }
            MiddleProduct = MiddleLeftProduct * MiddleRightProduct;
            return Math.Min(Math.Min(LeftProduct, MiddleProduct), RightProduct);
        }
        public ArraySegment<byte> CopyToNextSegment(SocketAsyncEventArgs sourceEventArgs)
        {
            Byte[] array;
            int offset;
            int count = sourceEventArgs.BytesTransferred;
            Locate(count, out array, out offset);
            var data = new ArraySegment<byte>(array, offset, count);

            if (sourceEventArgs.Buffer != null)
            {
                Buffer.BlockCopy(sourceEventArgs.Buffer, sourceEventArgs.Offset, array, offset, count);
            }
            else if (sourceEventArgs.BufferList != null)
            {
                int currentOffset = offset;
                int copiedCount = 0;
                foreach (var item in sourceEventArgs.BufferList)
                {
                    int willcopyCount = count - copiedCount;
                    int copyingCount = willcopyCount > item.Count ? item.Count : willcopyCount;
                    Buffer.BlockCopy(item.Array, item.Offset, array, currentOffset, copyingCount);
                    copiedCount = copiedCount + copiedCount;
                    currentOffset = copiedCount + offset;
                }
            }
            return data;
        }
Esempio n. 10
0
 // Outgoing
 public SettingsPair(SettingsFlags flags, SettingsIds id, int value)
 {
     _bufferSegment = new ArraySegment<byte>(new byte[PairSize], 0, PairSize);
     Flags = flags;
     Id = id;
     Value = value;
 }
Esempio n. 11
0
        private static async Task HandleWebSocketsAsync(HttpContext context, Func<Task> next)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await next();
                return;
            }

            var hub = context.RequestServices.GetRequiredService<MessageHub>();

            using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
            {
                try
                {
                    await hub.SubscribeAsync(webSocket);

                    var buffer = new ArraySegment<byte>(new byte[4096]);

                    while (webSocket?.State == WebSocketState.Open)
                    {
                        await webSocket.ReceiveAsync(buffer, CancellationToken.None);
                    }
                }
                finally
                {
                    await hub.UnsubscribeAsync(webSocket);
                }
            }
        }
        /// <inheritdoc />
        public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
        {
            // Treat the alternate as native
            if (IsAlternateContent(contentType))
            {
                // HACK: Should see if we have a declr or some xml
               contentType = this.contentType;
            }

            var msgContents = new byte[buffer.Count];
            Array.Copy(buffer.Array, buffer.Offset, msgContents, 0, msgContents.Length);
            bufferManager.ReturnBuffer(buffer.Array);

            // Most interoperable to include the xml declaration
            writerSettings.OmitXmlDeclaration = false;

            // Save the encoding for when we write the response
            writerSettings.Encoding = msgContents.GetEncoding(contentType);
            var xmlDeclEncoding = msgContents.GetXmlDeclEncoding(writerSettings.Encoding);

            // Check if the two encodings align
            if (xmlDeclEncoding != null && xmlDeclEncoding.WebName == writerSettings.Encoding.WebName)
            {
                // Need to recode
                msgContents = Encoding.Convert(writerSettings.Encoding, xmlDeclEncoding, msgContents);
            }

            var stream = new MemoryStream(msgContents);
            return ReadMessage(stream, int.MaxValue);
        }
        internal void SetUnmanagedStructures(IList<ArraySegment<byte>> buffers)
        {
            // Fill in Buffer Array structure that will be used for our send/recv Buffer.
            // Make sure we don't let the app mess up the buffer array enough to cause
            // corruption.
            int count = buffers.Count;
            ArraySegment<byte>[] buffersCopy = new ArraySegment<byte>[count];

            for (int i = 0; i < count; i++)
            {
                buffersCopy[i] = buffers[i];
                RangeValidationHelpers.ValidateSegment(buffersCopy[i]);
            }

            _wsaBuffers = new WSABuffer[count];

            object[] objectsToPin = new object[count];
            for (int i = 0; i < count; i++)
            {
                objectsToPin[i] = buffersCopy[i].Array;
            }

            base.SetUnmanagedStructures(objectsToPin);

            for (int i = 0; i < count; i++)
            {
                _wsaBuffers[i].Length = buffersCopy[i].Count;
                _wsaBuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffersCopy[i].Array, buffersCopy[i].Offset);
            }
        }
Esempio n. 14
0
        public static byte[] Handshake(WebSocketHttpRequest request)
        {
            FleckLog.Debug("Building Draft76 Response");

            var builder = new StringBuilder();
            builder.Append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
            builder.Append("Upgrade: WebSocket\r\n");
            builder.Append("Connection: Upgrade\r\n");
            builder.AppendFormat("Sec-WebSocket-Origin: {0}\r\n",  request["Origin"]);
            builder.AppendFormat("Sec-WebSocket-Location: {0}://{1}{2}\r\n", request.Scheme, request["Host"], request.Path);

            if (request.Headers.ContainsKey("Sec-WebSocket-Protocol"))
                builder.AppendFormat("Sec-WebSocket-Protocol: {0}\r\n", request["Sec-WebSocket-Protocol"]);

            builder.Append("\r\n");

            var key1 = request["Sec-WebSocket-Key1"];
            var key2 = request["Sec-WebSocket-Key2"];
            var challenge = new ArraySegment<byte>(request.Bytes, request.Bytes.Length - 8, 8);

            var answerBytes = CalculateAnswerBytes(key1, key2, challenge);

            byte[] byteResponse = Encoding.ASCII.GetBytes(builder.ToString());
            int byteResponseLength = byteResponse.Length;
            Array.Resize(ref byteResponse, byteResponseLength + answerBytes.Length);
            Array.Copy(answerBytes, 0, byteResponse, byteResponseLength, answerBytes.Length);

            return byteResponse;
        }
        public static ReliableDataHeader FromSegment(ArraySegment<byte> segment)
        {
            ushort sequenceNumber = segment.ReadSequenceNumber(SystemHeader.Size);
            ushort payloadSize = (ushort)BitConverter.ToInt16(segment.Array, segment.Offset + SystemHeader.Size + 2);

            return new ReliableDataHeader(sequenceNumber, payloadSize);
        }
        protected override object DeserializeObject(ArraySegment<byte> value) {
            Byte[] buffer;
            if (value.Offset != 0) {
                buffer = new Byte[value.Count];
                Array.Copy(value.Array, value.Offset, buffer, 0, value.Count);
            }
            else {
                buffer = value.Array;
            }

            Boolean isJson = false;
            if (buffer[0] == 123 && buffer[buffer.Length - 1] == 125) {
                isJson = true;
            }
            if (!isJson) {
                var isOrignalObjectByte = buffer.Take(10).Distinct().All(_donetBytes.Contains);
                isJson = !isOrignalObjectByte;
            }

            if (isJson) {
                return JsonDeserialize(buffer);
            }
            else {
                try {
                    return base.DeserializeObject(value);
                }
                catch (SerializationException) {
                    // Log or something
                    return JsonDeserialize(buffer);
                }
            }
        }
 public HeadTailWriteStream(ArraySegment<byte> head, int tailSize = 0)
 {
     _head = head;
     if (tailSize > 0)
         _tail = new ArraySegment<byte>(new byte[tailSize]);
     _size = head.Count + tailSize;
 }
Esempio n. 18
0
        public unsafe bool Read(PooledSocket socket)
        {
            this.StatusCode = -1;

            if (!socket.IsAlive)
                return false;

            var header = new byte[HeaderLength];
            socket.Read(header, 0, header.Length);

            int dataLength, extraLength;

            DeserializeHeader(header, out dataLength, out extraLength);

            if (dataLength > 0)
            {
                var data = new byte[dataLength];
                socket.Read(data, 0, dataLength);

                this.Extra = new ArraySegment<byte>(data, 0, extraLength);
                this.Data = new ArraySegment<byte>(data, extraLength, data.Length - extraLength);
            }

            return this.StatusCode == 0;
        }
        public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, byte[] buffer, int maxMessageSize)
        {
            ArraySegment<byte> arraySegment = new ArraySegment<byte>(buffer);

            WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
            // special-case close messages since they might not have the EOF flag set
            if (receiveResult.MessageType == WebSocketMessageType.Close)
            {
                return new WebSocketMessage(null, WebSocketMessageType.Close);
            }

            if (receiveResult.EndOfMessage)
            {
                // we anticipate that single-fragment messages will be common, so we optimize for them
                switch (receiveResult.MessageType)
                {
                    case WebSocketMessageType.Binary:
                        return new WebSocketMessage(BufferSliceToByteArray(buffer, receiveResult.Count), WebSocketMessageType.Binary);

                    case WebSocketMessageType.Text:
                        return new WebSocketMessage(BufferSliceToString(buffer, receiveResult.Count), WebSocketMessageType.Text);

                    default:
                        throw new Exception("This code path should never be hit.");
                }
            }
            else
            {
                // for multi-fragment messages, we need to coalesce
                ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
                bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                WebSocketMessageType originalMessageType = receiveResult.MessageType;

                while (true)
                {
                    // loop until an error occurs or we see EOF
                    receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
                    if (receiveResult.MessageType != originalMessageType)
                    {
                        throw new InvalidOperationException("Incorrect message type");
                    }

                    bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
                    if (receiveResult.EndOfMessage)
                    {
                        switch (receiveResult.MessageType)
                        {
                            case WebSocketMessageType.Binary:
                                return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);

                            case WebSocketMessageType.Text:
                                return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);

                            default:
                                throw new Exception("This code path should never be hit.");
                        }
                    }
                }
            }
        }
Esempio n. 20
0
        public void BulkReply()
        {
            string reply = "#############$7\r\nmyvalue\r\n~~~~~~~~~~~";
            var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(reply), 13, 13);
            int readed;
            var objResponse = new Redis.Driver.RedisProtocol().FindResponse(null, buffer, out readed);
            Assert.IsNotNull(objResponse);
            Assert.AreEqual(readed, 13);
            Assert.IsTrue(objResponse.Reply is Redis.Driver.BulkReplies);
            Assert.AreEqual("myvalue", Encoding.UTF8.GetString((objResponse.Reply as Redis.Driver.BulkReplies).Payload));

            reply = "!!!$-1\r\n^^^^^^^^^^^^^^^";
            buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(reply), 3, 5);
            objResponse = new Redis.Driver.RedisProtocol().FindResponse(null, buffer, out readed);
            Assert.IsNotNull(objResponse);
            Assert.AreEqual(readed, 5);
            Assert.IsTrue(objResponse.Reply is Redis.Driver.BulkReplies);
            Assert.IsNull((objResponse.Reply as Redis.Driver.BulkReplies).Payload);

            reply = "$5\r\nabc";
            buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(reply), 0, 7);
            objResponse = new Redis.Driver.RedisProtocol().FindResponse(null, buffer, out readed);
            Assert.IsNull(objResponse);
            Assert.AreEqual(readed, 0);
        }
        public static void GetPublicKey(ArraySegment<byte> publicKey, ArraySegment<byte> privateKey)
        {
            if (publicKey.Array == null)
                throw new ArgumentNullException("publicKey.Array");
            if (privateKey.Array == null)
                throw new ArgumentNullException("privateKey.Array");
            if (publicKey.Count != PublicKeySizeInBytes)
                throw new ArgumentException("privateKey.Count must be 32");
            if (privateKey.Count != PrivateKeySizeInBytes)
                throw new ArgumentException("privateKey.Count must be 32");

            // hack: abusing publicKey as temporary storage
            // todo: remove hack
            for (int i = 0; i < 32; i++)
            {
                publicKey.Array[publicKey.Offset + i] = privateKey.Array[privateKey.Offset + i];
            }
            ScalarOperations.sc_clamp(publicKey.Array, publicKey.Offset);

            GroupElementP3 A;
            GroupOperations.ge_scalarmult_base(out A, publicKey.Array, publicKey.Offset);
            FieldElement publicKeyFE;
            EdwardsToMontgomeryX(out publicKeyFE, ref A.Y, ref A.Z);
            FieldOperations.fe_tobytes(publicKey.Array, publicKey.Offset, ref publicKeyFE);
        }
        public byte[] Encrypt(ArraySegment<byte> plaintext, ArraySegment<byte> additionalAuthenticatedData, uint preBufferSize, uint postBufferSize)
        {
            // This wrapper simply converts ArraySegment<byte> to byte* and calls the impl method.

            // Input validation
            plaintext.Validate();
            additionalAuthenticatedData.Validate();

            byte dummy; // used only if plaintext or AAD is empty, since otherwise 'fixed' returns null pointer
            fixed (byte* pbPlaintextArray = plaintext.Array)
            {
                fixed (byte* pbAdditionalAuthenticatedDataArray = additionalAuthenticatedData.Array)
                {
                    try
                    {
                        return EncryptImpl(
                            pbPlaintext: (pbPlaintextArray != null) ? &pbPlaintextArray[plaintext.Offset] : &dummy,
                            cbPlaintext: (uint)plaintext.Count,
                            pbAdditionalAuthenticatedData: (pbAdditionalAuthenticatedDataArray != null) ? &pbAdditionalAuthenticatedDataArray[additionalAuthenticatedData.Offset] : &dummy,
                            cbAdditionalAuthenticatedData: (uint)additionalAuthenticatedData.Count,
                            cbPreBuffer: preBufferSize,
                            cbPostBuffer: postBufferSize);
                    }
                    catch (Exception ex) when (ex.RequiresHomogenization())
                    {
                        // Homogenize to CryptographicException.
                        throw Error.CryptCommon_GenericError(ex);
                    }
                }
            }
        }
Esempio n. 23
0
        private static async Task Listen(Tuple<int, WebSocket> connection)
        {            
            const int maxMsgSize = 1024;
            var webSocket = connection.Item2;
            var buffer = new ArraySegment<byte>(new byte[maxMsgSize]);
            WebSocketReceiveResult result = null;

            do
            {
                logger.LogVerbose("Listen");

                try {
                    result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
                }
                catch(Exception ex)
                {
                    logger.LogVerbose("ReceiveAsync error: {0}", ex.Message);
                    await webSocket.CloseAsync(WebSocketCloseStatus.ProtocolError, "webSocket.ReceiveAsync error", CancellationToken.None);
                    return;
                }                

                GetMessage(connection, result, buffer);
            } while (!result.CloseStatus.HasValue);

            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
		internal ConcateOperation(ConcatenationMode mode, string key, ArraySegment<byte> data)
			: base(mode == ConcatenationMode.Append
					? StoreCommand.Append
					: StoreCommand.Prepend, key, new CacheItem() { Data = data, Flags = 0 }, 0, 0)
		{
			this.mode = mode;
		}
Esempio n. 25
0
        public void ProcessRequest(HttpContext context)
        {
            context.AcceptWebSocketRequest(async sc =>
            {
                var socket = sc.WebSocket;
                while(true)
                {
                    var buffer = new ArraySegment<byte>(new byte[1024]);
                    await socket.ReceiveAsync(buffer, CancellationToken.None);
                    if (socket.State == WebSocketState.Open)
                    {
                        var message = Encoding.UTF8.GetString(buffer.Array, 0, buffer.Count);
                        var response = "Hello from WebSockets, " + message + ". The time is: " + DateTime.Now.ToShortTimeString();
                        var responseBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(response));
                        for (var i = 0; i < 5; i++)
                        {
                            var q = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello " + i));
                            await socket.SendAsync(q, WebSocketMessageType.Text, true, CancellationToken.None);
                            Thread.Sleep(2000);
                        }

                        await socket.SendAsync(responseBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                    else
                    {
                        break;
                    }
                }
            });
        }
        private WebSocketBuffer(ArraySegment<byte> internalBuffer, int receiveBufferSize, int sendBufferSize)
        {
            Contract.Assert(internalBuffer != null, "'internalBuffer' MUST NOT be NULL.");
            Contract.Assert(receiveBufferSize >= MinReceiveBufferSize,
                "'receiveBufferSize' MUST be at least " + MinReceiveBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(sendBufferSize >= MinSendBufferSize,
                "'sendBufferSize' MUST be at least " + MinSendBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(receiveBufferSize <= MaxBufferSize,
                "'receiveBufferSize' MUST NOT exceed " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");
            Contract.Assert(sendBufferSize <= MaxBufferSize,
                "'sendBufferSize' MUST NOT exceed  " + MaxBufferSize.ToString(NumberFormatInfo.InvariantInfo) + ".");

            m_ReceiveBufferSize = receiveBufferSize;
            m_SendBufferSize = sendBufferSize;
            m_InternalBuffer = internalBuffer;
            m_GCHandle = GCHandle.Alloc(internalBuffer.Array, GCHandleType.Pinned);
            // Size of the internal buffer owned exclusively by the WSPC.
            int nativeBufferSize = m_ReceiveBufferSize + m_SendBufferSize + NativeOverheadBufferSize;
            m_StartAddress = Marshal.UnsafeAddrOfPinnedArrayElement(internalBuffer.Array, internalBuffer.Offset).ToInt64();
            m_EndAddress = m_StartAddress + nativeBufferSize;
            m_NativeBuffer = new ArraySegment<byte>(internalBuffer.Array, internalBuffer.Offset, nativeBufferSize);
            m_PayloadBuffer = new ArraySegment<byte>(internalBuffer.Array,
                m_NativeBuffer.Offset + m_NativeBuffer.Count, 
                m_ReceiveBufferSize);
            m_PropertyBuffer = new ArraySegment<byte>(internalBuffer.Array,
                m_PayloadBuffer.Offset + m_PayloadBuffer.Count,
                s_PropertyBufferSize);
            m_SendBufferState = SendBufferState.None;
        }
        public void Send(ArraySegment<byte> segment)
        {
            if (!m_Connected || m_Session == null)
                throw new Exception("The socket is not connected.");

            m_Session.Send(segment);
        }
Esempio n. 28
0
 protected override void OnDecode(ByteBuffer buffer, int count)
 {
     if (count-- > 0)
     {
         this.Response = AmqpCodec.DecodeBinary(buffer);
     }
 }
 public static void DeriveKeysWithContextHeader(byte[] kdk, ArraySegment<byte> label, byte[] contextHeader, ArraySegment<byte> context, Func<byte[], HashAlgorithm> prfFactory, ArraySegment<byte> output)
 {
     byte[] combinedContext = new byte[checked(contextHeader.Length + context.Count)];
     Buffer.BlockCopy(contextHeader, 0, combinedContext, 0, contextHeader.Length);
     Buffer.BlockCopy(context.Array, context.Offset, combinedContext, contextHeader.Length, context.Count);
     DeriveKeys(kdk, label, new ArraySegment<byte>(combinedContext), prfFactory, output);
 }
Esempio n. 30
0
 private static void GetMessage(Tuple<int, WebSocket> connection, WebSocketReceiveResult result, ArraySegment<byte> bytes)
 {
     var connectionId = connection.Item1;
     var webSocket = connection.Item2;
     var message = Encoding.UTF8.GetString(bytes.Array, 0, result.Count);
     Broadcast(message, connectionId, result.EndOfMessage);
 }
Esempio n. 31
0
        private void RenderTriangles(ref Paint paint,
                                     ref Scissor scissor,
                                     float width, float fringe, float strokeThr,
                                     RenderingType renderingType,
                                     ArraySegment <Vertex> verts,
                                     PrimitiveType primitiveType,
                                     bool indexed)
        {
            if (verts.Count <= 0 ||
                indexed && _indexesCount <= 0)
            {
                return;
            }

            var innerColor = premultiplyColor(paint.InnerColor);
            var outerColor = premultiplyColor(paint.OuterColor);

            _strokeMult = (width * 0.5f + fringe * 0.5f) / fringe;

            if (scissor.Extent.X < -0.5f || scissor.Extent.Y < -0.5f)
            {
                _scissorTransform.Zero();

                _scissorExt.X   = 1.0f;
                _scissorExt.Y   = 1.0f;
                _scissorScale.X = 1.0f;
                _scissorScale.Y = 1.0f;
            }
            else
            {
                _scissorTransform = scissor.Transform.BuildInverse();
                _scissorExt.X     = scissor.Extent.X;
                _scissorExt.Y     = scissor.Extent.Y;
                _scissorScale.X   =
                    (float)Math.Sqrt(scissor.Transform.T1 * scissor.Transform.T1 +
                                     scissor.Transform.T3 * scissor.Transform.T3) / fringe;
                _scissorScale.Y =
                    (float)Math.Sqrt(scissor.Transform.T2 * scissor.Transform.T2 +
                                     scissor.Transform.T4 * scissor.Transform.T4) / fringe;
            }

            var transform = paint.Transform.BuildInverse();

            var transformMatrix = transform.ToMatrix();

            _viewSizeParam.SetValue(new Vector2(_device.PresentationParameters.Bounds.Width,
                                                _device.PresentationParameters.Bounds.Height));
            _scissorMatParam.SetValue(_scissorTransform.ToMatrix());
            _scissorExtParam.SetValue(_scissorExt);
            _scissorScaleParam.SetValue(_scissorScale);
            _paintMatParam.SetValue(transformMatrix);
            _extentParam.SetValue(new Vector4(paint.Extent.X, paint.Extent.Y, 0.0f, 0.0f));
            _radiusParam.SetValue(new Vector4(paint.Radius, 0.0f, 0.0f, 0.0f));
            _featherParam.SetValue(new Vector4(paint.Feather, 0.0f, 0.0f, 0.0f));
            _innerColParam.SetValue(innerColor.ToVector4());
            _outerColParam.SetValue(outerColor.ToVector4());
            // _effect.Parameters["strokeMult"].SetValue(new Vector4(_strokeMult, 0.0f, 0.0f, 0.0f));

            if (paint.Image > 0)
            {
                var texture = GetTextureById(paint.Image);
                _textureParam.SetValue(texture);
            }

            var technique = _techniques[(int)renderingType];

            _effect.CurrentTechnique = technique;
            foreach (var pass in _effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                if (indexed)
                {
                    _device.DrawUserIndexedPrimitives(primitiveType, verts.Array, verts.Offset, verts.Count,
                                                      _indexes, 0, _indexesCount / 3);
                }
                else
                {
                    var primitiveCount =
                        primitiveType == PrimitiveType.TriangleList ? verts.Count / 3 : verts.Count - 2;
                    _device.DrawUserPrimitives(primitiveType, verts.Array, verts.Offset, primitiveCount);
                }
            }

            _vertexes.Clear();
        }
Esempio n. 32
0
 public void SelectHexBoxRange(ArraySegment <byte> segment)
 {
     SelectHexBoxRange(segment.Offset - hexBoxBytes.Offset, segment.Count);
 }
Esempio n. 33
0
 private async Task SendMessage(ArraySegment <byte> message)
 {
     await _webSocket.SendAsync(message, WebSocketMessageType.Text, true, _cancellationTokenSource.Token);
 }
Esempio n. 34
0
 /// <summary>Constructs an incoming request frame.</summary>
 /// <param name="protocol">The Ice protocol.</param>
 /// <param name="data">The frame data as an array segment.</param>
 /// <param name="maxSize">The maximum payload size, checked during decompression.</param>
 public IncomingRequestFrame(Protocol protocol, ArraySegment <byte> data, int maxSize)
     : this(protocol, data, maxSize, null)
 {
 }
 public override Task SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
 public override Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Esempio n. 37
0
 public void ClearHexBox()
 {
     hexBoxBytes       = default;
     mHex.ByteProvider = null;
 }
Esempio n. 38
0
 public void SelectMaplePacket(MaplePacket packet)
 {
     hexBoxBytes       = packet.GetSegment(packet.Offset, packet.Length);
     mHex.ByteProvider = new DynamicByteProvider(hexBoxBytes.ToList());
 }
Esempio n. 39
0
 /// <summary>
 /// Send data to the server
 /// </summary>
 /// <param name="channelId">The channel to use.  0 is the default channel,
 /// but some transports might want to provide unreliable, encrypted, compressed, or any other feature
 /// as new channels</param>
 /// <param name="segment">The data to send to the server. Will be recycled after returning, so either use it directly or copy it internally. This allows for allocation-free sends!</param>
 public abstract void ClientSend(int channelId, ArraySegment <byte> segment);
Esempio n. 40
0
 /// <summary>
 /// Send data to a client.
 /// </summary>
 /// <param name="connectionId">The client connection id to send the data to</param>
 /// <param name="channelId">The channel to be used.  Transports can use channels to implement
 /// other features such as unreliable, encryption, compression, etc...</param>
 /// <param name="segment"></param>
 public abstract void ServerSend(int connectionId, int channelId, ArraySegment <byte> segment);
Esempio n. 41
0
 public void SetVertexData <T>(ArraySegment <T> vertexData, VertexDescriptor descriptor, int destinationOffsetInVertices) where T : struct
 {
     _stride = descriptor.VertexSizeInBytes;
     SetData(vertexData, destinationOffsetInVertices * descriptor.VertexSizeInBytes);
 }
Esempio n. 42
0
        /// <summary>
        /// Handle the player connection.
        /// </summary>
        /// <param name="request">The <see cref="ConnectionRequest"/> instance.</param>
        private static void HandleConnection(ConnectionRequest request)
        {
            try
            {
                int position = request.Data.Position;
                if (!request.Data.TryGetByte(out byte result1) || !request.Data.TryGetByte(out byte result2) || !request.Data.TryGetByte(out byte result3) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor || result3 != CustomNetworkManager.SyncedRevision)
                {
                    CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)3);
                    request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                }
                else
                {
                    bool flag = request.Data.TryGetInt(out int result4);
                    if (!request.Data.TryGetBytesWithLength(out byte[] result5))
                    {
                        flag = false;
                    }
                    if (!flag)
                    {
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)15);
                        request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                    }
                    else if (CustomLiteNetLib4MirrorTransport.DelayConnections)
                    {
                        CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)17);
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.DelayTime);
                        if (CustomLiteNetLib4MirrorTransport.DelayVolume < byte.MaxValue)
                        {
                            ++CustomLiteNetLib4MirrorTransport.DelayVolume;
                        }
                        if (CustomLiteNetLib4MirrorTransport.DelayVolume < CustomLiteNetLib4MirrorTransport.DelayVolumeThreshold)
                        {
                            ServerConsole.AddLog(
                                $"Delayed connection incoming from endpoint {request.RemoteEndPoint} by {CustomLiteNetLib4MirrorTransport.DelayTime} seconds.");
                            request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                        }
                        else
                        {
                            ServerConsole.AddLog(
                                $"Force delayed connection incoming from endpoint {request.RemoteEndPoint} by {CustomLiteNetLib4MirrorTransport.DelayTime} seconds.");
                            request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                        }
                    }
                    else
                    {
                        if (CustomLiteNetLib4MirrorTransport.UseChallenge)
                        {
                            if (result4 == 0 || result5 == null || result5.Length == 0)
                            {
                                if (!CustomLiteNetLib4MirrorTransport.CheckIpRateLimit(request))
                                {
                                    return;
                                }
                                int    num = 0;
                                string key = string.Empty;
                                for (byte index = 0; index < 3; ++index)
                                {
                                    num = RandomGenerator.GetInt32();
                                    if (num == 0)
                                    {
                                        num = 1;
                                    }
                                    key = request.RemoteEndPoint.Address + "-" + num;
                                    if (CustomLiteNetLib4MirrorTransport.Challenges.ContainsKey(key))
                                    {
                                        if (index == 2)
                                        {
                                            CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                            CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)4);
                                            request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                            ServerConsole.AddLog(
                                                $"Failed to generate ID for challenge for incoming connection from endpoint {request.RemoteEndPoint}.");
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                byte[] bytes = RandomGenerator.GetBytes(CustomLiteNetLib4MirrorTransport.ChallengeInitLen + CustomLiteNetLib4MirrorTransport.ChallengeSecretLen, true);
                                ServerConsole.AddLog(
                                    $"Requested challenge for incoming connection from endpoint {request.RemoteEndPoint}.");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)13);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)CustomLiteNetLib4MirrorTransport.ChallengeMode);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(num);
                                switch (CustomLiteNetLib4MirrorTransport.ChallengeMode)
                                {
                                case ChallengeType.MD5:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes, 0, CustomLiteNetLib4MirrorTransport.ChallengeInitLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.ChallengeSecretLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(Md.Md5(bytes));
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes, CustomLiteNetLib4MirrorTransport.ChallengeInitLen, CustomLiteNetLib4MirrorTransport.ChallengeSecretLen)));
                                    break;

                                case ChallengeType.SHA1:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes, 0, CustomLiteNetLib4MirrorTransport.ChallengeInitLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.ChallengeSecretLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(Sha.Sha1(bytes));
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes, CustomLiteNetLib4MirrorTransport.ChallengeInitLen, CustomLiteNetLib4MirrorTransport.ChallengeSecretLen)));
                                    break;

                                default:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes);
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes)));
                                    break;
                                }

                                request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                                return;
                            }

                            string key1 = request.RemoteEndPoint.Address + "-" + result4;
                            if (!CustomLiteNetLib4MirrorTransport.Challenges.ContainsKey(key1))
                            {
                                ServerConsole.AddLog(
                                    $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been REJECTED (invalid Challenge ID).");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)14);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                return;
                            }

                            ArraySegment <byte> validResponse = CustomLiteNetLib4MirrorTransport.Challenges[key1].ValidResponse;
                            if (!result5.SequenceEqual(validResponse))
                            {
                                ServerConsole.AddLog(
                                    $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been REJECTED (invalid response).");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)15);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                return;
                            }

                            CustomLiteNetLib4MirrorTransport.Challenges.Remove(key1);
                            CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                            ServerConsole.AddLog(
                                $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been accepted.");
                        }
                        else if (!CustomLiteNetLib4MirrorTransport.CheckIpRateLimit(request))
                        {
                            return;
                        }

                        if (!CharacterClassManager.OnlineMode)
                        {
                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                            if (keyValuePair.Value != null)
                            {
                                ServerConsole.AddLog($"Player tried to connect from banned endpoint {request.RemoteEndPoint}.");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)6);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(keyValuePair.Value.Expires);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(keyValuePair.Value?.Reason ?? string.Empty);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                            }
                            else
                            {
                                request.Accept();
                                CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                            }
                        }
                        else
                        {
                            if (!request.Data.TryGetString(out string result6) || result6 == string.Empty)
                            {
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)5);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                            }
 private FieldNameNode(ArraySegment<byte> bufferedToken)
     : base(bufferedToken, false)
 {
 }
Esempio n. 44
0
        static void WebServerOnData(int id, ArraySegment <byte> data)
        {
            _bitBuffer.Clear();
            _bitBuffer.FromArray(data.Array, data.Count);

            byte messageId = _bitBuffer.ReadByte();

            switch (messageId)
            {
            case 1:
            {
                uint qX = _bitBuffer.ReadUInt();
                uint qY = _bitBuffer.ReadUInt();

                PlayerData playerData = _playerDatas[id];
                playerData.qX = qX;
                playerData.qY = qY;

                // Send this position to everyone next state packet
                _dataToSend.Enqueue(playerData);

                break;
            }

            case 8:
            {
                string name = _bitBuffer.ReadString();
                _playerDatas[id].name       = name;
                _playerDatas[id].handshaked = true;

                _handshakenClientCount += 1;

                // Tell all the players this new client's name
                _bitBuffer.Clear();
                _bitBuffer.AddByte(9);
                _bitBuffer.AddUShort(_playerDatas[id].id);
                _bitBuffer.AddString(_playerDatas[id].name);
                _bitBuffer.ToArray(_buffer);
                _webServer.SendAll(_connectedIds, new ArraySegment <byte>(_buffer, 0, 23));

                break;
            }

            case 10:
            {
                ushort objectId = _bitBuffer.ReadUShort();
                ushort newX     = _bitBuffer.ReadUShort();
                ushort newY     = _bitBuffer.ReadUShort();
                _movedObjects[objectId] = new Tuple <ushort, ushort>(newX, newY);

                break;
            }

            case 11:
            {
                short pointChange = _bitBuffer.ReadShort();
                _playerDatas[id].points += pointChange;

                // If points are 0 or less, give builder a point
                if (pointChange <= 0)
                {
                    _playerDatas[_builderId].points += 1;
                }

                break;
            }
            }
        }
Esempio n. 45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Bitfield"/> class.
 /// </summary>
 /// <param name="buffer">Sequence of bits to initialize the bitfield from.</param>
 public Bitfield(ArraySegment <byte> buffer)
 {
     FromBytesInternal(buffer.Array, buffer.Offset, buffer.Count);
 }
Esempio n. 46
0
 protected override ProtobufRequestInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
 {
     info.Body = bodyBuffer.CloneRange(offset, length);
     return info;
 }
Esempio n. 47
0
        public int Initialize(ref ArraySegment <byte> readBuffer, IList <ArraySegment <byte> > writeBuffer)
        {
            if (!_isConnected)
            {
                int status = _delegate.Initialize(ref readBuffer, writeBuffer);
                if (status != SocketOperation.None)
                {
                    return(status);
                }
                _isConnected = true;
            }

            Socket?fd = _delegate.Fd();

            Debug.Assert(fd != null);

            Network.SetBlock(fd, true); // SSL requires a blocking socket

            //
            // For timeouts to work properly, we need to receive/send
            // the data in several chunks. Otherwise, we would only be
            // notified when all the data is received/written. The
            // connection timeout could easily be triggered when
            // receiving/sending large messages.
            //
            _maxSendPacketSize = Math.Max(512, Network.GetSendBufferSize(fd));
            _maxRecvPacketSize = Math.Max(512, Network.GetRecvBufferSize(fd));

            if (_sslStream == null)
            {
                try
                {
                    _sslStream = new SslStream(
                        new NetworkStream(fd, false),
                        false,
                        _engine.RemoteCertificateValidationCallback ?? RemoteCertificateValidationCallback,
                        _engine.CertificateSelectionCallback ?? CertificateSelectionCallback);
                }
                catch (IOException ex)
                {
                    if (Network.ConnectionLost(ex))
                    {
                        throw new ConnectionLostException(ex);
                    }
                    else
                    {
                        throw new TransportException(ex);
                    }
                }
                return(SocketOperation.Connect);
            }

            Debug.Assert(_sslStream.IsAuthenticated);
            _authenticated = true;

            _cipher = _sslStream.CipherAlgorithm.ToString();
            _engine.VerifyPeer((SslConnectionInfo)GetInfo(), ToString());

            if (_engine.SecurityTraceLevel >= 1)
            {
                _engine.TraceStream(_sslStream, ToString());
            }
            return(SocketOperation.None);
        }
Esempio n. 48
0
 /// <summary>
 /// Convert Bond byte arraysegment to Grpc ByteString
 /// </summary>
 public static ByteString ToByteString(this ArraySegment <byte> bytes)
 {
     return(ByteString.CopyFrom(bytes.Array, bytes.Offset, bytes.Count));
 }
Esempio n. 49
0
        Task <int> ReadFromSslStreamAsync(IByteBuffer outputBuffer, int outputBufferLength)
        {
            ArraySegment <byte> outlet = outputBuffer.GetIoBuffer(outputBuffer.WriterIndex, outputBufferLength);

            return(this.sslStream.ReadAsync(outlet.Array, outlet.Offset, outlet.Count));
        }
Esempio n. 50
0
        public async Task Connect()
        {
            int origin = Interlocked.Exchange(ref _state, _connecting);

            if (!(origin == _none || origin == _closed))
            {
                await Close(false);

                throw new InvalidOperationException("This tcp socket client is in invalid state when connecting.");
            }

            try
            {
                Clean();

                _tcpClient = _localEndPoint != null ?
                             new TcpClient(_localEndPoint) :
                             new TcpClient(_remoteEndPoint.Address.AddressFamily);
                SetSocketOptions();

                var awaiter = _tcpClient.ConnectAsync(_remoteEndPoint.Address, _remoteEndPoint.Port);
                if (!awaiter.Wait(ConnectTimeout))
                {
                    await Close(false);

                    throw new TimeoutException(string.Format(
                                                   "Connect to [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
                }

                var negotiator = NegotiateStream(_tcpClient.GetStream());
                if (!negotiator.Wait(ConnectTimeout))
                {
                    await Close(false);

                    throw new TimeoutException(string.Format(
                                                   "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
                }
                _stream = negotiator.Result;

                if (_receiveBuffer == default(ArraySegment <byte>))
                {
                    _receiveBuffer = _configuration.BufferManager.BorrowBuffer();
                }
                _receiveBufferOffset = 0;

                if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
                {
                    await Close(false);

                    throw new InvalidOperationException("This tcp socket client is in invalid state when connected.");
                }

                _log.DebugFormat("Connected to server [{0}] with dispatcher [{1}] on [{2}].",
                                 this.RemoteEndPoint,
                                 _dispatcher.GetType().Name,
                                 DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"));
                bool isErrorOccurredInUserSide = false;
                try
                {
                    await _dispatcher.OnServerConnected(this);
                }
                catch (Exception ex)
                {
                    isErrorOccurredInUserSide = true;
                    await HandleUserSideError(ex);
                }

                if (!isErrorOccurredInUserSide)
                {
                    Task.Factory.StartNew(async() =>
                    {
                        await Process();
                    },
                                          TaskCreationOptions.LongRunning)
                    .Forget();
                }
                else
                {
                    await Close();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
                throw;
            }
        }
        public async void Connect(System.Threading.CancellationToken?token = null)
        {
            var _token = token ?? GetDefaultCancellationToken();

            if (ReceivedMessageFunc == null)
            {
                throw (new ArgumentNullException(nameof(ReceivedMessageFunc)));
            }

            Log(LogType.Info, "开始连接服务器");

            if (!this._isConnect)
            {
                clientWebSocket = new System.Net.WebSockets.ClientWebSocket();
            }
            else
            {
                throw new Exception("已经建立链接,请断开链接后再试");
            }
            await clientWebSocket.ConnectAsync(new Uri("ws://message.1688.com/websocket"), _token);

            var rr = System.Threading.Tasks.Task.Run(async() =>
            {
                while (_isConnect)
                {
                    try
                    {
                        var buffer = new ArraySegment <byte>(new byte[4096]);
                        var result = await clientWebSocket.ReceiveAsync(buffer, _token);
                        if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Text)
                        {
                            if (result.EndOfMessage)
                            {
                                var json            = System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                                var receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(json, serializerSettings);
                                Log(LogType.Info, "接收到消息,类型:" + receivedMessage.Type);
                                if (receivedMessage.Type == WebSocketMessageType.CONNECT_ACK)
                                {
                                    IsConnect = true;
                                    sendHeartbeat(_token);
                                }
                                else if (receivedMessage.Type == WebSocketMessageType.SERVER_PUSH)
                                {
                                    var dd = System.Threading.Tasks.Task.Run(() =>
                                    {
                                        try
                                        {
                                            var b  = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessageDataBaseType>(receivedMessage.Content, serializerSettings);
                                            var ss = GetReceivedMessageData(b.Type, receivedMessage.Content);
                                            var r  = ReceivedMessageFunc?.Invoke(receivedMessage.MsgSource, ss);
                                            if (r == true)
                                            {
                                                sendConfirm(receivedMessage, _token);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Log(LogType.Error, "处理消息异常", ex);
                                        }
                                    });
                                }
                                else if (receivedMessage.Type == WebSocketMessageType.SYSTEM)
                                {
                                    SystemInfoFunc?.Invoke(receivedMessage.MsgSource, receivedMessage.Content);
                                }
                                else
                                {
                                    Log(LogType.Error, "接收到其他消息,--------------------------------------------------类型:" + receivedMessage.Type);
                                    //throw new Exception("异常");
                                }
                            }
                            else
                            {
                                throw new Exception("异常");
                            }
                        }
                        else if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Binary)
                        {
                            throw new Exception("异常");
                        }
                        else if (result.MessageType == System.Net.WebSockets.WebSocketMessageType.Close)
                        {
                            throw new Exception("异常");
                        }
                        else
                        {
                            throw new Exception("异常");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log(LogType.Error, "接收数据异常", ex);
                        //throw new Exception("异常", ex);
                    }
                }
            });

            sendConnect(_token);
            //sendHeartbeat();
        }
Esempio n. 52
0
 // Force caller to use asynchronous read.
 public int Read(ref ArraySegment <byte> buffer, ref int offset) =>
 offset < buffer.Count ? SocketOperation.Read : SocketOperation.None;
Esempio n. 53
0
        public void ExecuteCommand(GameSession session, ProtobufRequestInfo requestInfo)
        {
            if (!Gongyong.userlist.Any(w => w.session.SessionID.Equals(session.SessionID)))
            {
                session.Logger.Debug("DayToL : 非法连接");
                session.Close();
                return;
            }
            var           getMsg   = SendBT.ParseFrom(requestInfo.Body);
            List <mjuser> listuser = Gongyong.mulist.FindAll(u => u.RoomID == getMsg.RoomID);
            mjuser        mjuser   = Gongyong.mulist.Find(u => u.Openid == getMsg.Openid && u.RoomID == getMsg.RoomID);
            var           room     = Gongyong.roomlist.Find(w => w.RoomID == getMsg.RoomID);

            if (room == null)
            {
                return;
            }
            if (mjuser == null)
            {
                return;
            }
            if (getMsg.Type == 1 && mjuser.majiangs.Count != 14)//天听,报听时手牌还未扣除,因此为14张
            {
                return;
            }
            if ((getMsg.Type == 2 && !mjuser.Is_tiant))
            {
                return;
            }
            int fw = mjuser.ZS_Fw;

            if (mjuser.ByteData == requestInfo.Key)
            {
                return;
            }
            else
            {
                mjuser.ByteData = requestInfo.Key;
            }
            Ting t = new Ting();
            List <model.ServerMaJiang> Returnmj = new List <model.ServerMaJiang>();

            Returnmj.AddRange(mjuser.majiangs.ToArray());
            if (getMsg.Type == 1 && !mjuser.Is_tianHu)
            {
                List <model.ServerMaJiang> Ruturnjsmj = new List <model.ServerMaJiang>();

                Ruturnjsmj = t.ReturnJMJ(Returnmj);
                Returnmj.Remove(Returnmj.Find(w => w.PaiHs == getMsg.Mj.PaiHS && w.PaiId == getMsg.Mj.PaiID));
                if (!Ruturnjsmj.Any(w => w.PaiHs == getMsg.Mj.PaiHS))
                {
                    return;//出的牌必须是打出听牌的集合中的一张
                }
            }
            if (getMsg.Type == 2 && t.GetTing(Returnmj) == "MJ")
            {
                mjuser.Is_tiant = false;
                return;
            }
            bool          isShenTianHu = false;
            List <mjuser> list         = new List <mjuser>();

            foreach (var item in listuser)
            {
                list.Add(item);
                if (!isShenTianHu)
                {
                    item.SendData.Clear();
                }
                if (item.Openid.Equals(getMsg.Openid))
                {
                    switch (getMsg.Type)
                    {
                    case 1:
                        if (mjuser.Is_tianHu)
                        {
                            mjuser.Is_tianHu = false;
                        }
                        var roomInfo = Gongyong.roomlist.FirstOrDefault(w => w.RoomID.Equals(getMsg.RoomID));
                        if (roomInfo != null)
                        {
                            roomInfo.LastMoMJ = new model.ServerMaJiang {
                                PaiHs = getMsg.Mj.PaiHS, PaiId = getMsg.Mj.PaiID
                            }
                        }
                        ;
                        item.Is_baotin = true;
                        break;

                    case 2:
                        item.Is_tiant = true;
                        CardUser cu = Gongyong.FKUser.Find(u => u.roomid == getMsg.RoomID);
                        item.Is_tiantX = 1;
                        byte[] startHY = ReturnHyUser.CreateBuilder().SetCz("3001").SetFw(cu.win).Build().ToByteArray();
                        if (!listuser.Any(w => w.Is_tiantX == -1))
                        {
                            if (room != null)
                            {
                                room.DQHY = cu.win;
                                room.DQcz = "3001";
                            }
                            List <mjuser> listmjuserstart = Gongyong.mulist.FindAll(u => u.RoomID == getMsg.RoomID);

                            foreach (var items in listmjuserstart)
                            {
                                UserInfo users = Gongyong.userlist.Find(u => u.openid == items.Openid);
                                users.IsActive = true;
                                users.session.TrySend(new ArraySegment <byte>(CreateHead.CreateMessage(GameInformationBase.BASEAGREEMENTNUMBER + 7004, startHY.Length, requestInfo.MessageNum, startHY)));
                            }
                            var msglist = Gongyong.roommsg.FindAll(u => u.roomid == getMsg.RoomID);
                            if (msglist.Count > 0)
                            {
                                Room r = Gongyong.roomlist.Find(u => u.RoomID == getMsg.RoomID);
                                foreach (var msgitem in msglist)
                                {
                                    var userInfo = Gongyong.userlist.Find(u => u.openid == msgitem.openid);
                                    if (userInfo != null)
                                    {
                                        isShenTianHu = true;
                                        var mjUser = listmjuserstart.Find(u => u.Openid.Equals(msgitem.openid));
                                        r.DQHY = mjUser.ZS_Fw;
                                        if (!list.Any(w => w.Openid.Equals(msgitem.openid)))    //如果外面的遍历已经遍历过当前用户 则不需要清理集合
                                        {
                                            mjUser.SendData.Clear();
                                        }
                                        var data = new ArraySegment <byte>(CreateHead.CreateMessage(GameInformationBase.BASEAGREEMENTNUMBER + msgitem.xiaoxihao, msgitem.ArrList.Length, requestInfo.MessageNum, msgitem.ArrList));
                                        mjUser.SendData.Add(data);
                                        userInfo.session.TrySend(data);

                                        //session.Logger.Debug("过牌后根据之前的消息分配活跃用户" + r.DQHY);
                                    }
                                }
                                Gongyong.roommsg.RemoveAll(u => u.roomid == r.RoomID);
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
                UserInfo user = Gongyong.userlist.Find(u => u.openid == item.Openid);
                if (getMsg.Type == 1)
                {
                    var    renturnmsg = ReturnBTMsg.CreateBuilder().SetFw(fw).Build();
                    byte[] r          = renturnmsg.ToByteArray();
                    var    data       = new ArraySegment <byte>(CreateHead.CreateMessage(GameInformationBase.BASEAGREEMENTNUMBER + 5002, r.Length, requestInfo.MessageNum, r));
                    item.SendData.Add(data);
                    user.session.TrySend(data);
                }
                else
                {
                    var    renturnmsg = ReturnTT.CreateBuilder().SetFw(fw).Build();
                    byte[] r          = renturnmsg.ToByteArray();
                    var    data       = new ArraySegment <byte>(CreateHead.CreateMessage(GameInformationBase.BASEAGREEMENTNUMBER + 5013, r.Length, requestInfo.MessageNum, r));
                    item.SendData.Add(data);
                    user.session.TrySend(data);
                }
            }

            //牌局回放 摸牌

            room.gameOperationProcess.AddGameOperationInfo(
                GameOperationInfo.CreateBuilder()
                .SetSerialNumber(room.gameOperationProcess.GameOperationInfoCount)
                .SetOperationFW(mjuser.ZS_Fw)
                .SetOperationType(6)
                .SetTingHuType(getMsg.Type + 1)
                );
        }
Esempio n. 54
0
        /// <summary>Unwraps inbound SSL records.</summary>
        void Unwrap(IChannelHandlerContext ctx, IByteBuffer packet, int offset, int length, List <int> packetLengths, List <object> output)
        {
            Contract.Requires(packetLengths.Count > 0);

            //bool notifyClosure = false; // todo: netty/issues/137
            bool pending = false;

            IByteBuffer outputBuffer = null;

            try
            {
                ArraySegment <byte> inputIoBuffer = packet.GetIoBuffer(offset, length);
                this.mediationStream.SetSource(inputIoBuffer.Array, inputIoBuffer.Offset);

                int packetIndex = 0;

                while (!this.EnsureAuthenticated())
                {
                    this.mediationStream.ExpandSource(packetLengths[packetIndex]);
                    if (++packetIndex == packetLengths.Count)
                    {
                        return;
                    }
                }

                Task <int> currentReadFuture = this.pendingSslStreamReadFuture;

                int outputBufferLength;

                if (currentReadFuture != null)
                {
                    // restoring context from previous read
                    Contract.Assert(this.pendingSslStreamReadBuffer != null);

                    outputBuffer       = this.pendingSslStreamReadBuffer;
                    outputBufferLength = outputBuffer.WritableBytes;
                }
                else
                {
                    outputBufferLength = 0;
                }

                // go through packets one by one (because SslStream does not consume more than 1 packet at a time)
                for (; packetIndex < packetLengths.Count; packetIndex++)
                {
                    int currentPacketLength = packetLengths[packetIndex];
                    this.mediationStream.ExpandSource(currentPacketLength);

                    if (currentReadFuture != null)
                    {
                        // there was a read pending already, so we make sure we completed that first

                        if (!currentReadFuture.IsCompleted)
                        {
                            // we did feed the whole current packet to SslStream yet it did not produce any result -> move to the next packet in input
                            Contract.Assert(this.mediationStream.SourceReadableBytes == 0);

                            continue;
                        }

                        int read = currentReadFuture.Result;

                        // Now output the result of previous read and decide whether to do an extra read on the same source or move forward
                        AddBufferToOutput(outputBuffer, read, output);

                        currentReadFuture = null;
                        if (this.mediationStream.SourceReadableBytes == 0)
                        {
                            // we just made a frame available for reading but there was already pending read so SslStream read it out to make further progress there

                            if (read < outputBufferLength)
                            {
                                // SslStream returned non-full buffer and there's no more input to go through ->
                                // typically it means SslStream is done reading current frame so we skip
                                continue;
                            }

                            // we've read out `read` bytes out of current packet to fulfil previously outstanding read
                            outputBufferLength = currentPacketLength - read;
                            if (outputBufferLength <= 0)
                            {
                                // after feeding to SslStream current frame it read out more bytes than current packet size
                                outputBufferLength = FallbackReadBufferSize;
                            }
                        }
                        else
                        {
                            // SslStream did not get to reading current frame so it completed previous read sync
                            // and the next read will likely read out the new frame
                            outputBufferLength = currentPacketLength;
                        }
                    }
                    else
                    {
                        // there was no pending read before so we estimate buffer of `currentPacketLength` bytes to be sufficient
                        outputBufferLength = currentPacketLength;
                    }

                    outputBuffer      = ctx.Allocator.Buffer(outputBufferLength);
                    currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, outputBufferLength);
                }

                // read out the rest of SslStream's output (if any) at risk of going async
                // using FallbackReadBufferSize - buffer size we're ok to have pinned with the SslStream until it's done reading
                while (true)
                {
                    if (currentReadFuture != null)
                    {
                        if (!currentReadFuture.IsCompleted)
                        {
                            break;
                        }
                        int read = currentReadFuture.Result;
                        AddBufferToOutput(outputBuffer, read, output);
                    }
                    outputBuffer      = ctx.Allocator.Buffer(FallbackReadBufferSize);
                    currentReadFuture = this.ReadFromSslStreamAsync(outputBuffer, FallbackReadBufferSize);
                }

                pending = true;
                this.pendingSslStreamReadBuffer = outputBuffer;
                this.pendingSslStreamReadFuture = currentReadFuture;
            }
            catch (Exception ex)
            {
                this.HandleFailure(ex);
                throw;
            }
            finally
            {
                this.mediationStream.ResetSource();
                if (!pending && outputBuffer != null)
                {
                    if (outputBuffer.IsReadable())
                    {
                        output.Add(outputBuffer);
                    }
                    else
                    {
                        outputBuffer.SafeRelease();
                    }
                }
            }
        }
 private StringNode(ArraySegment<byte> bufferedToken)
     : base(bufferedToken, true)
 {
 }
        public override IFuzzyQuery Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            if (reader.GetCurrentJsonToken() == JsonToken.Null)
            {
                reader.ReadNext();
                return(null);
            }

            var                   count = 0;
            IFuzzyQuery           query = null;
            string                name  = null;
            double?               boost = null;
            MultiTermQueryRewrite multiTermQueryRewrite = null;
            int?                  prefixLength          = null;
            int?                  maxExpansions         = null;
            bool?                 transpositions        = null;

            while (reader.ReadIsInObject(ref count))
            {
                var field = reader.ReadPropertyName();
                // ReSharper disable once TooWideLocalVariableScope
                ArraySegment <byte> fuzzinessSegment = default;
                var valueCount = 0;
                while (reader.ReadIsInObject(ref valueCount))
                {
                    var property = reader.ReadPropertyNameSegmentRaw();
                    if (Fields.TryGetValue(property, out var value))
                    {
                        switch (value)
                        {
                        case 0:
                        {
                            var token = reader.GetCurrentJsonToken();
                            switch (token)
                            {
                            case JsonToken.String:
                                var valueSegment = reader.ReadStringSegmentUnsafe();
                                if (valueSegment.IsDateTime(formatterResolver, out var dateTime))
                                {
                                    query = new FuzzyDateQuery
                                    {
                                        Field = field,
                                        Value = dateTime
                                    }
                                }
                                ;
                                else
                                {
                                    query = new FuzzyQuery
                                    {
                                        Field = field,
                                        Value = valueSegment.Utf8String()
                                    }
                                };
                                break;

                            case JsonToken.Number:
                                query = new FuzzyNumericQuery
                                {
                                    Field = field,
                                    Value = reader.ReadDouble()
                                };
                                break;
                            }

                            if (fuzzinessSegment != default)
                            {
                                var fuzzinessReader = new JsonReader(fuzzinessSegment.Array, fuzzinessSegment.Offset);
                                SetFuzziness(ref fuzzinessReader, query, formatterResolver);
                            }
                            break;
                        }

                        case 1:
                        {
                            if (query != null)
                            {
                                SetFuzziness(ref reader, query, formatterResolver);
                            }
                            else
                            {
                                fuzzinessSegment = reader.ReadNextBlockSegment();
                            }
                            break;
                        }

                        case 2:
                            prefixLength = reader.ReadInt32();
                            break;

                        case 3:
                            maxExpansions = reader.ReadInt32();
                            break;

                        case 4:
                            transpositions = reader.ReadBoolean();
                            break;

                        case 5:
                            var rewriteFormatter = formatterResolver.GetFormatter <MultiTermQueryRewrite>();
                            multiTermQueryRewrite = rewriteFormatter.Deserialize(ref reader, formatterResolver);
                            break;

                        case 6:
                            name = reader.ReadString();
                            break;

                        case 7:
                            boost = reader.ReadDouble();
                            break;
                        }
                    }
                }
            }

            query.PrefixLength   = prefixLength;
            query.MaxExpansions  = maxExpansions;
            query.Transpositions = transpositions;
            query.Rewrite        = multiTermQueryRewrite;
            query.Name           = name;
            query.Boost          = boost;
            return(query);
        }
Esempio n. 57
0
 public virtual void SendResponse(ArraySegment <byte> segment)
 {
     InternalSend(segment);
 }
 protected StringNodeBase(ArraySegment<byte> bufferedToken, bool isStringNode)
     : base(isStringNode ? JsonNodeType.String : JsonNodeType.FieldName)
 {
     this.value = new Lazy<string>(() => JsonTextUtil.GetStringValue(bufferedToken));
 }
 public BufferedProducer(ArraySegment<byte> data)
 {
     this.data = data;
 }
 private NumberNode(ArraySegment<byte> bufferedToken)
     : base(JsonNodeType.Number)
 {
     this.value = new Lazy<double>(() => JsonTextUtil.GetNumberValue(bufferedToken));
 }