Esempio n. 1
1
        public IActionResult StartPsScript([FromQuery] DTOScript scriptFromQuery)
        {
            string key = _config.GetValue <string>("key");

            if (!string.Equals(key, scriptFromQuery.key))
            {
                return(Unauthorized(new DTOResult {
                    isCompletedSuccessfully = false,
                    message = "Invalid key. Please provide a valid key to make a webhook."
                }));
            }

            string stdout = _scriptRunner.Run(scriptFromQuery);

            return(Ok(new DTOResult {
                isCompletedSuccessfully = true,
                scriptName = scriptFromQuery.script,
                param = scriptFromQuery.param,
                output = stdout
            }));
        }
Esempio n. 2
0
        public async Task InstallGpu()
        {
            if (await phone.GetModel() != PhoneModel.Cityman)
            {
                var ex = new InvalidOperationException("This phone is not a Lumia 950 XL");
                Log.Error(ex, "Phone isn't a Lumia 950 XL");

                throw ex;
            }

            Log.Information("Installing GPU");
            await phone.EnsureBootPartitionIs(PartitionType.Basic);

            IList <Sentence> sentences = new List <Sentence>()
            {
                new Sentence(new Command(nameof(GitHubUnpack), new[] { new Argument("https://github.com/gus33000/MSM8994-8992-NT-ARM64-Drivers"), })),
                new Sentence(new Command(nameof(CopyDirectory), new[]
                {
                    new Argument(@"Downloaded\MSM8994-8992-NT-ARM64-Drivers-master\Supplemental\GPU\Cityman"),
                    new Argument(@"WindowsARM\Users\Public\OEMPanel"),
                })),
            };

            await scriptRunner.Run(new Script(sentences));
        }
        /// <summary>
        /// Returns all of the known migrations in order by migration number by extracting the migration number from the digits in the beginning of the filename
        /// Online migrations are identified by the string "online " following the migration number.
        /// </summary>
        /// <returns></returns>
        public IReadOnlyList <Migration> GatherMigrations()
        {
            MD5 md5   = MD5.Create();
            var files = Directory.GetFiles(_migrationsDirectory, _migrationsFileWildcard);

            return(files
                   .Select(
                       file =>
            {
                var filename = Path.GetFileName(file);

                // extract the migration number and name separately from the filename
                int migrationNumber = 0;
                string name = "";
                if (string.IsNullOrEmpty(filename) || !Char.IsDigit(filename[0]))
                {
                    throw new Exception("Migration script filenames must begin with a digit.");
                }

                var digits = new Stack <char>(filename.Length);
                bool isOnline = false;
                for (int i = 0; i < filename.Length; i++)
                {
                    char c = filename[i];
                    if (Char.IsDigit(c))
                    {
                        digits.Push(c);
                    }
                    else
                    {
                        name = filename.Substring(i).Trim();
                        if (name.StartsWith("online ", StringComparison.OrdinalIgnoreCase))
                        {
                            isOnline = true;
                            name = name.Substring(7).Trim();
                        }
                        break;
                    }
                }
                for (int placeValue = 1; digits.Count > 0; placeValue *= 10)
                {
                    int digitValue = digits.Pop() - '0';
                    migrationNumber += digitValue * placeValue;
                }
                using (var fs = File.OpenRead(file))
                {
                    using (var streamReader = new StreamReader(fs, Encoding.UTF8, true))
                    {
                        var contents = streamReader.ReadToEnd();
                        var hash = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(contents)));

                        return new Migration(migrationNumber, name.ToString(), hash, isOnline, pr => _scriptRunner.Run(contents));
                    }
                }
            }
                       )
                   .OrderBy(m => m.MigrationNumber)
                   .ToList());
        }
Esempio n. 4
0
 public bool Execute(CakeOptions options)
 {
     if (options == null)
     {
         throw new ArgumentNullException("options");
     }
     _scriptRunner.Run(_host, options.Script, options.Arguments);
     return(true);
 }
Esempio n. 5
0
        /// <summary>
        /// throws an exception if git acccess fails for some reason
        /// </summary>
        /// <param name="environment">e.g. "Vanilla"</param>
        /// <param name="suppressLog"></param>
        /// <returns>false if there were changes in the working directory
        ///   and the list of modified files (or any extraneous output from "git status --short"</returns>
        public (bool clean, string errorMessage) IsClean(string environment, bool suppressLog)
        {
            (int exitCode, string[] outputs) = scriptRunner.Run(
                Constants.DetectChangesScriptId, scriptRunner.DefaultEnv, suppressLog, Path.Combine(this.testDataPath, environment));
            // e.g. "C:\alt\projs\dasblog-core\source\DasBlog.Tests\Resources\Environments\Vanilla"
            if (exitCode != 0)
            {
                FormatErrorsAndThrow(Constants.DetectChangesScriptId, exitCode, outputs);
            }
            int numChanges = outputs.Count(o => !string.IsNullOrWhiteSpace(o));

            if (numChanges > 0)
            {
                return(false, "working directory contains modified files:" + Environment.NewLine
                       + string.Join(Environment.NewLine, outputs.Where(o => !string.IsNullOrWhiteSpace(o))));
            }
            return(true, string.Empty);
        }
Esempio n. 6
0
        public static void RunScript(ParameterDic initialParameters, bool cloneParameters, params IScriptCommand[] commands)
        {
            if (cloneParameters)
            {
                initialParameters = initialParameters.Clone();
            }

            IScriptRunner runner = initialParameters.GetValue <IScriptRunner>("{ScriptRunner}", Instance);

            runner.Run(new Queue <IScriptCommand>(commands), initialParameters);
        }
Esempio n. 7
0
        public async Task Deploy()
        {
            var dict = new Dictionary <PhoneModel, string>
            {
                { PhoneModel.Talkman, Path.Combine("Scripts", "950.txt") },
                { PhoneModel.Cityman, Path.Combine("Scripts", "950xl.txt") },
            };

            var phoneModel = await phone.GetModel();

            var path = dict[phoneModel];

            await scriptRunner.Run(parser.Parse(File.ReadAllText(path)));
        }
Esempio n. 8
0
        public bool Execute(CakeOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.Exclusive)
            {
                _host.Settings.UseExclusiveTarget();
            }

            _scriptRunner.Run(_host, options.Script, options.Arguments);
            return(true);
        }
Esempio n. 9
0
        public bool Execute(CakeOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _log.Debug("Performing debug...");
            _log.Information(Verbosity.Quiet, "Attach debugger to process {0} to continue", _debugger.GetProcessId());

            _debugger.WaitForAttach(Timeout.InfiniteTimeSpan);
            _log.Debug("Debugger attached");

            _scriptRunner.Run(_host, options.Script, options.Arguments);

            return(true);
        }
Esempio n. 10
0
        public async Task Deploy()
        {
            var dict = new Dictionary <PhoneModel, string>
            {
                { PhoneModel.Talkman, Path.Combine("Scripts", "950.txt") },
                { PhoneModel.Cityman, Path.Combine("Scripts", "950xl.txt") },
            };

            var phoneModel = await phone.GetModel();

            Log.Verbose("{Model} detected", phoneModel);
            var path = dict[phoneModel];

            await scriptRunner.Run(parser.Parse(File.ReadAllText(path)));

            await PreparePhoneDiskForSafeRemoval();
        }
Esempio n. 11
0
 /// <summary>
 /// Execute the IScriptRunner.Run method in the compiled_assembly
 /// </summary>
 /// <param name="compiled_assembly">compiled assembly</param>
 /// <param name="args">method arguments</param>
 /// <returns>object returned</returns>
 public static object Run(Assembly compiled_assembly, object[] args, PermissionSet permission_set)
 {
     if (compiled_assembly != null)
     {
         // security is not implemented yet !NIY
         // using Utilties.PrivateStorage was can save but not diaplay in Notepad
         // plus the output is saved in C:\Users\<user>\AppData\Local\IsolatedStorage\...
         // no contral over where to save make QuranCode unportable applicaton, which is a no no
         //// restrict code security
         //permission_set.PermitOnly();
         foreach (Type type in compiled_assembly.GetExportedTypes())
         {
             foreach (Type interface_type in type.GetInterfaces())
             {
                 if (interface_type == typeof(IScriptRunner))
                 {
                     ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes);
                     if ((constructor != null) && (constructor.IsPublic))
                     {
                         // construct object using default constructor
                         IScriptRunner obj = constructor.Invoke(null) as IScriptRunner;
                         if (obj != null)
                         {
                             return(obj.Run(args));
                         }
                         else
                         {
                             throw new Exception("Invalid C# code!");
                         }
                     }
                     else
                     {
                         throw new Exception("No default constructor was found!");
                     }
                 }
                 else
                 {
                     throw new Exception("IScriptRunner is not implemented!");
                 }
             }
         }
         // revert security restrictions
         //CodeAccessPermission.RevertPermitOnly();
     }
     return(null);
 }
Esempio n. 12
0
        public bool Execute(CakeOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.Exclusive)
            {
                _host.Settings.UseExclusiveTarget();
            }

            if (!string.IsNullOrWhiteSpace(options.ContinueFromTaskName))
            {
                _host.Settings.SetContinueFromTask(options.ContinueFromTaskName);
            }

            _scriptRunner.Run(_host, options.Script, options.Arguments);
            return(true);
        }
Esempio n. 13
0
        public RateResult Rate(Policy policy, IDataContext db)
        {
            RateResult result = new RateResult();

            result.Success = false;
            try
            {
                //var policy = _db.Policies.Find(policyID);
                var profile = GetEffectiveProfile(policy);

                if (profile == null)
                {
                    result.Message = "No rating profile";
                    return(result);
                }

                switch (profile.Engine)
                {
                case "InRule":
                    throw new NotImplementedException();

                case "Script":
                    var scriptResult = _scriptEngine.Run <Policy>(policy, "policy", db, profile.Script, profile.ScriptLanguage);
                    result.Success = scriptResult.Success;
                    result.Log.AddRange(scriptResult.Log);
                    break;
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                result.Log.Add(ex.Message);
            }

            return(result);
        }
 private string ExecuteScriptLocally(string scriptBody, ScriptType scriptType)
 {
     return(_scriptRunner.Run(scriptBody, scriptType));
 }
 /// <summary>
 /// Execute an Explorer command.
 /// </summary>
 /// <param name="command"></param>
 /// <param name="parameterDic">Will be merged with parameters from ParameterDicConverter</param>
 /// <param name="scriptRunner"></param>
 public static void Execute(this ICommandManager commandManager, IScriptCommand[] commands, ParameterDic parameterDic = null, IScriptRunner scriptRunner = null)
 {
     scriptRunner = scriptRunner ?? new ScriptRunner();
     scriptRunner.Run(commandManager.ParameterDicConverter.ConvertAndMerge(parameterDic), commands);
 }
Esempio n. 16
0
        public PolicyTransitionResponse Transition(Policy policy, PolicyTransitionRequest request, IDataContext db)
        {
            PolicyTransitionResponse response = new PolicyTransitionResponse();

            try
            {
                var transition = db.PolicyTypeTransitions.Find(request.PolicyTypeTransitionID);

                foreach (var journal in transition.JournalTemplates)
                {
                    var targetEntities = policy.ReportingEntities.Where(x => x.PolicyTypeEntityRequirementID == journal.EntityRequirementID).ToList();

                    foreach (var entity in targetEntities)
                    {
                        if (!String.IsNullOrEmpty(journal.Condition))
                        {
                            Dictionary <string, object> exprParameters = new Dictionary <string, object>();
                            exprParameters.Add("policy", policy);
                            exprParameters.Add("request", request);
                            if (!_scriptEngine.ResolveExpression <bool>(exprParameters, db, journal.Condition, "Python"))
                            {
                                continue;
                            }
                        }

                        TransactionTrigger       txnTrigger = new TransactionTrigger();
                        PolicyTransactionTrigger ptxTrigger = new PolicyTransactionTrigger();
                        ptxTrigger.TransactionTrigger = txnTrigger;
                        policy.TransactionTriggers.Add(ptxTrigger);

                        txnTrigger.ReportingEntity             = entity.ReportingEntity;
                        txnTrigger.Description                 = journal.JournalTemplate.Description;
                        txnTrigger.JournalTemplate             = journal.JournalTemplate;
                        txnTrigger.Status                      = journal.TransactionTriggerStatus;
                        txnTrigger.TransactionTriggerFrequency = journal.TransactionTriggerFrequency;

                        if (journal.TxnDateInputID.HasValue)
                        {
                            var strValue = request.Inputs.First(x => x.PolicyTypeTransitionInputID == journal.TxnDateInputID.Value).Value;
                            txnTrigger.NextExecutionDate = DateTime.Parse(strValue);
                            txnTrigger.TxnDate           = DateTime.Parse(strValue);
                        }

                        foreach (var input in journal.Inputs)
                        {
                            TransactionTriggerInput txInput = new TransactionTriggerInput();
                            txnTrigger.Inputs.Add(txInput);
                            txInput.JournalTemplateInputID = input.JournalTemplateInputID;

                            if (input.PolicyTypeTransitionInputID.HasValue)
                            {
                                var strValue = request.Inputs.First(x => x.PolicyTypeTransitionInputID == input.PolicyTypeTransitionInputID.Value).Value;
                                txInput.Value = strValue;
                            }

                            if (!String.IsNullOrEmpty(input.Expression))
                            {
                                var exprResult = _scriptEngine.ResolveExpression <TransactionTriggerInput>(txInput, "input", db, input.Expression, "Python");
                                txInput.Value = Convert.ToString(exprResult);
                            }
                        }
                    }
                }

                if (!String.IsNullOrEmpty(transition.Script))
                {
                    Dictionary <string, object> scriptParameters = new Dictionary <string, object>();
                    scriptParameters.Add("policy", policy);
                    scriptParameters.Add("request", request);
                    var scriptResult = _scriptEngine.Run(scriptParameters, db, transition.Script, "Python");
                    if (!scriptResult.Success)
                    {
                        string errMsg = string.Empty;
                        foreach (var s in scriptResult.Log)
                        {
                            errMsg += s;
                        }
                        throw new Exception(errMsg);
                    }
                }

                policy.Status    = transition.TargetStatus;
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }

            return(response);
        }
Esempio n. 17
0
 public static void Run(this IScriptRunner scriptRunner, ParameterDic initialParameters, params IScriptCommand[] cmds)
 {
     scriptRunner.Run(new Queue <IScriptCommand>(cmds), initialParameters);
 }
        public void ProcessCommand(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                Log.Info("Commands processing cancellation is requested");
                return;
            }

            var ipAddress = DomainContext.IPAddress;

            if (ipAddress.IsNullOrWhiteSpace())
            {
                ipAddress = "*";  // Bind to all interfaces
            }
            var portNumber = DomainContext.PortNumber;
            var endpoint   = "tcp://{0}:{1}".FormatString(ipAddress, portNumber);

            var encryptionKey  = DomainContext.TargetKey;
            var encryptionSalt = DomainContext.ServerKey;

            using (var context = NetMQContext.Create())
            {
                using (var socket = context.CreateResponseSocket())
                {
                    Log.Info("{0}Listening...", Environment.NewLine);
                    socket.Bind(endpoint);

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var encryptedJson = socket.ReceiveString(Encoding.UTF8);
                        Log.Info("Command received");

                        string output;

                        try
                        {
                            Log.Info("Decrypting...");
                            var json = EncryptionHelper.Decrypt(encryptedJson, encryptionKey, encryptionSalt);

                            Log.Info("Deserializing...");
                            var command = JsonConvert.DeserializeObject <ScriptExecutionCommand>(json);
                            // if (command.CommandTime.AddSeconds(60) < DateTime.UtcNow)
                            //     throw new TimeoutException();  // To prevent re-execution of script by using sniffed packet.

                            Log.Info("Executing {0} script...", command.ScriptType);
                            output = _scriptRunner.Run(command.ScriptBody, command.ScriptType.ToEnum <ScriptType>());
                            Log.Success("Script executed");
                        }
                        catch (Exception ex)
                        {
                            Log.Exception(ex);
                            output = ex.GetAllMessagesWithStackTraces();
                        }

                        Log.Info("Sending results...");
                        var encryptedOutput = EncryptionHelper.Encrypt(output, encryptionKey, encryptionSalt);
                        socket.Send(encryptedOutput, Encoding.UTF8);
                        Log.Success("Results sent");
                    }
                }
            }
        }
Esempio n. 19
0
        public async Task Deploy()
        {
            var scriptPath = Path.Combine("Scripts", "Deployment.txt");

            await scriptRunner.Run(parser.Parse(File.ReadAllText(scriptPath)));
        }