Esempio n. 1
0
        private void ExecuteList(IStream io, params string[] tokens)
        {
            var path = downloads;

            if (tokens.Length == 3)
            {
                var dir = tokens[2];
                AssertTools.True(PathTools.HasDirectChild(downloads, dir), "Directory not found {0}", dir);
                path = PathTools.Combine(downloads, dir);
            }

            var total = 0;

            foreach (var file in Directory.GetDirectories(path))
            {
                total++; //remove final \ as well
                io.WriteLine("{0}", file.Substring(path.Length + 1));
            }
            io.WriteLine("{0} total directories", total);
            total = 0;
            foreach (var file in Directory.GetFiles(path))
            {
                total++; //remove final \ as well
                var furi = new Uri(file);
                io.WriteLine("{0}", file.Substring(path.Length + 1));
            }
            io.WriteLine("{0} total files", total);
        }
Esempio n. 2
0
        private void ExecuteDelete(IStream io, params string[] tokens)
        {
            var dir = tokens[2];

            AssertTools.True(PathTools.HasDirectChild(downloads, dir), "Directory {0} not found", dir);
            Directory.Delete(PathTools.Combine(downloads, dir), true);
            io.WriteLine("Directory {0} deleted", dir);
        }
Esempio n. 3
0
        private void ExecuteKill(IStream io, params string[] tokens)
        {
            var id = tokens[2];

            clients.TryGetValue(id, out var rt);
            AssertTools.True(rt != null, "Client {0} not found", id);
            rt.Dispose();
            io.WriteLine("Client {0} killed", id);
        }
Esempio n. 4
0
        private void ExecuteKill(IStream io, params string[] tokens)
        {
            var id = tokens[2];

            running.TryGetValue(id, out var rt);
            AssertTools.True(rt != null, "Daemon {0} not found", id);
            Process.GetProcessById(rt.Pid).Kill();
            io.WriteLine("Daemon {0} killed", id);
        }
Esempio n. 5
0
        private void ExecuteUninstall(IStream io, params string[] tokens)
        {
            var id = tokens[2];

            installed.TryGetValue(id, out var dto);
            AssertTools.True(dto != null, "Daemon {0} not found", id);
            Database.Remove(database, id);
            io.WriteLine("Daemon {0} uninstalled", id);
            ReloadDatabase();
        }
Esempio n. 6
0
        public void Add(TKey key, TValue value)
        {
            AssertTools.IsNotNull(key);
            _dict[key] = value;
            _linkedList.Remove(key);
            _linkedList.AddFirst(key);

            if (_linkedList.Count > _capacity)
            {
                //Try to remove last
                Remove(_linkedList.Last.Value);
            }
        }
Esempio n. 7
0
        //https://stackoverflow.com/questions/18924789/directory-move-access-to-path-is-denied
        //netcore linux WSL System.IO.IOException: Access to the path
        //download zip and delete work ok at the same time
        private void ExecuteRename(IStream io, params string[] tokens)
        {
            var dir = tokens[2];

            AssertTools.True(PathTools.HasDirectChild(downloads, dir), "Directory {0} not found", dir);
            var path = PathTools.Combine(downloads, dir);

            var name = tokens[3];

            AssertTools.True(PathTools.IsChildPath(downloads, name), "Invalid new name {0}", name);
            var npath = PathTools.Combine(downloads, name);

            AssertTools.True(!Directory.Exists(npath), "Directory {0} already exist", name);

            Directory.Move(path, npath);
            io.WriteLine("Directory {0} renamed to {1}", dir, name);
        }
Esempio n. 8
0
    public void UnitMoves()
    {
        var systems = new Systems()
                      .Add(new UpdateUnitPosition(contexts.unit, contexts.globals));

        var testUnit = contexts.unit.CreateEntity();

        testUnit.AddPosition(new Vector2(0, 0));
        testUnit.AddDestination(new Vector2(2, 2));
        testUnit.AddMoveSpeed(1);

        for (int i = 0; i < 4; i++)
        {
            systems.Execute();
        }

        AssertTools.AreEqual(testUnit.position.value, new Vector2(2, 2), EPSILON);
    }
Esempio n. 9
0
        private void ExecuteZip(IStream io, params string[] tokens)
        {
            var uri     = new Uri(tokens[2], UriKind.Absolute);
            var request = (HttpWebRequest)WebRequest.Create(uri);

            request.Timeout = 5000;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                //https://www.nuget.org/api/v2/package/SharpSerial/1.0.1
                //redirects to https://globalcdn.nuget.org/packages/sharpserial.1.0.1.nupkg
                //io.WriteLine("Response URI : {0}...", response.ResponseUri);
                var zipfile = Path.GetFileName(response.ResponseUri.LocalPath);

                //Content-Disposition: attachment; filename="fname.ext"
                //nugets get application/octet-stream and empty disposition
                //to test Content-Disposition header use google drive link
                //SharpDaemon-sample.zip uploaded to drive with public link
                //https://docs.google.com/uc?export=download&id=1YgDnibq0waSbCYsobl3SIP_dSgD5DYbl
                var disposition = response.Headers["Content-Disposition"];
                //var mime = response.Headers["Content-Type"];
                //io.WriteLine("Content-Disposition : {0}...", disposition);
                //io.WriteLine("Content-Type : {0}...", mime);
                if (!string.IsNullOrEmpty(disposition))
                {
                    var header = new ContentDisposition(disposition);
                    if (!string.IsNullOrEmpty(header.FileName))
                    {
                        zipfile = header.FileName;
                    }
                }
                var zipdir     = zipfile; //do not remove dots
                var zipdirpath = Path.Combine(downloads, zipdir);
                AssertTools.True(PathTools.IsChildPath(downloads, zipdir), "Invalid directory name {0}", zipdir);
                AssertTools.True(!Directory.Exists(zipdirpath), "Download directory already exists {0}", zipdir);
                using (var zip = new ZipArchive(response.GetResponseStream()))
                {
                    Directory.CreateDirectory(zipdirpath);
                    zip.ExtractToDirectory(zipdirpath);
                    io.WriteLine("Downloaded to {0}", zipdir);
                }
            }
        }
Esempio n. 10
0
        private void ExecuteInstall(IStream io, params string[] tokens)
        {
            var id = tokens[2];

            installed.TryGetValue(id, out var dto);
            AssertTools.True(dto == null, "Daemon {0} already installed", id);
            AssertTools.True(Regex.IsMatch(id, "[a-zA_Z][a-zA_Z0-9_]*"), "Invalid id {0}", id);
            var exe = tokens[3];

            AssertTools.True(PathTools.IsChildPath(root, exe), "Invalid path {0}", exe);
            dto = new DaemonDto
            {
                Id   = id,
                Path = tokens[3],
                Args = DaemonProcess.MakeCli(tokens, 4),
            };
            var path = PathTools.Combine(root, dto.Path);

            AssertTools.True(File.Exists(path), "File {0} not found", dto.Path);
            Database.Save(database, dto);
            io.WriteLine("Daemon {0} installed as {1}", id, dto.Info("Path|Args"));
            ReloadDatabase();
        }
Esempio n. 11
0
        public void ClientRunNCmdTest()
        {
            using (var config = new Config())
            {
                TestTools.Shell(config, (shell) =>
                {
                    var tasks = new List <Task>();
                    var count = 20;
                    for (var i = 0; i < count; i++)
                    {
                        var task = Task.Run(() =>
                        {
                            //macos gets connection refused because shell not ready
                            Thread.Sleep(400);

                            TestTools.Client(config, (client, endpoint) =>
                            {
                                client.Execute(@"run cmd.exe");
                                client.WaitFor(400, @"<c Process \d+ has started");
                                client.WaitFor(400, @"<c Microsoft Windows");
                                client.Execute(@"cd c:\Users");
                                client.Execute(@"dir");
                                client.WaitFor(400, @"\d+ File");
                                client.WaitFor(400, @"\d+ Dir");
                                client.Execute(@"exit");                           //cmd.exe
                                client.WaitFor(400, @"<c Process \d+ has exited"); //prevent swallowing of exit!
                            });
                        });
                        tasks.Add(task);
                    }
                    //net462 works for 20 clients and 2000ms wait
                    //AggregateException showing array exceptions for each throwing task (confirmed)
                    AssertTools.True(Task.WaitAll(tasks.ToArray(), 2000), "Timeout waiting tasks");
                });
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            ProgramTools.Setup();

            var config = new Config();

            //args will always log to stderr because trace flag not loaded yet
            ExecutableTools.LogArgs(new StderrWriteLine(), args, (arg) =>
            {
                ConfigTools.SetProperty(config, arg);
            });

            AssertTools.NotEmpty(config.EndPoint, "Missing EndPoint");
            AssertTools.NotEmpty(config.Root, "Missing Root");

            if (!config.Daemon)
            {
                Logger.TRACE = new StderrWriteLine();
            }

            var uri  = string.Format("http://{0}/", config.EndPoint);
            var http = new HttpListener();

            http.Prefixes.Add(uri);
            http.Start();
            var accepter = new Runner(new Runner.Args {
                ThreadName = "Accepter"
            });
            var handler = new Runner(new Runner.Args {
                ThreadName = "Handler"
            });

            accepter.Run(() =>
            {
                while (http.IsListening)
                {
                    var ctx = http.GetContext();
                    handler.Run(() =>
                    {
                        var request  = ctx.Request;
                        var response = ctx.Response;
                        var pass     = true;
                        var file     = ctx.Request.RawUrl.Substring(1); //remove leading /
                        if (!PathTools.IsChildPath(config.Root, file))
                        {
                            pass = false;
                        }
                        var path = PathTools.Combine(config.Root, file);
                        Logger.Trace("File {0} {1}", file, path);
                        if (!File.Exists(path))
                        {
                            pass = false;
                        }
                        if (ctx.Request.HttpMethod != "GET")
                        {
                            pass = false;
                        }
                        if (pass)
                        {
                            var fi = new FileInfo(path);
                            var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                            ctx.Response.StatusCode      = (int)HttpStatusCode.OK;
                            ctx.Response.ContentLength64 = fi.Length;
                            ctx.Response.ContentType     = "application/octet-stream";
                            var data  = new byte[1024];
                            var count = fs.Read(data, 0, data.Length);
                            while (count > 0)
                            {
                                ctx.Response.OutputStream.Write(data, 0, count);
                                count = fs.Read(data, 0, data.Length);
                            }
                        }
                        else
                        {
                            ctx.Response.StatusCode      = (int)HttpStatusCode.NotFound;
                            ctx.Response.ContentLength64 = 0;
                        }
                        ctx.Response.Close();
                    });
                }
            });

            Stdio.SetStatus("Listeninig on {0}", uri);

            using (var disposer = new Disposer())
            {
                disposer.Push(handler);
                disposer.Push(accepter);
                disposer.Push(http.Stop);

                var line = Stdio.ReadLine();
                while (line != null)
                {
                    line = Stdio.ReadLine();
                }
            }

            Logger.Trace("Stdin closed");

            Environment.Exit(0);
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            ProgramTools.Setup();

            var config = new Config();

            config.IP      = "0.0.0.0";
            config.Port    = 22333;
            config.Delay   = 5000;
            config.Timeout = 5000;
            config.Root    = ExecutableTools.Relative("Root");

            //args will always log to stderr because daemon flag not loaded yet
            ExecutableTools.LogArgs(new StderrWriteLine(), args, (arg) =>
            {
                ConfigTools.SetProperty(config, arg);
            });

            AssertTools.NotEmpty(config.Root, "Missing Root path");
            AssertTools.NotEmpty(config.IP, "Missing IP");
            AssertTools.Ip(config.IP, "Invalid IP");

            var pid     = Process.GetCurrentProcess().Id;
            var writers = new WriteLineCollection();

            if (!config.Daemon)
            {
                writers.Add(new StderrWriteLine());
                Logger.TRACE = new TimedWriter(writers);
            }

            Logger.Trace("Root {0}", config.Root);

            var dbpath    = Path.Combine(config.Root, "SharpDaemon.LiteDb");
            var logpath   = Path.Combine(config.Root, "SharpDaemon.Log.txt");
            var eppath    = Path.Combine(config.Root, "SharpDaemon.Endpoint.txt");
            var downloads = Path.Combine(config.Root, "Downloads");

            Directory.CreateDirectory(downloads); //creates root as well

            //acts like mutex for the workspace
            var log = new StreamWriter(logpath, true);

            writers.Add(new TextWriterWriteLine(log));

            ExecutableTools.LogArgs(new TextWriterWriteLine(log), args);

            var instance = new Instance(new Instance.Args
            {
                DbPath       = dbpath,
                RestartDelay = config.Delay,
                Downloads    = downloads,
                EndPoint     = new IPEndPoint(IPAddress.Parse(config.IP), config.Port),
            });

            Stdio.SetStatus("Listening on {0}", instance.EndPoint);

            using (var disposer = new Disposer())
            {
                //wrap to add to disposable count
                disposer.Push(new Disposable.Wrapper(log));
                disposer.Push(instance);
                disposer.Push(() => Disposing(config.Timeout));

                if (config.Daemon)
                {
                    Logger.Trace("Stdin loop...");
                    var line = Stdio.ReadLine();
                    while (line != null)
                    {
                        Logger.Trace("> {0}", line);
                        if ("exit!" == line)
                        {
                            break;
                        }
                        line = Stdio.ReadLine();
                    }
                    Logger.Trace("Stdin closed");
                }
                else
                {
                    Logger.Trace("Stdin loop...");
                    var shell  = instance.CreateShell();
                    var stream = new ShellStream(new StdoutWriteLine(), new ConsoleReadLine());
                    //disposer.Push(stream); //stdin.readline wont return even after close/dispose call
                    var line = stream.ReadLine();
                    while (line != null)
                    {
                        if ("exit!" == line)
                        {
                            break;
                        }
                        Shell.ParseAndExecute(shell, stream, line);
                        line = stream.ReadLine();
                    }
                    Logger.Trace("Stdin closed");
                }
            }

            Environment.Exit(0);
        }