Example #1
0
        private async Task HandleManagingMessage(byte[] bytes, ManagingConnectionInfo connectionInfo)
        {
            try
            {
                (Message Msg, string UserId)res = await mEncoder.Decode(bytes);


                switch (res.Msg.Type)
                {
                case "AReq":
                    await Auth(connectionInfo, res.Msg, res.UserId);

                    break;

                case "DTAReq":
                    await NewDataTunnel(connectionInfo, res.Msg);

                    break;

                case "ConReq":
                    await NewConnection(connectionInfo, res.Msg);

                    break;

                case "DisconEvnt":
                    await Disconnect(connectionInfo, res.Msg);

                    break;
                }
            }
            catch (Exception ex)
            {
                log.LogError($"[{connectionInfo.connectionId}] Error Handle mMessage - {ex.Message}");
            }
        }
Example #2
0
        private async Task ProcessingManagingConnection(ManagingConnectionInfo connectionInfo)
        {
            var buffer = new byte[1024 * 16];

            while (connectionInfo.socket.State == WebSocketState.Open)
            {
                var ms = new MemoryStream();
                try
                {
                    WebSocketReceiveResult received;
                    do
                    {
                        received = await connectionInfo.socket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                        await ms.WriteAsync(buffer, 0, received.Count);
                    } while (!received.EndOfMessage);

                    if (received.MessageType == WebSocketMessageType.Close)
                    {
                        if (connectionInfo.socket.State == WebSocketState.CloseReceived)
                        {
                            await connectionInfo.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                        }
                    }
                    else
                    {
                        await HandleManagingMessage(ms.ToArray(), connectionInfo);
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"[{connectionInfo.connectionId}]: При получении данных произошла ошибка: {ex.Message} ");
                }
            }
        }
Example #3
0
 private Task SendDisconectEvent(ManagingConnectionInfo managingConnection, Guid socketId)
 {
     return(SendMessage(managingConnection, new Message
     {
         CorrelationId = Guid.NewGuid().ToString("N"),
         Type = "DisconEvnt",
         TimeStamp = DateTime.UtcNow,
         Payload = new DisconEvnt
         {
             SocketId = socketId
         }
     }));
 }
Example #4
0
        private async Task Auth(ManagingConnectionInfo connectionInfo, Message msg, string userId)
        {
            var sw = new Stopwatch();

            sw.Start();

            var aReq = msg.Payload.ConvertValue <AReq>();

            if (connectionInfo.UserInfo != null)
            {
                return;
            }

            var userInfo = await dataCache.GetUserInfo(userId);

            connectionInfo.UserInfo = userInfo;

            var aRes = new ARes
            {
                Error = AuthUser(userInfo, aReq)
            };

            if (aRes.Error == null)
            {
                aRes.Status = ResStatus.Ok;
                connectionInfo.notAuthTimeOut.Dispose();
            }
            else
            {
                aRes.Status = ResStatus.Error;
            }

            sw.Stop();

            var result = new Message
            {
                CorrelationId     = msg.CorrelationId,
                Type              = "ARes",
                Payload           = aRes,
                TimeStamp         = DateTime.UtcNow,
                ExecutionDuration = sw.Elapsed
            };

            await SendMessage(connectionInfo, result);
        }
Example #5
0
        public async Task RegisterManagingConnection(WebSocket socket, Guid connectionId)
        {
            var connectionInfo = new ManagingConnectionInfo
            {
                socket         = socket,
                connectionId   = connectionId,
                type           = ConnectionType.Managing,
                notAuthTimeOut = new CancellationTokenSource()
            };

            if (!mConnections.TryAdd(connectionId, connectionInfo))
            {
                return;
            }

            connectionInfo.notAuthTimeOut.Token.Register(async() =>
            {
                if (mConnections.TryRemove(connectionId, out var ci))
                {
                    if (ci.socket.State == WebSocketState.Open)
                    {
                        await ci.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                    }
                }
            });

            connectionInfo.notAuthTimeOut.CancelAfter(TimeSpan.FromSeconds(5));

            await ProcessingManagingConnection(connectionInfo);

            connectionInfo.notAuthTimeOut.Dispose();

            if (mConnections.TryRemove(connectionId, out var ci))
            {
                if (ci.socket.State == WebSocketState.Open)
                {
                    await ci.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                }
            }
        }
Example #6
0
        private async Task <bool> SendMessage(ManagingConnectionInfo connection, Message msg)
        {
            var data = await mEncoder.Encode(msg, connection.UserInfo.Kid);

            return(await SendData(connection, data));
        }
Example #7
0
        private Task Disconnect(ManagingConnectionInfo connection, Message msg)
        {
            var dEvent = msg.Payload.ConvertValue <DisconEvnt>();

            return(SocketDisconnect(dEvent.SocketId, false));
        }
Example #8
0
        private async Task NewConnection(ManagingConnectionInfo connectionInfo, Message msg)
        {
            var sw = new Stopwatch();

            sw.Start();

            var conReq = msg.Payload.ConvertValue <ConReq>();
            var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

            try
            {
                var ip = Dns.GetHostAddresses(conReq.Addr)
                         .First(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);


                await socket.ConnectAsync(ip, conReq.Port);

                var socketInfo = new SocketInfo
                {
                    Socket           = socket,
                    mainConnectionId = connectionInfo.connectionId,
                    SocketId         = conReq.SocketId
                };
                if (socketInfos.TryAdd(conReq.SocketId, socketInfo))
                {
                    log.LogTrace($"Новый сокет {conReq.SocketId} -> {ip}:{conReq.Port}");
                    RunProcessingSocketConnection(socketInfo);
                }
                else
                {
                    throw new Exception("Ошибка добавления соедининия");
                }

                sw.Stop();

                await SendMessage(connectionInfo, new Message
                {
                    CorrelationId     = msg.CorrelationId,
                    ExecutionDuration = sw.Elapsed,
                    TimeStamp         = DateTime.UtcNow,
                    Type    = "ConRes",
                    Payload = new ConRes
                    {
                        SocketId = conReq.SocketId,
                        Ip       = ip.GetAddressBytes(),
                        Status   = ResStatus.Ok
                    }
                });
            }
            catch (Exception ex)
            {
                await SendMessage(connectionInfo, new Message
                {
                    CorrelationId     = msg.CorrelationId,
                    ExecutionDuration = sw.Elapsed,
                    TimeStamp         = DateTime.UtcNow,
                    Type    = "ConRes",
                    Payload = new ConRes
                    {
                        SocketId = conReq.SocketId,
                        Status   = ResStatus.Error,
                        Error    = new Error
                        {
                            Code    = "ConnectionFailed",
                            Message = ex.Message
                        }
                    }
                });
            }

            void RunProcessingSocketConnection(SocketInfo si)
            {
                connectionInfo.dataScokets.TryAdd(si.SocketId, si.SocketId);
                Task.Run(async() =>
                {
                    await ProcessingSocketConnection(si);
                    await SocketDisconnect(si.SocketId, true);
                });
            }
        }
Example #9
0
        private async Task NewDataTunnel(ManagingConnectionInfo connectionInfo, Message msg)
        {
            var sw = new Stopwatch();

            sw.Start();


            var dtaRes = new DTARes();

            var result = new Message
            {
                CorrelationId = msg.CorrelationId,
                Type          = "DTARes",
                Payload       = dtaRes
            };


            if (connectionInfo.UserInfo == null)
            {
                dtaRes.Status = ResStatus.Error;
                dtaRes.Error  = new Error
                {
                    Code = "InsufficientPermission",
                };

                sw.Stop();
                result.ExecutionDuration = sw.Elapsed;
                result.TimeStamp         = DateTime.UtcNow;


                await SendMessage(connectionInfo, result);

                return;
            }


            var aes = Aes.Create();

            aes.GenerateIV();
            aes.GenerateKey();

            var dataConnection = new ReqDataConnection
            {
                reqCID = Guid.NewGuid(),
                notConnectionTimeOut = new CancellationTokenSource(),
                aes              = aes,
                blockSize        = 0,
                mainConnectionId = connectionInfo.connectionId
            };


            if (!reqDConnections.TryAdd(dataConnection.reqCID, dataConnection))
            {
                log.LogError("Ошибка добавления нового соединения");
                dtaRes.Status = ResStatus.Error;
                dtaRes.Error  = new Error
                {
                    Code = "InternalError",
                };

                sw.Stop();
                result.ExecutionDuration = sw.Elapsed;
                result.TimeStamp         = DateTime.UtcNow;

                await SendMessage(connectionInfo, result);

                return;
            }

            dtaRes.DTKey = dataConnection.aes.Key;
            dtaRes.DTIV  = dataConnection.aes.IV;
            dtaRes.DTBS  = dataConnection.blockSize;
            dtaRes.DTUri = dataConnection.reqCID.ToString("N");

            dataConnection.notConnectionTimeOut.Token.Register(() =>
            {
                reqDConnections.TryRemove(dataConnection.reqCID, out var rdc);
            });


            dtaRes.Status = ResStatus.Ok;
            dtaRes.Error  = null;

            sw.Stop();
            result.ExecutionDuration = sw.Elapsed;
            result.TimeStamp         = DateTime.UtcNow;

            await SendMessage(connectionInfo, result);

            dataConnection.notConnectionTimeOut.CancelAfter(TimeSpan.FromSeconds(5));
        }