public void set(string varnName, object value) { varnName = varsPrefix + varnName; if (!(value is string)) { value = value.ToString(); } if (_useCacheInRam) { if (!this.cache.ContainsKey(varnName)) { this.cache[varnName] = new FileVar { name = varnName } } ; this.cache[varnName].value = (string)value; this.cache[varnName].writed = false; if (th == null) { th = new EasyThread(this.writeToFile, true); } } else { write(directory + varnName, value is string?(string)value: value.ToString()); } }
public static void Main(String[] args) { try { Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); dnsLock = new Object(); cookieLock = new Object(); Share share = new Share(); Share.LockFunction lf = new Share.LockFunction(OnLock); Share.UnlockFunction ulf = new Share.UnlockFunction(OnUnlock); share.SetOpt(CURLSHoption.CURLSHOPT_LOCKFUNC, lf); share.SetOpt(CURLSHoption.CURLSHOPT_UNLOCKFUNC, ulf); share.SetOpt(CURLSHoption.CURLSHOPT_SHARE, CURLlockData.CURL_LOCK_DATA_COOKIE); share.SetOpt(CURLSHoption.CURLSHOPT_SHARE, CURLlockData.CURL_LOCK_DATA_DNS); EasyThread et1 = new EasyThread(args[0], share); EasyThread et2 = new EasyThread(args[1], share); Thread t1 = new Thread(new ThreadStart(et1.ThreadFunc)); Thread t2 = new Thread(new ThreadStart(et2.ThreadFunc)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); share.Cleanup(); Curl.GlobalCleanup(); } catch(Exception ex) { Console.WriteLine(ex); } }
public static void run(String[] args) { try { Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); dnsLock = new Object(); cookieLock = new Object(); Share share = new Share(); Share.LockFunction lf = new Share.LockFunction(OnLock); Share.UnlockFunction ulf = new Share.UnlockFunction(OnUnlock); share.SetOpt(CURLSHoption.CURLSHOPT_LOCKFUNC, lf); share.SetOpt(CURLSHoption.CURLSHOPT_UNLOCKFUNC, ulf); share.SetOpt(CURLSHoption.CURLSHOPT_SHARE, CURLlockData.CURL_LOCK_DATA_COOKIE); share.SetOpt(CURLSHoption.CURLSHOPT_SHARE, CURLlockData.CURL_LOCK_DATA_DNS); EasyThread et1 = new EasyThread(args[0], share); EasyThread et2 = new EasyThread(args[1], share); Thread t1 = new Thread(new ThreadStart(et1.ThreadFunc)); Thread t2 = new Thread(new ThreadStart(et2.ThreadFunc)); t1.Start(); t2.Start(); t1.Join(); t2.Join(); share.Cleanup(); Curl.GlobalCleanup(); } catch (Exception ex) { Console.WriteLine(ex); } }
//--- Public Methods --- public void StartAttack(string databasePath, int numThreads, IPasswordSource passwordSource) { if (numThreads <= 0) { throw new ArgumentOutOfRangeException("numThreads"); } lock (_syncLock) { if (_started) { throw new InvalidOperationException(); } _started = true; } if (!PerformSelfTest()) { throw new Exception("Self test failed"); } var fileStream = new FileStream(databasePath, FileMode.Open, FileAccess.Read); DatabaseOpener databaseOpener = new DatabaseOpener(fileStream); stopwatch.Start(); for (int i = 0; i < numThreads; i++) { EasyThread.BeginInvoke(new EasyThreadMethod( () => { Thread.MemoryBarrier(); _guessingThreadsRunning++; Thread.MemoryBarrier(); string result = AttackThread(databaseOpener, passwordSource); Thread.MemoryBarrier(); _guessingThreadsRunning--; Thread.MemoryBarrier(); if (result != null) { _passwordFound = result; OnPasswordFound(new PasswordFoundEventArgs(_passwordFound)); } else if (_guessingThreadsRunning == 0) { OnPasswordNotFound(EventArgs.Empty); } if (_guessingThreadsRunning == 0) { fileStream.Close(); OnCompleted(EventArgs.Empty); } })); } }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; this.Visible = false; Thread th = new Thread(delegate() { EasyThread.stopAllThreads(true); Process.GetCurrentProcess().Kill(); }); th.Start(); }
/// <summary> /// 批量下载 判断完成后 需要支持EasyThread.Stop /// 开线程 /// </summary> /// <param name="list">所有需要下载的内容</param> /// <param name="callback">当前文件本地大小、当前文件服务器大小、所有文件本地大小、所有文件服务器大小、当前文件</param> /// <param name="errorCallback"></param> public void BatchDownload(List <DownloadUnit> list, Action <Size, DownloadUnit, bool> callback, System.Action <DownloadUnit> errorCallback = null) { //Debug.Log("1"); EasyThread downloadThread = null; downloadThread = new EasyThread(() => { download(list, callback, downloadThread, errorCallback); downloadThread.Stop(); }); downloadThread.Start(); }
public void flush() { if (th == null) { th = new EasyThread(this.writeToFile, true); } th.pause(); writeToFile(th, null); th.resume(); }
private void writeToFile(EasyThread sender, object parameters) { //operações com arquivos devem ser, preferencialmente, realizadas em threads sender.sleep(10); int cont = 0; var directory = this.appPath + "\\vars"; if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } while (cont < this.cache.Count) { try { if (!this.cache.ElementAt(cont).Value.writed) { int tries = 5; int currentRetryInterval = 50; while (tries > 0) { try { string name = this.StringToFileName(this.cache.ElementAt(cont).Key); System.IO.File.WriteAllText(directory + "\\" + name, this.cache.ElementAt(cont).Value.value); this.cache[name].writed = true; tries = 0; } catch { Thread.Sleep(currentRetryInterval); currentRetryInterval += 50; } tries--; } } } catch { } cont++; } }
/// <summary> /// 单个下载 /// 开线程 /// </summary> /// <param name="downUnit"></param> /// <param name="precentCallback">下载进度回调</param> public void SingleDownload(DownloadUnit downUnit, System.Action <long, long, bool> callback, System.Action <DownloadUnit> errorCallback = null) { if (File.Exists(downUnit.FullPath)) { if (callback != null) { callback(1, 1, true); } return; } EasyThread downloadThread = null; downloadThread = new EasyThread(() => { download(downUnit, callback, downloadThread, errorCallback); downloadThread.Stop(); }); downloadThread.Start(); }
private void loadLastFoldersList() { int cont = vars.get("lastFolders.count", 0).AsInt - 1; int loadeds = 0; recentesToolStripMenuItem.DropDownItems.Clear(); List <string> addedToMenu = new List <string>(); while ((loadeds < 10) && (cont >= 0)) { string currName = vars.get("lastFolders." + cont.ToString(), "").AsString; if (!addedToMenu.Contains(currName)) { addedToMenu.Add(currName); EasyThread.StartNew(delegate(EasyThread thPointer, object arguments) { string curr = (string)((object[])arguments)[1]; //recentesToolStripMenuItem try { if (Directory.Exists(curr)) { ToolStripMenuItem temp = new ToolStripMenuItem(curr); temp.Click += delegate(object sender, EventArgs e) { this.loadFolder(((ToolStripMenuItem)sender).Text); }; this.Invoke((MethodInvoker) delegate() { recentesToolStripMenuItem.DropDownItems.Add(temp); }); } } catch { } }, false, new object[] { cont, currName }); } cont--; } }
/// <summary> /// Função para armazenar uma variável no sistema. Estas variáveis são persistentes e podem ser recuperadas em outras. /// execuções. /// </summary> /// <param name="name">Nome da variável.</param> /// <param name="value">Valor da variável.</param> public void _rawSet(string name, string value) { lock (toLock) { if ((!this.cache.ContainsKey(name)) || (this.cache[name] == null)) { this.cache[name] = new FileVar { name = name } } ; this.cache[name].value = value; this.cache[name].writed = false; if (th == null) { th = new EasyThread(this.writeToFile, true); } } }
private void writeToFile(EasyThread sender, object parameters) { //operações com arquivos devem ser, preferencialmente, realizadas em threads sender.sleep(10); int cont = 0; while (cont < this.cache.Count) { try { if (!this.cache.ElementAt(cont).Value.writed) { int tries = 5; int currentRetryInterval = 50; while (tries > 0) { try { string name = getValidVarName(this.cache.ElementAt(cont).Key); write(directory + name, this.cache.ElementAt(cont).Value.value); this.cache[name].writed = true; tries = 0; } catch { Thread.Sleep(currentRetryInterval); currentRetryInterval += 50; } tries--; } } } catch { } cont++; } }
/// <summary> /// 下载 /// </summary> /// <param name="downUnit"></param> /// <param name="callback"></param> private void download(DownloadUnit downUnit, System.Action <long, long, bool> callback, EasyThread downloadThread, System.Action <DownloadUnit> errorCallback = null) { //打开上次下载的文件 long startPos = 0; //将文件的后缀名改为临时文件名 .temp string tempfilename = downUnit.fileName.Replace(Path.GetExtension(downUnit.fileName), ".temp"); string tempFile = downUnit.savePath + "/" + tempfilename; string InstallFile = downUnit.savePath + "/" + downUnit.fileName; //Debug.LogError("文件路径 :" + InstallFile + " /文件名称/ :" + downUnit.fileName + " /服务器的md5/ :" + downUnit.md5); long totalSize = GetWebFileSize(downUnit.downUrl); //float totalSize; //float.TryParse(downUnit.size, out totalSize); //Debug.Log(totalSize); FileStream fs = null; //若此文件已经存在 则直接返回文件的总大小 if (File.Exists(InstallFile) && string.Equals(Utility.GetMd5Hash(File.OpenRead(InstallFile)), downUnit.md5)) { //不执行下载流程 Debug.LogError("下载的文件 已经存在 : " + InstallFile); if (callback != null) { callback(totalSize, totalSize, true); } return; } if (File.Exists(tempFile)) { fs = File.OpenWrite(tempFile); startPos = fs.Length; fs.Seek(startPos, SeekOrigin.Current); //移动文件流中的当前指针 } else { string direName = Path.GetDirectoryName(tempFile); if (!Directory.Exists(direName)) { Directory.CreateDirectory(direName); } fs = new FileStream(tempFile, FileMode.Create); Debug.Log(fs.ToString()); } // 下载逻辑 HttpWebRequest request = null; WebResponse respone = null; Stream ns = null; try { request = WebRequest.Create(downUnit.downUrl) as HttpWebRequest; request.ReadWriteTimeout = ReadWriteTimeOut; request.Timeout = TimeOutWait; if (startPos > 0) { request.AddRange((int)startPos); //设置Range值,断点续传 } //向服务器请求,获得服务器回应数据流 respone = request.GetResponse(); ns = respone.GetResponseStream(); long curSize = startPos; byte[] bytes = new byte[oneReadLen]; int readSize = ns.Read(bytes, 0, oneReadLen); // 读取第一份数据 while (readSize > 0) { //如果Unity客户端关闭,停止下载 if (IsStop) { if (fs != null) { fs.Flush(); fs.Close(); fs = null; } if (ns != null) { ns.Close(); } if (respone != null) { respone.Close(); } if (request != null) { request.Abort(); } downloadThread.Stop(); } fs.Write(bytes, 0, readSize); // 将下载到的数据写入临时文件 curSize += readSize; // 回调一下 if (callback != null) { callback(curSize, totalSize, false); } // 往下继续读取 readSize = ns.Read(bytes, 0, oneReadLen); } fs.Flush(); fs.Close(); fs = null; File.Move(tempFile, InstallFile); var file = File.OpenRead(InstallFile); string md5 = Utility.GetMd5Hash(file); Debug.LogError("文件路径 :" + InstallFile + " /文件名称/ :" + downUnit.fileName + " /本地计算的md5值为/ :" + md5 + " /服务器的md5/ :" + downUnit.md5 + " /下载url / :" + downUnit.downUrl); file.Dispose(); file.Close(); if (md5 == downUnit.md5) { if (callback != null) { callback(curSize, totalSize, true); } } else { if (errorCallback != null) { errorCallback(downUnit); Debug.LogError("MD5验证失败"); } File.Delete(InstallFile); Debug.LogError("删除 删除 删除 删除 删除 删除 删除 删除 删除 删除 删除 " + InstallFile); //downloadThread.Stop(); } } catch (WebException ex) { Debug.LogError(ex); if (errorCallback != null) { errorCallback(downUnit); Debug.Log("下载出错:" + ex.Message); } } finally { if (fs != null) { fs.Flush(); fs.Close(); fs = null; } if (ns != null) { ns.Close(); } if (respone != null) { respone.Close(); } if (request != null) { request.Abort(); } } }
private void btnStop_Click() { var thread = new EasyThread(btnStop_Click_Core, null); }
private void btnStart() { var thread = new EasyThread(btnStart_Core, null); }
public void loadGlobalDb(string globalDbPath) { EasyThread.StartNew(delegate(EasyThread sender, object arguments) { //define a lista de nodos atual como sendo o nodo raíz do treeview var parentAtt = treeView1.Nodes; ivk(delegate() { progressBar1.Maximum = 1; progressBar1.Value = 0; progressBar1.Show(); }); try { //lista os arquivos List <string> filesT = getVarsFiles(globalDbPath).ToList(); //filesT.Sort((item1, item2) => item1.CompareTo(item2)); filesT.Sort(delegate(string item1, string item2) { if (item1 != null && item2 != null) { string[] fName1 = item1.Split(new char[] { '.', '/', '\\' }); string[] fName2 = item2.Split(new char[] { '.', '/', '\\' }); int c = 0; Parallel.For(c, fName1.Length, delegate(int curr) { if (isNumber(fName1[curr])) { fName1[curr] = int.Parse(fName1[curr]).ToString("000000000000000"); } }); c = 0; Parallel.For(c, fName2.Length, delegate(int curr) { if (isNumber(fName2[curr])) { fName2[curr] = int.Parse(fName2[curr]).ToString("000000000000000"); } }); string compFName1 = ""; foreach (var curr in fName1) { compFName1 += curr + "."; } string compFName2 = ""; foreach (var curr in fName2) { compFName2 += curr + "."; } return(compFName1.CompareTo(compFName2)); } else { return(0); } }); string[] files = filesT.ToArray(); ivk(delegate() { treeView1.Nodes.Clear(); progressBar1.Maximum = files.Length; //treeView1.Hide(); }); foreach (var attFname in files) { ivk(delegate() { parentAtt = treeView1.Nodes; progressBar1.Value = progressBar1.Value + 1; }); //var att = Path.GetFileName(attFname); var att = attFname.Substring(globalDbPath.Length + 1); if (att.ToLower().Contains("time")) { ; } char sep = '.'; if (att.Contains("\\")) { sep = '\\'; } else if (att.Contains("/")) { sep = '/'; } string[] names = att.Split(sep); string completeName = globalDbPath + "\\"; foreach (var nameAtt in names) { completeName += nameAtt; //verifica se o nome atual já está na lista parent ivk(delegate() { if (parentAtt.ContainsKey(completeName)) { //define o nodo encontrado como o parentAtt parentAtt = parentAtt[parentAtt.IndexOfKey(completeName)].Nodes; } else { //adiciona o nodo na lista e o define como parent parentAtt = parentAtt.Add(completeName, nameAtt).Nodes; } }); completeName += sep; //Application.DoEvents(); } } /*ivk(delegate () * { * treeView1.TreeViewNodeSorter = new NodeSorter(); * treeView1.Sort(); * });*/ } catch { } ivk(delegate() { progressBar1.Hide(); //treeView1.Show(); }); }, false); }
/// <summary> /// 下载 /// </summary> /// <param name="downList"></param> /// <param name="callback"></param> private void download(List <DownloadUnit> downList, System.Action <Size, DownloadUnit, bool> callback, EasyThread downloadThread, System.Action <DownloadUnit> errorCallback = null) { // 计算所有要下载的文件大小 float totalSize = 0; float oneSize = 0; DownloadUnit unit; int i = 0; Size size = new Size(); //下载完成的个数统计 用于判断是否全部完成 int downCount = 0; for (i = 0; i < downList.Count; i++) { unit = downList[i]; oneSize = GetWebFileSize(unit.downUrl); totalSize += oneSize; } long currentSize = 0; i = 0; int count = downList.Count; for (i = 0; i < count; i++) { unit = downList[i]; long currentFileSize = 0; download(unit, (long _currentSize, long _fileSize, bool isDone) => { currentFileSize = _currentSize; long tempCurrentSize = currentSize + currentFileSize; if (callback != null) { size.LocalSize = _currentSize; size.ServerSize = _fileSize; size.TotalLocalSize = tempCurrentSize; size.TotalServerSize = totalSize; callback(size, unit, isDone); } }, downloadThread, (DownloadUnit _unit) => { if (errorCallback != null) { errorCallback(_unit); } }); currentSize += currentFileSize; //Debug.Log("finishe one: i = " + i); } }
//private Dictionary<DownloadUnit, OSSFile> faillist; /// <summary> /// 批量下载 /// </summary> /// <param name="list"></param> /// <param name="callback"></param> public void BatchOSSDownload(Dictionary <DownloadUnit, OSSFile> list, Action <bool> callback) { Dictionary <DownloadUnit, OSSFile> faillist = new Dictionary <DownloadUnit, OSSFile>(); int cureentDownCount = 0; int fallCount = 0; //下载完成的个数统计 用于判断是否全部完成 int i = 0; foreach (var file in list) { //Debug.Log("StartDownload::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size); Loom.QueueOnMainThread((() => { WriteIntoTxt(i + "StartDownload::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size, "list"); i++; })); } int j = 0; foreach (var file in list) { EasyThread et = null; et = new EasyThread((() => { OSSdownload(file.Key, file.Value, (b => { if (b) { Loom.QueueOnMainThread((() => { WriteIntoTxt(j + "DownloadSuccess::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size, "down"); j++; })); // Debug.Log("DownloadSuccess::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size); //HttpManager.Instance.DownLoadcurSize += float.Parse(file.Key.size); } else { fallCount++; faillist.Add(file.Key, file.Value); Debug.LogError("失败:::::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size); Loom.QueueOnMainThread((() => { WriteIntoTxt(j + "DownloadFail::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size, "down"); j++; })); // if (float.Parse(file.Key.size) <= 0 || file.Key.size == null) // { // //HttpManager.Instance.DownLoadcurSize += float.Parse(file.Key.size); // if (cureentDownCount == list.Count) // { // if (callback != null) // { // callback(fallCount <= 0); // } // } // } // else // { // fallCount++; // faillist.Add(file.Key, file.Value); // Debug.LogError("失败:::::::" + file.Key.downUrl + " " + file.Value.endpoint + " " + file.Key.fileName + " " + file.Key.size); // } } cureentDownCount++; Debug.LogWarning("总共 " + list.Count + " 当前 " + cureentDownCount); HttpManager.Instance.DownloadPercent((float)cureentDownCount / (float)list.Count); if (cureentDownCount == list.Count) { callback(fallCount <= 0); } et.Stop(); })); }), ThreadPriority.Highest); et.Start(); } ; }
/*private void delNode(TreeNode node) * { * * * * // Application.DoEvents(); * if (node.Nodes.Count > 0) * { * while (node.Nodes.Count > 0) * delNode(node.Nodes[0]); * } * * var parentNode = node.Parent; * if (parentNode != null) * { * if (parentNode.Nodes.Contains(node)) * parentNode.Nodes.Remove(node); * } * else * { * if (treeView1.Nodes.Contains(node)) * treeView1.Nodes.Remove(node); * } * * if (File.Exists(node.Name)) * { * File.Delete(node.Name); * } * * * * }*/ private void delNode(TreeNode node) { var parentNode = node.Parent; if (parentNode != null) { if (parentNode.Nodes.Contains(node)) { parentNode.Nodes.Remove(node); } } else { if (treeView1.Nodes.Contains(node)) { treeView1.Nodes.Remove(node); } } EasyThread.StartNew(delegate(EasyThread sender, object args) { string fName = ""; ivk(delegate() { fName = node.Name; }); List <string> childs = new List <string>(); childs.Add(fName); Directory.GetFiles(Path.GetDirectoryName(fName), Path.GetFileName(fName) + "*").ToString(); int max = 1; while (childs.Count > 0) { if (File.Exists(childs.Last())) { File.Delete(childs.Last()); childs.RemoveAt(childs.Count - 1); } else if (Directory.Exists(childs.Last())) { var tempFiles = Directory.GetFiles(childs.Last()); var tempFolders = Directory.GetDirectories(childs.Last()); if ((tempFiles.Length == 0) && (tempFolders.Length == 0)) { Directory.Delete(childs.Last(), true); childs.RemoveAt(childs.Count - 1); } else { childs.AddRange(tempFiles); childs.AddRange(tempFolders); max += tempFiles.Length + tempFolders.Length; } } else { childs.RemoveAt(childs.Count - 1); } ivk(delegate() { progressBar1.Maximum = max; progressBar1.Value = max - childs.Count; }); } ivk(delegate() { progressBar1.Hide(); }); }, false); }