Exemple #1
0
        private async Task <WebSocketCloseStatus> LoginDevice(HttpContext context, WebSocket socket, byte[] buffer, RegisteredDevice device, AnperiDbContext dbContext)
        {
            await socket.SendJson(SharedJsonApiObjectFactory.CreateLoginResponse(true, device.Name));

            List <AuthenticatedWebSocketConnection> connectedPairedDevices = await GetOnlinePairedDevices(device, dbContext);

            var connection = new AuthenticatedWebSocketConnection(context, socket, buffer, device, dbContext, _logger, this, connectedPairedDevices);

            lock (_syncRootActiveConnections)
            {
                _activeConnections.Add(connection.Device.Id, connection);
            }
            WebSocketCloseStatus closeStatus;

            try
            {
                await OnDeviceLoggedIn(connection, dbContext);

                closeStatus = await connection.Run(_options.Value.RequestCancelToken);
            }
            catch (WebSocketException se)
            {
                if (!(se.InnerException is BadHttpRequestException))
                {
                    throw;
                }
                closeStatus = WebSocketCloseStatus.Empty;
                _logger.LogWarning(
                    $"BadHttpRequestException occured while handling a websocket: {se.Message} -> {se.InnerException.Message}");
            }
            finally
            {
                if (!connection.IsAborted)
                {
                    await RemoveLoggedInDevice(connection, dbContext);
                }
            }
            return(closeStatus);
        }
Exemple #2
0
        private async Task HandleWebSocket(HttpContext ctx, AnperiDbContext dbContext)
        {
            WebSocket socket = await ctx.WebSockets.AcceptWebSocketAsync();

            var buffer = new byte[_options.Value.WsBufferSize];

            WebSocketApiResult apiObjectResult =
                await socket.ReceiveApiMessage(buffer, _options.Value.RequestCancelToken);

            bool authFailed = true;
            WebSocketCloseStatus closeStatus = WebSocketCloseStatus.Empty;

            if (apiObjectResult.Obj == null)
            {
                await socket.SendJson(
                    SharedJsonApiObjectFactory.CreateError(apiObjectResult.JsonException.Message),
                    _options.Value.RequestCancelToken);
            }
            else
            {
                if (apiObjectResult.Obj.context == JsonApiContextTypes.server &&
                    apiObjectResult.Obj.message_type == JsonApiMessageTypes.request)
                {
                    apiObjectResult.Obj.data.TryGetValue(nameof(JsonLoginData.device_type), out string typeString);
                    if (Enum.TryParse(typeString, out SharedJsonDeviceType type) &&
                        Enum.TryParse(apiObjectResult.Obj.message_code, out SharedJsonRequestCode code))
                    {
                        RegisteredDevice device = null;
                        switch (code)
                        {
                        case SharedJsonRequestCode.login:
                            if (!apiObjectResult.Obj.data.TryGetValue("token", out string token))
                            {
                                await socket.SendJson(
                                    SharedJsonApiObjectFactory.CreateError("Error retrieving token from request."));
                            }
                            else
                            {
                                switch (type)
                                {
                                case SharedJsonDeviceType.host:
                                    device = dbContext.Hosts.SingleOrDefault(d => d.Token == token);
                                    break;

                                case SharedJsonDeviceType.peripheral:
                                    device = dbContext.Peripherals.SingleOrDefault(d => d.Token == token);
                                    break;

                                default:
                                    await socket.SendJson(
                                        SharedJsonApiObjectFactory.CreateError(
                                            "You need to be a host or peripheral."));

                                    break;
                                }
                                if (device != null)
                                {
                                    AuthenticatedWebSocketConnection activeConn;
                                    lock (_activeConnections)
                                    {
                                        _activeConnections.TryGetValue(device.Id, out activeConn);
                                    }
                                    if (activeConn != null)
                                    {
                                        activeConn.Abort();
                                        await RemoveLoggedInDevice(activeConn, dbContext);
                                    }
                                    closeStatus = await LoginDevice(ctx, socket, buffer, device, dbContext);

                                    authFailed = false;
                                }
                            }
                            break;

                        case SharedJsonRequestCode.register:
                            switch (type)
                            {
                            case SharedJsonDeviceType.host:
                                device = new Host();
                                break;

                            case SharedJsonDeviceType.peripheral:
                                device = new Peripheral();
                                break;

                            default:
                                await socket.SendJson(
                                    SharedJsonApiObjectFactory.CreateError(
                                        "You need to be a host or peripheral."));

                                break;
                            }
                            if (device != null)
                            {
                                device.Token = Cryptography.CreateAuthToken();
                                if (apiObjectResult.Obj.data.TryGetValue("name", out string name))
                                {
                                    device.Name = name;
                                }
                                else
                                {
                                    await socket.SendJson(
                                        SharedJsonApiObjectFactory.CreateError(
                                            "A device registration requires a name!"));
                                }
                                if (string.IsNullOrWhiteSpace(device.Name))
                                {
                                    device.Name = "devices want a name :(";
                                }
                                dbContext.RegisteredDevices.Add(device);
                                await dbContext.SaveChangesAsync();

                                await socket.SendJson(
                                    SharedJsonApiObjectFactory.CreateRegisterResponse(device.Token, device.Name));

                                closeStatus = await LoginDevice(ctx, socket, buffer, device, dbContext);

                                authFailed = false;
                            }
                            break;

                        default:
                            await socket.SendJson(
                                SharedJsonApiObjectFactory.CreateError("Only login and register are valid here."));

                            break;
                        }
                    }
                    else
                    {
                        await socket.SendJson(
                            SharedJsonApiObjectFactory.CreateError(
                                "Error parsing correct login or register parameters."));
                    }
                }
            }

            if (authFailed)
            {
                await socket.SendJson(SharedJsonApiObjectFactory.CreateLoginResponse(false, null));

                CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000));
                await socket.CloseAsync(WebSocketCloseStatus.PolicyViolation, "Authentication failed.", cts.Token);
            }
            else if (_options.Value.RequestCancelToken.IsCancellationRequested)
            {
                CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(1000));
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Server is shutting down.", cts.Token);
            }
            else
            {
                await socket.CloseAsync(closeStatus, apiObjectResult.SocketResult.CloseStatusDescription, CancellationToken.None);
            }
        }