public static bool IsRevoked(Certificate certToCheck, out RevocationCertificate revokeCert, NetProxy proxy = null, int timeout = 10000) { if (certToCheck.RevocationURL == null) { throw new CryptoException("Certificate does not support revocation."); } using (WebClientEx client = new WebClientEx()) { client.Proxy = proxy; client.Timeout = timeout; using (Stream s = client.OpenRead(certToCheck.RevocationURL.AbsoluteUri + "?sn=" + certToCheck.SerialNumber)) { switch (s.ReadByte()) { case -1: throw new EndOfStreamException(); case 0: //not found revokeCert = null; return(false); case 1: revokeCert = new RevocationCertificate(s); break; default: throw new CryptoException("RevokedCertificate version not supported."); } } return(revokeCert.IsValid(certToCheck)); } }
public void DownloadSignedCertificate(Uri apiUri) { using (WebClientEx client = new WebClientEx()) { client.Proxy = _proxy; client.UserAgent = GetUserAgent(); using (BinaryReader bR = new BinaryReader(client.OpenRead(apiUri.AbsoluteUri + "?cmd=dlc&email=" + _localCertStore.Certificate.IssuedTo.EmailAddress.Address))) { int errorCode = bR.ReadInt32(); if (errorCode != 0) { string message = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); string remoteStackTrace = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32())); throw new BitChatException(message); } Certificate cert = new Certificate(bR.BaseStream); if (!cert.IssuedTo.EmailAddress.Equals(_localCertStore.Certificate.IssuedTo.EmailAddress) || (cert.PublicKeyEncryptionAlgorithm != _localCertStore.PrivateKey.Algorithm) || (cert.PublicKeyXML != _localCertStore.PrivateKey.GetPublicKey())) { throw new BitChatException("Invalid signed certificate received. Please try again."); } _localCertStore = new CertificateStore(cert, _localCertStore.PrivateKey); } } }
private bool TryFirstConnect() { bool CouldConnect = false; Stream str = client.OpenRead("https://unturnedsl.com/auth/login"); StreamReader reader = new StreamReader(str); string ReturnValue = reader.ReadToEnd(); reader.Close(); str.Close(); string ToFind = "<input type=\"hidden\" name=\"_token\" value=\""; int start = ReturnValue.IndexOf(ToFind) + 42; ToFind = "\">"; int end = ReturnValue.IndexOf(ToFind, start); LogBox.Text += "\nReading For Access Token @ " + start.ToString() + "-" + end.ToString(); if (Token.Length < 3) { Token = ReturnValue.Substring(start, end - start); } LogBox.Text += "\nToken: " + Token; if (Token.Length > 3) { CouldConnect = true; } return(CouldConnect); }
void resetPower(bool turnOff = true) { string challenge; using (WebClientEx client = new WebClientEx()) { client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"; using (Stream sin = client.OpenRead("http://" + _host + "/")) using (StreamReader srin = new StreamReader(sin)) { string data = srin.ReadToEnd(); var m = Regex.Match(data, "NAME=\"Challenge\" VALUE=\"(.*)\"> <input"); challenge = m.Groups[1].Value; } var md5 = MD5.Create(); var hash = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(_user + _pass + challenge)); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("x2")); } // Make final web requests client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; string postData = "Username="******"&Response=" + sb.ToString() + "&Challenge=&Password="******"http://" + _host + "/tgi/login.tgi", postData); if (turnOff) { // Off postData = "P6" + _port + "=Off&ButtonName=Apply"; client.UploadString("http://" + _host + "/tgi/iocontrol.tgi", postData); // Pause System.Threading.Thread.Sleep(_powerPause); } // On postData = "P6" + _port + "=On&ButtonName=Apply"; client.UploadString("http://" + _host + "/tgi/iocontrol.tgi", postData); } }
/// <summary> /// Check if an internet connection is available. /// </summary> /// <param name="timeout">Length of time, in milliseconds, until the web request time out.</param> /// <param name="testUrl">Valid url to requested resource over Internet.</param> /// <returns>True if application has access to Internet, false otherwise.</returns> public static bool isConnectionAvailable(int timeout = DefaultTimeout, string testUrl = "http://google.com/generate_204") { var webClient = new WebClientEx(timeout); try { webClient.OpenRead(testUrl); return(true); } catch { return(false); } }
private void CheckForUpdateAsync(object state) { if (state == null) { if (DateTime.UtcNow < _lastUpdateCheckedOn.AddDays(_checkUpdateIntervalDays)) { return; } } //update last check time _lastUpdateCheckedOn = DateTime.UtcNow; try { using (WebClientEx client = new WebClientEx()) { client.Proxy = _proxy; client.UserAgent = GetUserAgent(); client.IfModifiedSince = _lastModifiedGMT; using (Stream s = client.OpenRead(_checkUpdateURL)) { _updateInfo = new UpdateInfo(s); } _lastModifiedGMT = DateTime.Parse(client.ResponseHeaders["Last-Modified"]); if (_updateInfo.IsUpdateAvailable(_currentVersion)) { //update available, stop timer _checkTimer.Change(Timeout.Infinite, Timeout.Infinite); //raise event to user UI RaiseEventUpdateAvailable(); } else { //if manual check then raise event if (state != null) { RaiseEventNoUpdateAvailable(); } } } } catch (WebException ex) { HttpWebResponse response = ex.Response as HttpWebResponse; if (response != null) { switch (response.StatusCode) { case HttpStatusCode.NotModified: case HttpStatusCode.NotFound: //if manual check then raise event if (state != null) { RaiseEventNoUpdateAvailable(); } break; default: //if manual check then raise event if (state != null) { RaiseEventUpdateError(ex); } break; } } else { //if manual check then raise event if (state != null) { RaiseEventUpdateError(ex); } } } catch (Exception ex) { //if manual check then raise event if (state != null) { RaiseEventUpdateError(ex); } } if (state != null) { _checkUpdate = null; } }
protected override void UpdateTracker(TrackerClientEvent @event, IPEndPoint clientEP) { string queryString; queryString = "?info_hash=" + Uri.EscapeDataString(Encoding.ASCII.GetString(_infoHash)) + "&peer_id=" + Uri.EscapeDataString(Encoding.ASCII.GetString(_clientID.PeerID)); switch (clientEP.Address.ToString()) { case "0.0.0.0": case "127.0.0.1": case "::": case "::1": break; default: if (clientEP.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { queryString += "&ipv6=" + clientEP.Address.ToString(); } else { queryString += "&ip=" + clientEP.Address.ToString(); } break; } queryString += "&port=" + clientEP.Port + "&uploaded=0&downloaded=0&left=0&corrupt=0" + "&key=" + BitConverter.ToString(_clientID.ClientKey).Replace("-", ""); switch (@event) { case TrackerClientEvent.Started: queryString += "&event=started"; break; case TrackerClientEvent.Stopped: queryString += "&event=stopped"; break; case TrackerClientEvent.Completed: queryString += "&event=completed"; break; } queryString += "&numwant=" + _clientID.NumWant; if (_clientID.Compact) { queryString += "&compact=1"; } else { queryString += "&compact=0"; } if (_clientID.NoPeerID) { queryString += "&no_peer_id=1"; } using (WebClientEx webClient = new WebClientEx()) { webClient.Proxy = _proxy; webClient.Timeout = 30000; //30 sec timeout webClient.UserAgent = _clientID.HttpUserAgent; webClient.AddHeader("Accept-Encoding", _clientID.HttpAcceptEncoding); webClient.KeepAlive = false; using (Stream responseStream = webClient.OpenRead(_trackerURI.AbsoluteUri + queryString)) { switch (@event) { case TrackerClientEvent.None: case TrackerClientEvent.Started: Bencoding x = Bencoding.Decode(responseStream); switch (x.Type) { case BencodingType.Dictionary: _peers.Clear(); foreach (var item in x.ValueDictionary) { switch (item.Key) { case "peers": switch (item.Value.Type) { case BencodingType.String: ParseCompactPeersIPv4(item.Value.Value as byte[], _peers); break; case BencodingType.List: foreach (var peerObj in item.Value.ValueList) { var peer = peerObj.ValueDictionary; _peers.Add(new IPEndPoint(IPAddress.Parse(peer["ip"].ValueString), Convert.ToInt32(peer["port"].ValueInteger))); } break; } break; case "peers_ipv6": case "peers6": switch (item.Value.Type) { case BencodingType.String: ParseCompactPeersIPv6(item.Value.Value as byte[], _peers); break; } break; case "interval": if (item.Value.Type == BencodingType.Integer) { _interval = Convert.ToInt32(item.Value.Value); } break; case "min interval": if (item.Value.Type == BencodingType.Integer) { _minInterval = Convert.ToInt32(item.Value.Value); } break; } } break; default: throw new TrackerClientException("Invalid data received from tracker. Expected bencoded dictionary."); } break; } } } }
void worker_DoWork(object sender, DoWorkEventArgs e) { check = false; BackgroundWorker worker = sender as BackgroundWorker; DownloadInstructions instr = (DownloadInstructions)e.Argument; bool harddiskMode = Directory.Exists(instr.From); string to = instr.To; string from = instr.From; //downloadLocation; ModuleUpdateFilePath[] download = instr.Files; //config[localVersion.ToString()].GetStrings("game_add"); string[] remove = new string[0]; //config[localVersion.ToString()].GetStrings("game_remove"); if (download.Length == 0) { finished.Set(); return; } int totalsize = 0; using (WebClientEx client = new WebClientEx()) { // make backup worker.ReportProgress(0, Program.Text[instr.Text].Get("backup")); string backupPath = "tmp/backup/"; Directory.CreateDirectory(backupPath); foreach (ModuleUpdateFilePath str in download) { string dir = Path.GetDirectoryName(str.File); if (!Directory.Exists(backupPath + dir)) { Directory.CreateDirectory(backupPath + dir); } if (System.IO.File.Exists(str.File)) { System.IO.File.Copy(str.File, backupPath + str.File, true); } } // remove old files foreach (string str in remove) { string[] filenames = Directory.GetFiles(gamePath, str); foreach (string filename in filenames) { System.IO.File.Delete(filename); } } // retrieve file size worker.ReportProgress(0, Program.Text[instr.Text].Get("retrieve")); int index = 0; // get info do { string filename = from + download[index].FullPath; try { if (harddiskMode) { FileInfo info = new FileInfo(filename); totalsize += (int)info.Length; } else { totalsize += GetHttpFileSize(filename); } } catch { MessageBox.Show(string.Format(Program.Text[instr.Text].Get("error1"), filename), Program.Text[instr.Text].Get("error")); worker.ReportProgress(-1); finished.Set(); return; } index++; } while (!worker.CancellationPending && index < download.Length); if (worker.CancellationPending) { finished.Set(); return; } int downloaded = 0; bool open = false; // download string msg = Program.Text[instr.Text].Get("download"); worker.ReportProgress(0, string.Format(msg, GetSizeString(instr.Text, downloaded), GetSizeString(instr.Text, totalsize))); index = 0; Stream strResponse = null; Stream strLocal = null; byte[] downBuffer = new byte[2048]; int progress = 0; do { if (!open) { string filename = from + download[index].FullPath; msg = Program.Text[instr.Text].Get("download_file"); worker.ReportProgress(progress, string.Format(msg, download[index], GetSizeString(instr.Text, downloaded), GetSizeString(instr.Text, totalsize))); try { // get download stream if (harddiskMode) { strResponse = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); } else { strResponse = client.OpenRead(filename); } } catch { MessageBox.Show(string.Format(Program.Text[instr.Text].Get("error2"), filename), Program.Text[instr.Text].Get("error")); worker.ReportProgress(-1); break; } // create local file strLocal = new FileStream(to + download[index].File, FileMode.Create, FileAccess.Write, FileShare.None); open = true; } int bytesSize = 0; // download 2kb bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length); if (bytesSize > 0) { // save to harddrive strLocal.Write(downBuffer, 0, bytesSize); // report progress downloaded += bytesSize; // update progress if changed float fprogress = downloaded * 100.0f / totalsize; //if (progress != (int)fprogress) { progress = (int)fprogress; msg = Program.Text[instr.Text].Get("download_file"); worker.ReportProgress(progress, string.Format(msg, download[index].File, GetSizeString(instr.Text, downloaded), GetSizeString(instr.Text, totalsize))); } } else { strLocal.Close(); strResponse.Close(); open = false; } if (!open) { index++; } } while (!worker.CancellationPending && index < download.Length); strLocal.Close(); strResponse.Close(); // download was cancelled if (worker.CancellationPending) { worker.ReportProgress(progress, Program.Text[instr.Text].Get("rollback")); // delete downloaded files foreach (ModuleUpdateFilePath file in download) { if (System.IO.File.Exists(to + file.File)) { System.IO.File.Delete(to + file.File); } } // restore backup foreach (ModuleUpdateFilePath file in download) { if (System.IO.File.Exists(backupPath + file.File)) { System.IO.File.Copy(backupPath + file.File, to + file.File, true); } } } // remove backup Directory.Delete(backupPath, true); } if (worker.CancellationPending) { worker.ReportProgress(100, Program.Text[instr.Text].Get("cancel")); } else { worker.ReportProgress(100, string.Format(Program.Text[instr.Text].Get("finish"), GetSizeString(instr.Text, totalsize))); } finished.Set(); check = true; }