public override DnsDatagram Query(DnsDatagram request)
        {
            //serialize request
            byte[] requestBuffer;

            using (MemoryStream mS = new MemoryStream(32))
            {
                request.WriteTo(mS);
                requestBuffer = mS.ToArray();
            }

            //DoH wire format request
            DateTime sentAt = DateTime.UtcNow;

            byte[] responseBuffer;

            using (WebClientEx wC = new WebClientEx())
            {
                wC.AddHeader("content-type", "application/dns-message");
                wC.AddHeader("accept", "application/dns-message");
                wC.AddHeader("host", _server.DnsOverHttpEndPoint.Host + ":" + _server.DnsOverHttpEndPoint.Port);
                wC.UserAgent = "DoH client";
                wC.Proxy     = _proxy;
                wC.Timeout   = _timeout;

                if (_proxy == null)
                {
                    if (_server.IPEndPoint == null)
                    {
                        _server.RecursiveResolveIPAddress();
                    }

                    responseBuffer = wC.UploadData(new Uri(_server.DnsOverHttpEndPoint.Scheme + "://" + _server.IPEndPoint.ToString() + _server.DnsOverHttpEndPoint.PathAndQuery), requestBuffer);
                }
                else
                {
                    responseBuffer = wC.UploadData(_server.DnsOverHttpEndPoint, requestBuffer);
                }
            }

            //parse response
            using (MemoryStream mS = new MemoryStream(responseBuffer, false))
            {
                DnsDatagram response = new DnsDatagram(mS);

                response.SetMetadata(new DnsDatagramMetadata(_server, _protocol, responseBuffer.Length, (DateTime.UtcNow - sentAt).TotalMilliseconds));

                if (response.Header.Identifier == request.Header.Identifier)
                {
                    return(response);
                }
            }

            return(null);
        }
Example #2
0
        public login GetLogin(string User, string Password)
        {
            string user   = Convert.ToBase64String(Encoding.UTF8.GetBytes(User));
            string pass   = Convert.ToBase64String(Encoding.UTF8.GetBytes(Password));
            string cfrom  = "thirdParty";
            int    device = GetTimeStamp();

            StringBuilder LoginData = new StringBuilder();

            LoginData.AppendFormat("{0}={1}&", "user", user);
            LoginData.AppendFormat("{0}={1}&", "pass", pass);
            LoginData.AppendFormat("{0}={1}&", "cfrom", cfrom);
            LoginData.AppendFormat("{0}={1}&", "device", device);

            WebClientEx LoginWc = new WebClientEx
            {
                Timeout = 5000
            };

            LoginWc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            string Url = "http://" + server + "/api.php?m=login&a=check";

            return(JsonConvert.DeserializeObject <login>(Encoding.UTF8.GetString(LoginWc.UploadData(Url, Encoding.UTF8.GetBytes(LoginData.ToString())))));
        }
        public StandardResponse PostFile(string path, byte[] content)
        {
            WebClientEx wc = new WebClientEx()
            {
                Certificates = API.ClientCertificates
            };

            var responseByteArray = wc.UploadData(API.BaseUrl + $"{Client.Version}/containers/{Name}/files?path={path}", null, content);

            return(wc.ResponseHeaders[HttpRequestHeader.ContentType] == "application/json"
                ? StandardResponse.Parse(System.Text.Encoding.ASCII.GetString(responseByteArray))
                : new StandardResponse.InvalidResponse());
        }
Example #4
0
                static byte[] Send <T>(string method, string argName, T arg)
                {
                    var request = new MemoryStream();

                    request.SerializeDataContract(arg);

                    using (var client = new WebClientEx {
                        Timeout = TimeSpan.FromMinutes(1)
                    })
                    {
                        var response = client.UploadData($"{Paths.GetWebSiteUrl()}/services/instrumentprovider.ashx?method={method}", request.To <byte[]>().DeflateTo());
                        return(response.DeflateFrom());
                    }
                }
Example #5
0
        public void Register(Uri apiUri, CertificateStore localCertStore)
        {
            _localCertStore = localCertStore;

            //check if email address domain exists
            {
                DnsClient dns = new DnsClient(IPAddress.Parse("8.8.8.8"));

                try
                {
                    dns.ResolveMX(_localCertStore.Certificate.IssuedTo.EmailAddress);
                }
                catch (NameErrorDnsClientException)
                {
                    throw new NameErrorDnsClientException("The domain of your email address '" + _localCertStore.Certificate.IssuedTo.EmailAddress.Host + "' does not exists. Please check if you have entered correct email address.");
                }
                catch
                {
                    DnsDatagram response = DnsClient.ResolveViaRootNameServers(_localCertStore.Certificate.IssuedTo.EmailAddress.Host, DnsResourceRecordType.MX);
                    if (response.Header.RCODE == DnsResponseCode.NameError)
                    {
                        throw new NameErrorDnsClientException("The domain of your email address '" + _localCertStore.Certificate.IssuedTo.EmailAddress.Host + "' does not exists. Please check if you have entered correct email address.");
                    }
                }
            }

            //verify self signed cert
            _localCertStore.Certificate.Verify(new Certificate[] { _localCertStore.Certificate });

            using (WebClientEx client = new WebClientEx())
            {
                client.Proxy     = _proxy;
                client.UserAgent = GetUserAgent();

                byte[] data = client.UploadData(apiUri.AbsoluteUri + "?cmd=reg", _localCertStore.Certificate.ToArray());

                using (BinaryReader bR = new BinaryReader(new MemoryStream(data)))
                {
                    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 Exception(message);
                    }
                }
            }
        }
Example #6
0
            public ICollection <SecurityMessage> LookupSecurities(SecurityLookupMessage criteria)
            {
                if (criteria == null)
                {
                    throw new ArgumentNullException(nameof(criteria));
                }

                var existingSecurities = ServicesRegistry.TrySecurityProvider?.Lookup(criteria).Select(s => s.ToMessage()).Where(s => !s.SecurityId.IsAllSecurity()).ToArray() ?? Enumerable.Empty <SecurityMessage>();
                var existingIds        = existingSecurities.Select(s => s.SecurityId.ToStringId()).ToHashSet(StringComparer.InvariantCultureIgnoreCase);

                var securities = new List <SecurityMessage>();

                byte[] Send <T>(string method, string argName, T arg)
                {
                    var request = new MemoryStream();

                    request.SerializeDataContract(arg);

                    using (var client = new WebClientEx {
                        Timeout = TimeSpan.FromMinutes(1)
                    })
                    {
                        var response = client.UploadData($"https://stocksharp.com/services/instrumentprovider.ashx?method={method}", request.To <byte[]>().DeflateTo());
                        return(response.DeflateFrom());
                    }
                }

                var ids = Send(nameof(IRemoteStorage.LookupSecurityIds), "criteria", criteria).UTF8().SplitByDotComma();

                var newSecurityIds = ids.Where(id => !existingIds.Contains(id)).ToArray();

                foreach (var b in newSecurityIds.Batch(RemoteStorage.DefaultMaxSecurityCount))
                {
                    var batch = b.ToArray();

                    var response = Send(nameof(IRemoteStorage.GetSecurities), "securityIds", batch);
                    securities.AddRange(response.To <Stream>().DeserializeDataContract <SecurityMessage[]>());
                }

                securities.AddRange(existingSecurities);
                return(securities);
            }
Example #7
0
        public bool Send(string args, string m, out string result)
        {
            string url = $"http://{clientItem.Ip}:{clientItem.Port}/{clientItem.Server.ServerName}";

            if (!string.IsNullOrEmpty(clientItem.Url))
            {
                url = clientItem.Url.StartsWith("http://") ? clientItem.Url:$"http://{clientItem.Url}";
            }
            url = url.EndsWith("/") ? $"{url}{m}" : $"{url}/{m}";
            using (var webClient = new WebClientEx {
                Encoding = Encoding.UTF8, TimeOut = clientItem.TimeOut
            })
            {
                webClient.Headers.Add("Content-Type", "application/json;charset=utf-8");
                var    postData     = Encoding.UTF8.GetBytes(args);
                byte[] responseData = webClient.UploadData(url, "POST", postData);
                result = Encoding.UTF8.GetString(responseData);
                return(true);
            }
        }
Example #8
0
        /// <summary>
        /// 上传数据
        /// </summary>
        /// <param name="eType"></param>
        /// <param name="sUrl"></param>
        /// <param name="sFilePathNameOrData"></param>
        /// <param name="iTimeOut"></param>
        /// <returns></returns>
        public static object Upload(DOWNLOAD_TYPE eType, string sUrl, string sFilePathNameOrData, int iTimeOut)
        {
            if (String.IsNullOrWhiteSpace(sFilePathNameOrData))
            {
                return(null);
            }

            object      aRet    = null;
            WebClientEx aClient = new WebClientEx(iTimeOut);

            try
            {
                WebRequest myre = WebRequest.Create(sUrl);
                if (eType == DOWNLOAD_TYPE.FILE)
                {
                    var di = new DirectoryInfo(Path.GetDirectoryName(sFilePathNameOrData));
                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    aClient.UploadFile(sUrl, sFilePathNameOrData);
                    aRet = 0;
                }
                if (eType == DOWNLOAD_TYPE.STIRNG)
                {
                    aClient.Encoding = System.Text.Encoding.UTF8;//定义对象语言
                    aRet             = aClient.UploadString(sUrl, sFilePathNameOrData);
                }
                if (eType == DOWNLOAD_TYPE.DATA)
                {
                    byte[] byteArray = System.Text.Encoding.Default.GetBytes(sFilePathNameOrData);
                    aRet = aClient.UploadData(sUrl, byteArray);
                }
            }
            catch
            {
            }
            aClient.Dispose();
            return(aRet);
        }
        public static async Task Post(HttpContext context)
        {
            var scheme     = context.Request.Scheme;
            var serverHost = context.Request.Host.Host;

            if (context.Request.Host.Port != 80)
            {
                serverHost += ":" + context.Request.Host.Port;
            }

            Dictionary <string, string> cookies  = new Dictionary <string, string>();
            Dictionary <string, string> hostDict = new Dictionary <string, string>();
            string tarHost = null;

            foreach (var item in context.Request.Cookies)
            {
                if (item.Key == "host")
                {
                    tarHost = item.Value;
                }
                else if (item.Key.StartsWith("host-"))
                {
                    hostDict[item.Value] = item.Key.Substring(5);
                }
                else
                {
                    cookies[item.Key] = item.Value;
                }
            }
            Dictionary <string, string> headers = new Dictionary <string, string>();

            foreach (var item in context.Request.Headers)
            {
                headers[item.Key] = item.Value;
            }

            WebClientEx webClient = new WebClientEx();

            foreach (var item in context.Request.Headers)
            {
                if (item.Key.Equals("Cookie", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                if (item.Key.Equals("Connection", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                if (item.Key.Equals("Host", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                else if (item.Key.Equals("Referer", StringComparison.OrdinalIgnoreCase))
                {
                    webClient.Headers.Add("Referer", item.Value.ToString().Replace("//" + tarHost, "//" + serverHost));
                }
                else
                {
                    webClient.Headers.Add(item.Key, item.Value);
                }
            }
            foreach (var item in cookies)
            {
                webClient.AddCookie(scheme + "://" + tarHost, item.Key, item.Value);
            }

            var path = context.Request.GetEncodedPathAndQuery();
            var url  = scheme + "://" + tarHost + path;
            var m    = urlRegex.Match(url);

            if (m.Success)
            {
                var name = m.Groups[0].Value;
                url = scheme + "://" + hostDict[name] + path.Replace(m.Value, "");
            }
            var body = await context.Request.BodyReader.ReadAsync();

            var datas = webClient.UploadData(url, body.Buffer.ToArray());

            foreach (var item in webClient.ResponseHeaders.AllKeys)
            {
                context.Response.Headers[item] = webClient.ResponseHeaders[item].ToString();
            }
            context.Response.StatusCode = 200;
            if (webClient.ResponseHeaders["content-type"].Contains("text/html", StringComparison.OrdinalIgnoreCase))
            {
                var html = Encoding.UTF8.GetString(datas);
                html = HtmlHelper.ReplaceHtml(html, serverHost, tarHost, hostDict);

                await context.Response.WriteAsync(html);

                return;
            }
            if (webClient.ResponseHeaders["content-type"].Contains("text/css", StringComparison.OrdinalIgnoreCase))
            {
                var html = Encoding.UTF8.GetString(datas);
                html = HtmlHelper.ReplaceCss(html, serverHost, tarHost, hostDict);

                await context.Response.WriteAsync(html);

                return;
            }
            if (webClient.ResponseHeaders["content-type"].Contains("javascript", StringComparison.OrdinalIgnoreCase))
            {
                var html = Encoding.UTF8.GetString(datas);
                html = HtmlHelper.ReplaceScript(html, serverHost, tarHost, hostDict);

                await context.Response.WriteAsync(html);

                return;
            }
            await context.Response.Body.WriteAsync(datas, 0, datas.Length);
        }