コード例 #1
0
        CoapResponse ExecuteCoapRequest(CoapRequest coapRequest, PythonDictionary parameters)
        {
            var clientUid = Convert.ToString(parameters.get("client_uid", null));
            var timeout   = Convert.ToInt32(parameters.get("timeout", 1000));

            if (!string.IsNullOrEmpty(clientUid))
            {
                ICoapClient coapClient;
                lock (_clients)
                {
                    if (!_clients.TryGetValue(clientUid, out coapClient))
                    {
                        coapClient          = CreateClient(parameters).GetAwaiter().GetResult();
                        _clients[clientUid] = coapClient;
                    }
                }

                try
                {
                    using (var cancellationTokenSource = new CancellationTokenSource(timeout))
                    {
                        lock (coapClient)
                        {
                            Console.WriteLine("SENDING COAP REQUEST");
                            return(coapClient.RequestAsync(coapRequest, cancellationTokenSource.Token).GetAwaiter().GetResult());
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("CLOSING EXISTING COAP CLIENT");
                    coapClient.Dispose();

                    lock (_clients)
                    {
                        _clients.Remove(clientUid);
                    }

                    throw;
                }
            }

            CoapResponse coapResponse;

            using (var coapClient = CreateClient(parameters).GetAwaiter().GetResult())
            {
                using (var cancellationTokenSource = new CancellationTokenSource(timeout))
                {
                    Console.WriteLine("SENDING COAP REQUEST");
                    coapResponse = coapClient.RequestAsync(coapRequest, cancellationTokenSource.Token).GetAwaiter().GetResult();
                }

                Console.WriteLine("CLOSING COAP CLIENT");
            }

            return(coapResponse);
        }
コード例 #2
0
        CoapRequest CreateRequest(PythonDictionary parameters)
        {
            var method  = Convert.ToString(parameters.get("method", "get"));
            var path    = Convert.ToString(parameters.get("path", string.Empty));
            var payload = parameters.get("payload", Array.Empty <byte>());

            return(new CoapRequestBuilder()
                   .WithMethod((CoapRequestMethod)Enum.Parse(typeof(CoapRequestMethod), method, true))
                   .WithPath(path)
                   .WithPayload(PythonConvert.ToPayload(payload))
                   .Build());
        }
コード例 #3
0
        public RegisterArgument(PythonBoss pyBoss, Context context, PythonDictionary spec, Process process, Arguments parent, string namePrefix)
        {
            NamePrefix   = namePrefix;
            this.process = process;

            // Parse the spec for this argument
            // regspec: [{"name": "socket",
            //		      "register": "rcx",
            //		      "type": None,
            //		      "fuzz": NOFUZZ},]

            Register      = ((string)spec.get("register")).ToLower();
            Fuzz          = (bool)spec.get("fuzz");
            Name          = (string)spec.get("name");
            _argumentType = (object)spec.get("type");
            if (spec.ContainsKey("type_args"))
            {
                _typeArgs = spec.get("type_args");
            }

            // Validate required fields
            if (Name == null)
            {
                throw new Exception("ERROR: Argument specification must include 'name' attribute. Failed when parsing name prefix '" + namePrefix + "'.");
            }
            else if (Fuzz == null)
            {
                throw new Exception("ERROR: Argument specification must include 'fuzz' attribute. Failed when parsing type '" + namePrefix + Name + "'.");
            }

            this.process = process;
            _pyBoss      = pyBoss;
            _parent      = parent;

            // Read the data
            var tmpData = context.GetMember(Register);

            if (tmpData is UInt32)
            {
                Data = BitConverter.GetBytes((UInt32)tmpData);
            }
            else if (tmpData is UInt64)
            {
                Data = BitConverter.GetBytes((UInt64)tmpData);
            }
            else
            {
                throw new Exception("Register argument type definition problem. The register must be of type 'int' or 'long'. The is likely an engine bug. Argument name: " + Name + ". The unsupported register type is: " + tmpData.ToString());
            }
            Size = Data.Length;

            PointerTarget = null;
        }
コード例 #4
0
        public void register_panel(PythonDictionary panel_definition)
        {
            if (panel_definition is null)
            {
                throw new ArgumentNullException(nameof(panel_definition));
            }

            _appService.RegisterPanel(new AppPanelDefinition
            {
                Uid           = panel_definition.get("uid", null) as string,
                PositionIndex = (int)panel_definition.get("position_index", 0),
                ViewSource    = (string)panel_definition.get("view_source", null)
            });
        }
コード例 #5
0
        private bool ValidateUser(PythonDictionary context)
        {
            var handlerPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web", "authorization_handler.py");

            if (!File.Exists(handlerPath))
            {
                return(false);
            }

            var code = File.ReadAllText(handlerPath);

            var scriptEngine = IronPython.Hosting.Python.CreateEngine();
            //scriptEngine.Runtime.IO.SetOutput(new PythonIOStream(_logger.), Encoding.UTF8);

            var scriptScope  = scriptEngine.CreateScope();
            var scriptSource = scriptScope.Engine.CreateScriptSourceFromString(code, SourceCodeKind.File);
            var compiledCode = scriptSource.Compile();

            compiledCode.Execute(scriptScope);
            var function = scriptScope.Engine.Operations.GetMember <PythonFunction>(scriptScope, "handle_authenticate");

            scriptScope.Engine.Operations.Invoke(function, context);

            return(context.get("is_authenticated", false) as bool? == true);
        }
コード例 #6
0
        public void publish(PythonDictionary parameters)
        {
            if (parameters == null) throw new ArgumentNullException(nameof(parameters));

            var topic = Convert.ToString(parameters.get("topic"));
            var payload = parameters.get("payload", new byte[0]);
            var qos = Convert.ToInt32(parameters.get("qos", 0));
            var retain = Convert.ToBoolean(parameters.get("retain", false));

            _mqttService.Publish(new MqttPublishParameters
            {
                Topic = topic,
                Payload = ConvertPayload(payload),
                QualityOfServiceLevel = (MqttQualityOfServiceLevel)qos,
                Retain = retain
            });
        }
コード例 #7
0
        private void Publish(PythonDictionary parameters)
        {
            try
            {
                var applicationMessageBuilder = new MqttApplicationMessageBuilder()
                                                .WithTopic((string)parameters.get("topic", null))
                                                .WithRetainFlag((bool)parameters.get("retain", false))
                                                .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)(int)parameters.get("qos", 0));

                var    payload = parameters.get("payload", null);
                byte[] binaryPayload;

                if (payload == null)
                {
                    binaryPayload = new byte[0];
                }
                else if (payload is string stringPayload)
                {
                    binaryPayload = Encoding.UTF8.GetBytes(stringPayload);
                }
                else if (payload is ByteArray byteArray)
                {
                    binaryPayload = byteArray.ToArray();
                }
                else if (payload is IEnumerable <int> intArray)
                {
                    binaryPayload = intArray.Select(Convert.ToByte).ToArray();
                }
                else
                {
                    throw new NotSupportedException("Payload type not supported.");
                }

                applicationMessageBuilder = applicationMessageBuilder
                                            .WithPayload(binaryPayload);

                var applicationMessage = applicationMessageBuilder.Build();

                _mqttServer.PublishAsync(applicationMessage).GetAwaiter().GetResult();
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Error while publishing application message from server.");
            }
        }
コード例 #8
0
        async Task <ICoapClient> CreateClient(PythonDictionary parameters)
        {
            var host     = Convert.ToString(parameters.get("host", string.Empty));
            var port     = Convert.ToInt32(parameters.get("port", 5684));
            var protocol = Convert.ToString(parameters.get("protocol", "dtls"));
            var identity = Convert.ToString(parameters.get("identity", string.Empty));
            var key      = Convert.ToString(parameters.get("key", string.Empty));
            var timeout  = Convert.ToInt32(parameters.get("timeout", 5000));

            var connectOptionsBuilder = new CoapClientConnectOptionsBuilder()
                                        .WithHost(host)
                                        .WithPort(port);

            if (protocol == "dtls")
            {
                connectOptionsBuilder.WithDtlsTransportLayer(o => o.WithPreSharedKey(identity, key));
            }

            var connectOptions = connectOptionsBuilder.Build();

            var coapClient = new CoapFactory().CreateClient();

            using (var cancellationTokenSource = new CancellationTokenSource(timeout))
            {
                await coapClient.ConnectAsync(connectOptions, cancellationTokenSource.Token).ConfigureAwait(false);
            }

            return(coapClient);
        }
コード例 #9
0
        private static HttpRequestMessage CreateRequest(PythonDictionary parameters)
        {
            var uri     = Convert.ToString(parameters.get("uri"));
            var method  = Convert.ToString(parameters.get("method", "get"));
            var headers = (PythonDictionary)parameters.get("headers", new PythonDictionary());

            var request = new HttpRequestMessage
            {
                Method     = new HttpMethod(method),
                RequestUri = new Uri(uri, UriKind.Absolute)
            };

            foreach (var header in headers)
            {
                var headerName  = Convert.ToString(header.Key, CultureInfo.InvariantCulture);
                var headerValue = Convert.ToString(header.Value, CultureInfo.InvariantCulture);

                request.Headers.TryAddWithoutValidation(headerName, headerValue);
            }

            return(request);
        }
コード例 #10
0
ファイル: OSPythonProxy.cs プロジェクト: mfr78/Wirehome.Core
        private static LaunchParamters ParseLaunchParameters(PythonDictionary pythonDictionary)
        {
            var launchParameters = new LaunchParamters
            {
                FileName = Convert.ToString(pythonDictionary.get("file_name", null)),
                Timeout  = Convert.ToInt32(pythonDictionary.get("timeout", 60000))
            };

            var arguments = pythonDictionary.get("arguments", null);

            if (arguments is string argumentsText)
            {
                launchParameters.Arguments.Add(argumentsText);
            }
            else if (arguments is List argumentsList)
            {
                foreach (var argument in argumentsList)
                {
                    launchParameters.Arguments.Add(Convert.ToString(argument));
                }
            }

            return(launchParameters);
        }
コード例 #11
0
        public string start_topic_import(string uid, PythonDictionary parameters)
        {
            if (parameters == null) throw new ArgumentNullException(nameof(parameters));

            var topicImportParameters = new MqttImportTopicParameters
            {
                Server = Convert.ToString(parameters.get("server")),
                Port = Convert.ToInt32(parameters.get("port", 1883)),
                UseTls = Convert.ToBoolean(parameters.get("tls", false)),
                Username = Convert.ToString(parameters.get("username")),
                Password = Convert.ToString(parameters.get("password")),
                ClientId = Convert.ToString(parameters.get("client_id", Guid.NewGuid().ToString("N"))),
                Topic = Convert.ToString(parameters.get("topic")),
                QualityOfServiceLevel = (MqttQualityOfServiceLevel)Convert.ToInt32(parameters.get("qos"))
            };

            return _mqttService.StartTopicImport(uid, topicImportParameters);
        }
コード例 #12
0
ファイル: MacroProxy.cs プロジェクト: eksotama/Accounting.NET
        public string call(string macroName, PythonDictionary parameters = null)
        {
            var macro  = _context.Macros.FirstOrDefault(o => o.Name == macroName);
            var script = macro.Script;

            if (parameters != null)
            {
                var macroParameters = new MacroScriptParameters();
                foreach (var k in parameters.keys())
                {
                    macroParameters.SetParameter((string)k, (string)parameters.get((string)k));
                }
                script = macroParameters.ReplaceParameters(macro);
            }
            var result = _runner.RunScript(script, _ledger, _context);

            return(result);
        }
コード例 #13
0
        public PythonDictionary send(PythonDictionary parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            try
            {
                using (var httpClient = new HttpClient())
                    using (var request = CreateRequest(parameters))
                    {
                        var response = httpClient.SendAsync(request).GetAwaiter().GetResult();
                        var content  = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();

                        var result = new PythonDictionary
                        {
                            ["type"]        = ControlType.Success,
                            ["status_code"] = (int)response.StatusCode
                        };

                        var responseContentType = Convert.ToString(parameters.get("response_content_type", "text"));
                        if (responseContentType == "raw")
                        {
                            var rawContent = new List();
                            foreach (var contentByte in content)
                            {
                                rawContent.Add(contentByte);
                            }

                            result["content"] = rawContent;
                        }
                        else if (responseContentType == "text")
                        {
                            result["content"] = Encoding.UTF8.GetString(content);
                        }
                        else if (responseContentType == "json")
                        {
                            var jsonString = Encoding.UTF8.GetString(content);
                            if (!string.IsNullOrEmpty(jsonString))
                            {
                                try
                                {
                                    var json = JObject.Parse(jsonString);

                                    var convertedJson = PythonConvert.ToPython(json);
                                    result["content"] = convertedJson;
                                }
                                catch (Exception exception)
                                {
                                    return(new ExceptionPythonModel(exception).ConvertToPythonDictionary());
                                }
                            }
                        }

                        return(result);
                    }
            }
            catch (Exception exception)
            {
                return(new ExceptionPythonModel(exception).ConvertToPythonDictionary());
            }
        }
コード例 #14
0
ファイル: Arguments.cs プロジェクト: Zinterax/meddle
        public Argument(PythonBoss pyBoss, long address, PythonDictionary spec, Process process, int depth, Arguments parent, string namePrefix)
        {
            Address = address;
            this.process = process;
            _pyBoss = pyBoss;
            _parent = parent;
            NamePrefix = namePrefix;

            // Parse the spec for this argument
            // stackspec: [{"name": "socket",
            //		      "size": 4,
            //		      "type": None,
            //		      "fuzz": NOFUZZ,
            //            "type_args": None},]

            Fuzz = (bool)spec.get("fuzz");
            Name = (string)spec.get("name");
            _argumentType = (object)spec.get("type");
            if ( spec.ContainsKey("type_args") )
            {
                _typeArgs = spec.get("type_args");
            }

            // Validate required fields
            if (Name == null)
                throw new Exception("ERROR: Argument specification must include 'name' attribute. Failed when parsing name prefix '" + namePrefix + "'.");
            else if (Fuzz == null)
                throw new Exception("ERROR: Argument specification must include 'fuzz' attribute. Failed when parsing type '" + namePrefix + Name + "'.");
            else if (spec.get("size") == null)
                throw new Exception("ERROR: Argument specification must include 'size' attribute. Failed when parsing type '" + namePrefix + Name + "'.");

            if (spec.get("size") is string)
            {
                object sizeArgument = null;
                if (parent.TryGetMemberSearchUp((string)spec.get("size"), out sizeArgument))
                    Size = ((Argument)sizeArgument).ToInt();
                else
                    throw new Exception("ERROR: Unable to load size for type '" + Name + "' from parent member named '" + (string)spec.get("size") + "'. Please make sure this field exists in the parent.");
            }
            else if (spec.get("size") is int)
            {
                Size = (int)spec.get("size");
            }
            else
            {
                throw new Exception("ERROR: Unable to load size for type '" + Name + "'. The size must be of type 'int' or type 'string'. Size is type: '" + spec.get("size").ToString() + "'" );
            }

            // Read the data
            try
            {
                Data = MemoryFunctions.ReadMemory(process.ProcessDotNet, address, (uint)Size);
            }
            catch (Exception e)
            {
                Data = null;
            }

            PointerTarget = null;
        }
コード例 #15
0
        public WirehomeDictionary publish_external(PythonDictionary parameters)
        {
            var server   = Convert.ToString(parameters.get("server"));
            var port     = Convert.ToInt32(parameters.get("port", 1883));
            var username = Convert.ToString(parameters.get("username"));
            var password = Convert.ToString(parameters.get("password"));
            var clientId = Convert.ToString(parameters.get("client_id", Guid.NewGuid().ToString("N")));
            var topic    = Convert.ToString(parameters.get("topic"));
            var qos      = Convert.ToInt32(parameters.get("qos", 0));
            var retain   = Convert.ToBoolean(parameters.get("retain", false));
            var tls      = Convert.ToBoolean(parameters.get("tls", false));
            var timeout  = Convert.ToInt32(parameters.get("timeout", 5000));
            var payload  = parameters.get("payload", null);

            var mqttClient = new MqttFactory().CreateMqttClient();

            try
            {
                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(server, port)
                              .WithCredentials(username, password)
                              .WithClientId(clientId)
                              .WithCommunicationTimeout(TimeSpan.FromMilliseconds(timeout))
                              .WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = tls
                })
                              .Build();

                mqttClient.ConnectAsync(options).GetAwaiter().GetResult();

                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(topic)
                              .WithPayload(ConvertPayload(payload))
                              .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qos)
                              .WithRetainFlag(retain)
                              .Build();

                mqttClient.PublishAsync(message).GetAwaiter().GetResult();

                return(new WirehomeDictionary().WithType("success"));
            }
            catch (MqttConnectingFailedException)
            {
                return(new WirehomeDictionary().WithType("exception.connecting_failed"));
            }
            catch (Exception exception)
            {
                return(new ExceptionPythonModel(exception).ConvertToPythonDictionary());
            }
            finally
            {
                mqttClient?.DisconnectAsync().GetAwaiter().GetResult();
                mqttClient?.Dispose();
            }
        }
コード例 #16
0
ファイル: Arguments.cs プロジェクト: stallonederek/meddle
        public Argument(PythonBoss pyBoss, long address, PythonDictionary spec, Process process, int depth, Arguments parent, string namePrefix)
        {
            Address      = address;
            this.process = process;
            _pyBoss      = pyBoss;
            _parent      = parent;
            NamePrefix   = namePrefix;


            // Parse the spec for this argument
            // stackspec: [{"name": "socket",
            //		      "size": 4,
            //		      "type": None,
            //		      "fuzz": NOFUZZ,
            //            "type_args": None},]

            Fuzz          = (bool)spec.get("fuzz");
            Name          = (string)spec.get("name");
            _argumentType = (object)spec.get("type");
            if (spec.ContainsKey("type_args"))
            {
                _typeArgs = spec.get("type_args");
            }


            // Validate required fields
            if (Name == null)
            {
                throw new Exception("ERROR: Argument specification must include 'name' attribute. Failed when parsing name prefix '" + namePrefix + "'.");
            }
            else if (Fuzz == null)
            {
                throw new Exception("ERROR: Argument specification must include 'fuzz' attribute. Failed when parsing type '" + namePrefix + Name + "'.");
            }
            else if (spec.get("size") == null)
            {
                throw new Exception("ERROR: Argument specification must include 'size' attribute. Failed when parsing type '" + namePrefix + Name + "'.");
            }


            if (spec.get("size") is string)
            {
                object sizeArgument = null;
                if (parent.TryGetMemberSearchUp((string)spec.get("size"), out sizeArgument))
                {
                    Size = ((Argument)sizeArgument).ToInt();
                }
                else
                {
                    throw new Exception("ERROR: Unable to load size for type '" + Name + "' from parent member named '" + (string)spec.get("size") + "'. Please make sure this field exists in the parent.");
                }
            }
            else if (spec.get("size") is int)
            {
                Size = (int)spec.get("size");
            }
            else
            {
                throw new Exception("ERROR: Unable to load size for type '" + Name + "'. The size must be of type 'int' or type 'string'. Size is type: '" + spec.get("size").ToString() + "'");
            }

            // Read the data
            try
            {
                Data = MemoryFunctions.ReadMemory(process.ProcessDotNet, address, (uint)Size);
            }
            catch (Exception e)
            {
                Data = null;
            }


            PointerTarget = null;
        }
コード例 #17
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey(HeaderNames.Authorization))
            {
                return(AuthenticateResult.NoResult());
            }

            try
            {
                var headerValue       = Request.Headers[HeaderNames.Authorization];
                var parsedHeaderValue = AuthenticationHeaderValue.Parse(Request.Headers[HeaderNames.Authorization]);

                var    scheme    = parsedHeaderValue.Scheme;
                var    parameter = parsedHeaderValue.Parameter;
                string username  = null;
                string password  = null;

                if (scheme.Equals("Basic", StringComparison.OrdinalIgnoreCase))
                {
                    var credentialBytes = Convert.FromBase64String(parsedHeaderValue.Parameter);
                    var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(':');
                    username = credentials[0];
                    password = credentials[1];
                }

                var context = new PythonDictionary
                {
                    ["header_value"]     = headerValue,
                    ["scheme"]           = scheme,
                    ["parameter"]        = parameter,
                    ["username"]         = username,
                    ["password"]         = password,
                    ["is_authenticated"] = false
                };

                if (!ValidateUser(context))
                {
                    return(AuthenticateResult.Fail("Invalid credentials."));
                }

                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.get("username") as string ?? string.Empty)
                };

                var identity  = new ClaimsIdentity(claims, Scheme.Name);
                var principal = new ClaimsPrincipal(identity);
                var ticket    = new AuthenticationTicket(principal, Scheme.Name);

                return(AuthenticateResult.Success(ticket));
            }
            catch (Exception exception)
            {
                _logger.LogWarning("Error while authenticating user.", exception);

                return(AuthenticateResult.Fail(exception));
            }
            finally
            {
                await Task.CompletedTask;
            }
        }
コード例 #18
0
        public PythonDictionary request(PythonDictionary parameters)
        {
            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            try
            {
                var clientUid = Convert.ToString(parameters.get("client_uid", string.Empty));
                var timeout   = Convert.ToInt32(parameters.get("timeout", 5000));

                var          request = CreateRequest(parameters);
                CoapResponse response;

                if (!string.IsNullOrEmpty(clientUid))
                {
                    ICoapClient coapClient;
                    lock (_clients)
                    {
                        if (!_clients.TryGetValue(clientUid, out coapClient))
                        {
                            coapClient          = CreateClient(parameters).GetAwaiter().GetResult();
                            _clients[clientUid] = coapClient;
                        }
                    }

                    try
                    {
                        using (var cancellationTokenSource = new CancellationTokenSource(timeout))
                        {
                            response = coapClient.RequestAsync(request, cancellationTokenSource.Token).GetAwaiter().GetResult();
                        }
                    }
                    catch
                    {
                        coapClient.Dispose();

                        lock (_clients)
                        {
                            _clients.Remove(clientUid);
                        }

                        throw;
                    }
                }
                else
                {
                    using (var coapClient = CreateClient(parameters).GetAwaiter().GetResult())
                    {
                        using (var cancellationTokenSource = new CancellationTokenSource(timeout))
                        {
                            response = coapClient.RequestAsync(request, cancellationTokenSource.Token).GetAwaiter().GetResult();
                        }
                    }
                }

                return(new PythonDictionary
                {
                    ["type"] = WirehomeMessageType.Success,
                    ["status"] = response.StatusCode.ToString(),
                    ["status_code"] = (int)response.StatusCode,
                    ["payload"] = new Bytes(response.Payload ?? Array.Empty <byte>())
                });
            }
            catch (Exception exception)
            {
                return(new PythonDictionary
                {
                    ["type"] = WirehomeMessageType.Exception,
                    ["message"] = exception.Message
                });
            }
        }