Пример #1
2
        private async Task<bool> SendLoginData(string username, string password)
        {
            CookieContainer cookies = await _webManager.PostData(
                Constants.LOGIN_URL, string.Format(
                    "action=login&username={0}&password={1}",
                    username.Replace(" ", "+"),
                    WebUtility.UrlEncode(password)));

            if (cookies.Count < 2)
            {
                return false;
            }

            var fixedCookieContainer = new CookieContainer();

            // TODO: HUGE HACK. For some reason Windows Phone does not use the Domain Key on a cookie, but only the domain when making requests.
            // Windows 8 won't break on it, but Windows Phone will, since the Domain Key and Domain are different on SA.
            // We need to move this code to a more common place.

            foreach (Cookie cookie in cookies.GetCookies(new Uri(Constants.COOKIE_DOMAIN_URL)))
            {
                var fixedCookie = new Cookie(cookie.Name, cookie.Value, "/", ".somethingawful.com");
                fixedCookieContainer.Add(new Uri(Constants.COOKIE_DOMAIN_URL), fixedCookie);
            }

            await _localStorageManager.SaveCookie(Constants.COOKIE_FILE, cookies, new Uri(Constants.COOKIE_DOMAIN_URL));
            return true;
        }
Пример #2
1
        /// <summary>
        /// convert cookies string to CookieContainer
        /// </summary>
        /// <param name="cookies"></param>
        /// <returns></returns>
        public static CookieContainer ConvertToCookieContainer(Dictionary<string, string> cookies)
        {
            CookieContainer cookieContainer = new CookieContainer();

            foreach (var cookie in cookies)
            {
                string[] strEachCookParts = cookie.Value.Split(';');
                int intEachCookPartsCount = strEachCookParts.Length;

                foreach (string strCNameAndCValue in strEachCookParts)
                {
                    if (!string.IsNullOrEmpty(strCNameAndCValue))
                    {
                        Cookie cookTemp = new Cookie();
                        int firstEqual = strCNameAndCValue.IndexOf("=");
                        string firstName = strCNameAndCValue.Substring(0, firstEqual);
                        string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
                        cookTemp.Name = firstName;
                        cookTemp.Value = allValue;
                        cookTemp.Path = "/";
                        cookTemp.Domain = cookie.Key;
                        cookieContainer.Add(cookTemp);
                    }
                }
            }
            return cookieContainer;
        }
Пример #3
1
        public bool Login(string userName, string password, out Cookie authCookie)
        {
            var request=WebRequest.Create(ConfigurationManager.AppSettings["RemoteServer"] + "api/authorize") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            var authCredentials = "userName="******"&password="******".AspNet.ApplicationCookie"];
            }

            if (authCookie != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Пример #4
1
 public Meteor()
 {
     cookies = new Cookie();
     cookies.Domain = "http://www.meteor.ie";
     cookies.Name = "meteor";
     cookieContainer = new CookieContainer();
 }
Пример #5
0
        public static bool Get(string route, IEnumerable<KeyValuePair<string, string>> parameters, out JObject result, Cookie cookie = null)
        {
            KeyValuePair<bool, string> get = GetAsync(route, parameters, cookie).Result;

            result = get.Key ? JObject.Parse(get.Value) : null;
            return get.Key;
        }
Пример #6
0
        public string getPaperReferenceHTML(ArrayList paper_ids)
        {
            if (_AuthCookie == null)
            {
                //Auth Cookie is null
                return null;
            }

            string rs = "|";

            foreach( string p in paper_ids)
            {
                rs = rs + p + "|";
            }

            Cookie rs_cookie = new Cookie("rs", rs, _AuthCookie.Path, _AuthCookie.Domain);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL_2);
            request.CookieContainer = new CookieContainer();

            request.CookieContainer.Add(_AuthCookie);
            request.CookieContainer.Add(rs_cookie);

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                return reader.ReadToEnd();
            }

            return null;
        }
        private async void GetReddits()
        {
            if (Subreddits.LoggedIn)
            {
                try
                {
                    HttpClientHandler handler = new HttpClientHandler();

                    //var request = (HttpWebRequest)WebRequest.Create("http://www.reddit.com/reddits/mine.json");
                    //request.CookieContainer = new CookieContainer();

                    Cookie c = new Cookie("reddit_session", App.cookie.Replace(",", "%2C"));
                    handler.CookieContainer.Add(new Uri("http://www.reddit.com"), c);

                    App.JsonClient = new HttpClient(handler);

                    var response = App.JsonClient.GetAsync("http://www.reddit.com/reddits/mine.json").Result.Content;
                    await Subreddits.LoadCollection(response);
                }
                catch (Exception)
                {

                }
            }
            else
            {
                App.JsonClient = new HttpClient();
                var response = App.JsonClient.GetAsync("http://www.reddit.com/reddits.json").Result.Content;
                await Subreddits.LoadCollection(response);
            }

            ItemListView.ScrollIntoView(ItemListView.Items[0]);
        }
Пример #8
0
 public string GetHeaderValue(Cookie cookie)
 {
     return cookie.Expires == Session
         ? String.Format("{0}={1};path=/", cookie.Name, cookie.Value)
         : String.Format("{0}={1};expires={2};path={3}",
             cookie.Name, cookie.Value, cookie.Expires.ToString("R"), cookie.Path ?? "/");
 }
Пример #9
0
 public void TestDeep(string username, string password)
 {
     Blog service = new Blog();
     string ticket = service.Login(username, password);
     Cookie cookie = new Cookie(sDBlogAuthCookieName, ticket, "/", "localhost");
     TestDeep(cookie);
 }
        static Cookie ToNetCookie(NSHttpCookie cookie)
        {
            var nc = new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain);
            nc.Secure = cookie.IsSecure;

            return nc;
        }
Пример #11
0
 public string ExecutPostMethod(string postData)
 {
     var request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
     request.Method = "POST";
     request.Timeout = this.timeout;
     request.ContentType = "text/xml; charset=UTF-8";
     request.UserAgent = "Clearwave.Overseer";
     request.CookieContainer = new CookieContainer();
     request.ServerCertificateValidationCallback = HandleCert;
     if (SessionCookie != null)
     {
         request.CookieContainer.Add(SessionCookie);
     }
     var postDataBuffer = Encoding.UTF8.GetBytes(postData);
     request.ContentLength = postDataBuffer.Length;
     using (var dataStream = request.GetRequestStream())
     {
         dataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
     }
     var response = (HttpWebResponse)request.GetResponse();
     if (response.StatusCode != HttpStatusCode.OK)
     {
         throw new Exception(response.StatusCode.ToString() + " " + ReadContentFromResult(response));
     }
     var cookies = response.Cookies;
     if (cookies[SessionCookieName] != null)
     {
         this.SessionCookie = cookies[SessionCookieName];
     }
     var resultString = ReadContentFromResult(response);
     return resultString;
 }
Пример #12
0
        private static bool AuthenticateUser(string user, string password, out Cookie authCookie)
        {
            var request = WebRequest.Create("https://localhost/account/LogIn") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer();

            var authCredentials = "UserName="******"&Password=" + password;
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
            request.ContentLength = bytes.Length;
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            using (var response = request.GetResponse() as HttpWebResponse)
            {
                authCookie = response.Cookies[FormsAuthentication.FormsCookieName];
            }

            if (authCookie != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Performs active authentication against ADFS using the trust/13/usernamemixed ADFS endpoint.
        /// </summary>
        /// <param name="siteUrl">Url of the SharePoint site that's secured via ADFS</param>
        /// <param name="serialNumber">Serial Number of the Current User > My Certificate to use to authenticate </param>
        /// <param name="certificateMixed">Uri to the ADFS certificatemixed endpoint</param>
        /// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
        /// <param name="logonTokenCacheExpirationWindow"></param>
        /// <returns>A cookiecontainer holding the FedAuth cookie</returns>
        public CookieContainer GetFedAuthCookie(string siteUrl, string serialNumber, Uri certificateMixed, string relyingPartyIdentifier, int logonTokenCacheExpirationWindow)
        {
            CertificateMixed adfsTokenProvider = new CertificateMixed();

            var token = adfsTokenProvider.RequestToken(serialNumber, certificateMixed, relyingPartyIdentifier);
            string fedAuthValue = TransformSamlTokenToFedAuth(token.TokenXml.OuterXml, siteUrl, relyingPartyIdentifier);

            // Construct the cookie expiration date
            TimeSpan lifeTime = SamlTokenlifeTime(token.TokenXml.OuterXml);
            if (lifeTime == TimeSpan.Zero)
            {
                lifeTime = new TimeSpan(0, 60, 0);
            }

            int cookieLifeTime = Math.Min((lifeTime.Hours * 60 + lifeTime.Minutes), logonTokenCacheExpirationWindow);
            DateTime expiresOn = DateTime.Now.AddMinutes(cookieLifeTime);

            CookieContainer cc = null;

            if (!string.IsNullOrEmpty(fedAuthValue))
            {
                cc = new CookieContainer();
                Cookie samlAuth = new Cookie("FedAuth", fedAuthValue);
                samlAuth.Expires = expiresOn;
                samlAuth.Path = "/";
                samlAuth.Secure = true;
                samlAuth.HttpOnly = true;
                Uri samlUri = new Uri(siteUrl);
                samlAuth.Domain = samlUri.Host;
                cc.Add(samlAuth);
            }

            return cc;
        }
 /// <summary>
 /// Get request to a website
 /// </summary>
 /// <param name="uri">Uri to request</param>
 /// <param name="host">Host for header</param>
 /// <param name="cookie">Cookie for authentication</param>
 /// <param name="referer">Referer for header</param>
 /// <param name="action">Callback</param>
 /// <param name="userAgent">Useragent for header</param>
 /// <remarks>Requires refactoring, make it more general and replace CrawlString with it</remarks>
 public static void Get(String uri, String host, Cookie cookie, String referer, Action<PostResult> action, String userAgent)
 {
     using (var client = new WebClientEx())
     {
         if (cookie != null)
         {
             client.CookieContainer.Add(cookie);
         }
         client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
         client.Headers["Accept-Language"] = "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3";
         client.Headers["Cache-Control"] = "no-cache";
         client.Headers["User-Agent"] = userAgent;
         if (!String.IsNullOrEmpty(referer))
         {
             client.Headers["Referer"] = referer;
         }
         if (!String.IsNullOrEmpty(host))
         {
             client.Headers["Host"] = host;
         }
         client.Headers["X-Requested-With"] = "XMLHttpRequest";
         var response = client.DownloadString(uri);
         PostResult ps = new PostResult() { Result = response };
         action(ps);
     }
 }
 public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
 {
     // not use FormsCredentials unless you have implements acustom autentication.
     authCookie = null;
     user = password = authority = null;
     return false;
 }
Пример #16
0
 public static void AddCookie(this List<Cookie> cookieList, string setCookieFormat)
 {
     var bits = setCookieFormat.Split(';');
     string key, value;
     GetKeyValue(bits[0], '=', out key, out value);
     var c = new Cookie(key, value);
     for(var i = 1; i < bits.Length; i++) {
         GetKeyValue(bits[1], '=', out key, out value);
         switch(key) {
             case "expires":
                 c.Expires = DateTime.Parse(value);
                 break;
             case "path":
                 c.Path = value;
                 break;
             case "domain":
                 c.Domain = value;
                 break;
             case "secure":
                 c.Secure = value == "true";
                 break;
         }
     }
     cookieList.AddCookie(c);
 }
        /// <summary>
        /// Tests the scenario when the initial request contains a cookie (corresponding to user), in which case, the response should contain a similar cookie with the information
        /// replicated into the listener data.
        /// </summary>
        protected void ValidateUserIdWithRequestCookie(string requestPath, int testListenerTimeoutInMs, int testRequestTimeOutInMs, Cookie[] additionalCookies = null)
        {
            DateTimeOffset time = DateTimeOffset.UtcNow;
            List<Cookie> cookies = new List<Cookie>();
            int additionalCookiesLength = 0;
            if (null != additionalCookies)
            {
                cookies.AddRange(additionalCookies);
                additionalCookiesLength = additionalCookies.Length;
            }
            string userCookieStr = "userId|" + time.ToString("O");
            var cookie = new Cookie(CookieNames.UserCookie, userCookieStr);
            cookies.Add(cookie);

            var requestResponseContainer = new RequestResponseContainer(cookies.ToArray(), requestPath, this.Config.ApplicationUri, testListenerTimeoutInMs, testRequestTimeOutInMs);
            requestResponseContainer.SendRequest();

            var userCookie = requestResponseContainer.CookieCollection.ReceiveUserCookie();
            var item = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(
                1,
                testListenerTimeoutInMs)[0];

            Assert.AreEqual("OK", requestResponseContainer.ResponseTask.Result.ReasonPhrase);
            Assert.AreEqual(2 + additionalCookiesLength, requestResponseContainer.CookieCollection.Count);
            Assert.AreEqual("userId", item.UserContext.Id);
            Assert.AreEqual(time, item.UserContext.AcquisitionDate.Value);
            Assert.AreEqual(userCookieStr, userCookie);
            Assert.AreEqual(userCookie, item.UserContext.Id + "|" + item.UserContext.AcquisitionDate.Value.ToString("O"));   
        }
Пример #18
0
        private async void OnIdentityProviderTapped(object sender, TappedRoutedEventArgs e)
        {
            var identityProvider = (IdentityProvider)((FrameworkElement)e.OriginalSource).DataContext;

            var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                        WebAuthenticationOptions.None,
                        new Uri(identityProvider.LoginUrl),
                        new Uri("http://authentication.brainthud.com/api/federationcallback/end"));

            var start = webAuthenticationResult.ResponseData.LastIndexOf('=') + 1;
            var nameIdentifier = webAuthenticationResult.ResponseData.Substring(start, webAuthenticationResult.ResponseData.Length - start);
            var cookies = this.getCookies(nameIdentifier);

            var uri = new Uri(@"http://www.brainthud.com/api/Cards/");
            var cookieContainer = new CookieContainer();

            foreach(var cookie in cookies)
            {
                var cookieItem = new Cookie(cookie.Key, cookie.Value);
                cookieContainer.Add(uri, cookieItem);
            }

            var handler = new HttpClientHandler();
            handler.CookieContainer =cookieContainer;
            var client = new HttpClient(handler);
            var response = client.GetAsync(uri).Result;
            var result = response.Content.ReadAsStringAsync().Result;
            var x = result;
        }
Пример #19
0
        public static string WebPageGetWithCookies(Uri url,
            List<KeyValuePair<string, string>> vCookies, string strDomain)
        {
            if(url == null) throw new ArgumentNullException("url");

            HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url);

            hwr.Method = "GET";
            hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";

            if(vCookies != null)
            {
                hwr.CookieContainer = new CookieContainer();

                foreach(KeyValuePair<string, string> kvpCookie in vCookies)
                {
                    Cookie ck = new Cookie(kvpCookie.Key, kvpCookie.Value,
                        "/", strDomain);
                    hwr.CookieContainer.Add(ck);
                }
            }

            WebResponse wr = hwr.GetResponse();

            StreamReader sr = new StreamReader(wr.GetResponseStream());
            string strResponse = sr.ReadToEnd();
            sr.Close();
            wr.Close();

            return strResponse;
        }
        //渡されたcookieヘッダーをcookieに変換する。
        //CookieContainer.SetCookies()は不都合が生じる。
        protected virtual IEnumerable<Cookie> ParseCookies(string cookieHeader, Uri url)
        {
            if (string.IsNullOrEmpty(cookieHeader))
                yield break;

            var cookiesText = cookieHeader.Split(';');
            foreach (var data in cookiesText)
            {
                var cookie = new Cookie();
                var chunks = data.ToString().Split('=');
                if (2 > chunks.Length)
                {
                    TraceError(this, "IE Cookie解析に失敗。", string.Format("cookieHeader: {0}\r\nurl: {1}", cookieHeader, url));
                    throw new CookieImportException("IE Cookieの解析に失敗。", CookieImportState.ConvertError);
                }
                var name = chunks[0].Trim();
                var value = chunks[1].Trim();
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
                {
                    TraceError(this, "IE Cookieの解析に失敗。", string.Format("cookieHeader: {0}\r\nurl: {1}", cookieHeader, url));
                    throw new CookieImportException("IE Cookieの解析に失敗。", CookieImportState.ConvertError);
                }

                cookie.Name = name;
                cookie.Value = value;
                cookie.Domain = url.Host;
                //cookie.Path = url.AbsolutePath;
                //このほうがいいきがする 2011-11-19
                cookie.Path = url.Segments[0];
                //有効期限適当付与 2013-07-03
                cookie.Expires = DateTime.Now.AddDays(30);
                yield return cookie;
            }
        }
Пример #21
0
 public bool GetFormsCredentials(out Cookie authCookie, out string user,
  out string password, out string authority)
 {
     authCookie = null;
     user = password = authority = null;
     return false;
 }
Пример #22
0
        public string GetHeaderValue(Cookie cookie)
        {
            var path = cookie.Expires == Session
                ? "/"
                : cookie.Path ?? "/";

            var sb = new StringBuilder();

            sb.AppendFormat("{0}={1};path={2}", cookie.Name, cookie.Value, path);

            if (cookie.Expires != Session)
            {
                sb.AppendFormat(";expires={0}", cookie.Expires.ToString("R"));
            }

            if (!string.IsNullOrEmpty(cookie.Domain))
            {
                sb.AppendFormat(";domain={0}", cookie.Domain);
            }
            else if (EndpointHost.Config.RestrictAllCookiesToDomain != null)
            {
                sb.AppendFormat(";domain={0}", EndpointHost.Config.RestrictAllCookiesToDomain);
            }

            if (cookie.Secure)
            {
                sb.Append(";Secure");
            }
            if (cookie.HttpOnly)
            {
                sb.Append(";HttpOnly");
            }
            
            return sb.ToString();
        }
Пример #23
0
    public static Cookie ToCookie(this string str)
    {
      if (string.IsNullOrWhiteSpace(str))
        return null;
      var elements = str.SplitClean(';').ToArray();
      var keyValues = new NameValueCollection();
      var cookie = new Cookie();
      var nameValue = elements[0].SplitClean('=').ToArray();
      cookie.Name = nameValue[0];
      cookie.Value = nameValue[1];
      foreach (var element in elements.Skip(1))
      {
        if (element.Contains('='))
        {
          var keyValue = element.Split('=');
          keyValues.Add(keyValue[0].ToLower(), keyValue[1]);
        }
        //        else if (element.ToLower() == "secure")
        //        {
        //          cookie.Secure = true;
        //        }
        //        else if (element.ToLower() == "httponly")
        //        {
        //          cookie.HttpOnly = true;
        //        }
      }

      cookie.Domain = keyValues["domain"];
      cookie.Path = keyValues["path"];
      return cookie;
    }
        public void Context()
        {
            File.WriteAllText(AuthenticationCookiePersister.PersistentCookiePath, "nonsence nonsence nonsence nonsence nonsence nonsence nonsence");

            var authenticationCookiePersister = new AuthenticationCookiePersister();
            _cookie = authenticationCookiePersister.GetPersistentAuthenticationCookie();
        }
Пример #25
0
 /// <summary>
 /// Deletes a specified cookie by setting its value to empty and expiration to -1 days
 /// </summary>
 public void DeleteCookie(string cookieName)
 {
     var cookie = new Cookie(cookieName, string.Empty, "/") {
         Expires = DateTime.UtcNow.AddDays(-1)
     };
     AddCookie(cookie);
 }
Пример #26
0
        /// <summary>
        /// ͬ������HttpRequest
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static HttpWebResponse SendHttpPostRequest(Cookie cookie, string url, string postData)
        {
            //���https�µ�֤������
            HttpRequestCredentialHelper.SetDefaultCredentialValidationLogic();

            var request = HttpWebRequest.Create(url) as HttpWebRequest;

            //������������ΪPOST
            request.Method = "POST";

            //����Post������
            if (!string.IsNullOrEmpty(postData))
            {
                request.ContentLength = postData.Length;
                request.ContentType = "application/x-www-form-urlencoded";
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(postData);
                    writer.Close();
                }
            }

            //��Cookie�����������÷�����֪����ǰ�û������
            var container = new CookieContainer();
            request.CookieContainer = container;
            if (cookie != null)
            {
                container.SetCookies(new Uri(Constants.ROOT_URL), string.Format("{0}={1}", cookie.Name, cookie.Value));
                var logger = DependencyResolver.Resolve<ILoggerFactory>().Create(typeof(HttpWebRequestHelper));
                logger.InfoFormat("HttpWebRequest CookieName:{0}, Value:{1}", cookie.Name, cookie.Value);
            }

            return request.GetResponse() as HttpWebResponse;
        }
Пример #27
0
 private static Cookie fromOssiferCookie(OssiferCookie cookie)
 {
     Cookie ret = new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain);
     ret.HttpOnly = cookie.HttpOnly;
     ret.Secure = cookie.Secure;
     return ret;
 }
Пример #28
0
		public void PublicFields ()
		{
			Cookie c = new Cookie ();
			Assert.AreEqual (string.Empty, c.Name, "#A1");
			Assert.AreEqual (string.Empty, c.Value, "#A2");
			Assert.AreEqual (string.Empty, c.Domain, "#A3");
			Assert.AreEqual (string.Empty, c.Port, "#A4");
			Assert.AreEqual (string.Empty, c.Comment, "#A5");
			Assert.AreEqual (null, c.CommentUri, "#A6");
			Assert.IsFalse (c.Discard, "#A7");
			Assert.IsFalse (c.Expired, "#A8");
			Assert.AreEqual (DateTime.MinValue, c.Expires, "#A9");
			Assert.IsFalse (c.HttpOnly, "#A10");
			Assert.AreEqual (string.Empty, c.Path, "#A11");
			Assert.IsFalse (c.Secure, "#A12");
			Assert.AreEqual (0, c.Version, "#A13");
			Assert.AreEqual (string.Empty, c.ToString (), "#A14");

			c.Expires = DateTime.Now;
			Assert.IsTrue (c.Expired, "#A15");

			c.Port = null;
			Assert.AreEqual (string.Empty, c.Port, "#A16");

			c.Value = null;
			Assert.AreEqual (string.Empty, c.Value, "#A17");
		}
 public void Add(Cookie cookie)
 {
     Uri uri;
     if (cookie == null)
     {
         throw new ArgumentNullException("cookie");
     }
     if (cookie.Domain.Length == 0)
     {
         throw new ArgumentException(SR.GetString("net_emptystringcall"), "cookie.Domain");
     }
     StringBuilder builder = new StringBuilder();
     builder.Append(cookie.Secure ? Uri.UriSchemeHttps : Uri.UriSchemeHttp).Append(Uri.SchemeDelimiter);
     if (!cookie.DomainImplicit && (cookie.Domain[0] == '.'))
     {
         builder.Append("0");
     }
     builder.Append(cookie.Domain);
     if (cookie.PortList != null)
     {
         builder.Append(":").Append(cookie.PortList[0]);
     }
     builder.Append(cookie.Path);
     if (!Uri.TryCreate(builder.ToString(), UriKind.Absolute, out uri))
     {
         throw new CookieException(SR.GetString("net_cookie_attribute", new object[] { "Domain", cookie.Domain }));
     }
     Cookie cookie2 = cookie.Clone();
     cookie2.VerifySetDefaults(cookie2.Variant, uri, this.IsLocalDomain(uri.Host), this.m_fqdnMyDomain, true, true);
     this.Add(cookie2, true);
 }
Пример #30
0
 public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName,
                                 out string password, out string authority)
 {
     authCookie = null;
     userName   = null;
     password   = null;
     authority  = null;
     return(false);
 }
    bool IReportServerCredentials.GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string formsPassword, out string authority)
    {
        authCookie    = null;
        userName      = username;
        formsPassword = password;
        authority     = domain;

        return(false);
    }
    public override bool NewRow(DBNS.Value [] row)
    {
        if (Mode == 0)
        {
            object v = row[0]._O;
            if (v is string)
            {
                PutUtf8((string)v);
            }
            else
            {
                int code = (int)row[0].L;
                v = row[1]._O;

                if (code == 10)
                {
                    Ctx.Response.ContentType = (string)v;
                }
                else if (code == 11)
                {
                    PutBytes((byte[])v);
                }
                else if (code == 14)
                {
                    Ctx.Response.StatusCode = (int)row[1].L;
                }
                else if (code == 15)
                {
                    Ctx.Response.Redirect((string)v);
                }
                else if (code == 16)
                {
                    System.Net.Cookie ck      = new System.Net.Cookie((string)v, ( string )row[2]._O);
                    string            expires = ( string )row[3]._O;
                    if (expires != "")
                    {
                        ck.Expires = System.DateTime.Parse(expires);
                    }
                    Ctx.Response.Cookies.Add(ck);
                }
            }
        }
        else // HTML table mode
        {
            PutUtf8("<tr>");
            for (int i = 0; i < CI.Count; i += 1)
            {
                var type = CI.Types[i];
                PutUtf8(type == DBNS.DataType.String ? "<td>" : "<td align=right>");
                PutUtf8(DBNS.Util.ToHtml(row[i], type));
            }
        }
        return(true);
    }
Пример #33
0
        protected void autoLogin_Click(object sender, EventArgs e)
        {
            string          url = HttpContext.Current.Request.Url.AbsoluteUri.ToString().Replace("AutoLogin", "Login");
            CookieContainer myCookieContainer = new CookieContainer();
            HttpWebRequest  request           = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = myCookieContainer;
            request.Method          = "GET";
            request.KeepAlive       = false;

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            string srcString = reader.ReadToEnd();

            // get the page ViewState
            string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
            int    i             = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length;
            int    j             = srcString.IndexOf("\"", i);
            string viewState     = srcString.Substring(i, j - i);

            // get page EventValidation
            string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\"";

            i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length;
            j = srcString.IndexOf("\"", i);
            string eventValidation = srcString.Substring(i, j - i);

            string submitButton = "LoginButton";

            // UserName and Password
            string userName = btnUserName.Text;
            string password = btnPassword.Text;

            // Convert the text into the url encoding string
            viewState       = System.Web.HttpUtility.UrlEncode(viewState);
            eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
            submitButton    = System.Web.HttpUtility.UrlEncode(submitButton);

            // Concat the string data which will be submit
            string formatString =
                "UserName={0}&Password={1}&loginButton={2}&__VIEWSTATE={3}&__EVENTVALIDATION={4}";
            string postString =
                string.Format(formatString, userName, password, submitButton, viewState, eventValidation);

            // Convert the submit string data into the byte array
            byte[] postData = Encoding.ASCII.GetBytes(postString);

            // Set the request parameters
            request                 = WebRequest.Create(url) as HttpWebRequest;
            request.Method          = "POST";
            request.Referer         = url;
            request.KeepAlive       = false;
            request.UserAgent       = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; CIBA)";
            request.ContentType     = "application/x-www-form-urlencoded";
            request.CookieContainer = myCookieContainer;
            System.Net.Cookie ck = new System.Net.Cookie("TestCookie1", "Value of test cookie");
            ck.Domain = request.RequestUri.Host;
            request.CookieContainer.Add(ck);
            request.CookieContainer.Add(response.Cookies);

            request.ContentLength = postData.Length;

            // Submit the request data
            System.IO.Stream outputStream = request.GetRequestStream();
            request.AllowAutoRedirect = true;
            outputStream.Write(postData, 0, postData.Length);
            outputStream.Close();


            // Get the return data
            response       = request.GetResponse() as HttpWebResponse;
            responseStream = response.GetResponseStream();
            reader         = new System.IO.StreamReader(responseStream, Encoding.UTF8);
            srcString      = reader.ReadToEnd();
            Response.Write(srcString);
            Response.End();
        }
Пример #34
0
 internal CookieParser(string cookieString)
 {
     _tokenizer   = new CookieTokenizer(cookieString);
     _savedCookie = null;
 }
Пример #35
0
        public async void loadNicoFavList(Boolean dialogShow)
        {
            //ニコ生フォロー中表示。引数はログイン無い時にダイアログだすかどうか
            list.Clear();
            if (Properties.Settings.Default.user_session != "")
            {
                // タイトルを取得したいサイトのURL
                var urlstring = "https://sp.live.nicovideo.jp/favorites";

                //user_session
                var user_session = Properties.Settings.Default.user_session;
                //Cookieをせっと(user_session)
                var cookieContainer = new CookieContainer();
                var cookie          = new System.Net.Cookie();
                cookie.Name   = "user_session";
                cookie.Value  = user_session;
                cookie.Domain = ".nicovideo.jp";
                cookieContainer.Add(cookie);

                var header = new HttpClientHandler();
                header.CookieContainer = cookieContainer;

                // 指定したサイトのHTMLをストリームで取得する
                var client = new HttpClient(header);
                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "NicoLiveAlert_Twitter;@takusan_23");
                using (var stream = await client.GetAsync(new Uri(urlstring)))
                {
                    //var html = await client.GetStringAsync(urlstring);

                    if (stream.StatusCode == HttpStatusCode.OK)
                    {
                        var parser     = new HtmlParser();
                        var jsonString = await stream.Content.ReadAsStringAsync();

                        var doc = await parser.ParseDocumentAsync(jsonString);

                        //フォロー中の番組のJSON
                        var json = doc.Head.GetElementsByTagName("script")[5].TextContent;
                        json = HttpUtility.UrlDecode(json);

                        json = json.Replace("window.__initial_state__ = \"", "");
                        json = json.Replace("locationBeforeTransitions\":null}}\";", "locationBeforeTransitions\":null}}");
                        json = json.Replace("window.__public_path__ = \"https://nicolive.cdn.nimg.jp/relive/sp/\";", "");


                        var nicoJSON = JsonConvert.DeserializeObject <RootObject>(json);

                        //forEachで取り出す
                        if (nicoJSON != null)
                        {
                            var pos = 0;
                            foreach (var program in nicoJSON.pageContents.favorites.favoritePrograms.programs)
                            {
                                //予約枠だけ取得
                                if (program.liveCycle == "BeforeOpen")
                                {
                                    //なんかしらんけどbeginAtがフォロー中番組だけ値が大きすぎるのでUnixTimeにする割り算
                                    var beginTime = program.beginAt / 1000L;
                                    var dateTime  = "開場時間 : " + DateTimeOffset.FromUnixTimeSeconds(beginTime).LocalDateTime.ToString();
                                    var item      = new ProgramListViewData {
                                        Name = program.title + " | " + program.socialGroupName + " | " + program.id, Pos = pos, beginAt = beginTime, ID = program.id, dateTime = dateTime
                                    };
                                    pos += 1;
                                    list.Add(item);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (dialogShow)
                {
                    showLoginMessage();
                }
            }
        }
Пример #36
0
        internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow)
        {
            if (NetEventSource.IsEnabled)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Info(this, $"uri:{uri} headerName:{headerName} setCookieHeader:{setCookieHeader} isThrow:{isThrow}");
                }
            }

            CookieCollection cookies = new CookieCollection();
            CookieVariant    variant = CookieVariant.Unknown;

            if (headerName == null)
            {
                variant = CookieVariant.Default;
            }
            else
            {
                for (int i = 0; i < s_headerInfo.Length; ++i)
                {
                    if ((String.Compare(headerName, s_headerInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        variant = s_headerInfo[i].Variant;
                    }
                }
            }

            bool isLocalDomain = IsLocalDomain(uri.Host);

            try
            {
                CookieParser parser = new CookieParser(setCookieHeader);
                do
                {
                    Cookie cookie = parser.Get();
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Info(this, $"CookieParser returned cookie:{cookie}");
                    }

                    if (cookie == null)
                    {
                        if (parser.EndofHeader())
                        {
                            break;
                        }
                        continue;
                    }

                    // Parser marks invalid cookies this way
                    if (String.IsNullOrEmpty(cookie.Name))
                    {
                        if (isThrow)
                        {
                            throw new CookieException(SR.net_cookie_format);
                        }
                        // Otherwise, ignore (reject) cookie
                        continue;
                    }

                    // This will set the default values from the response URI
                    // AND will check for cookie validity
                    if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, m_fqdnMyDomain, true, isThrow))
                    {
                        continue;
                    }
                    // If many same cookies arrive we collapse them into just one, hence setting
                    // parameter isStrict = true below
                    cookies.InternalAdd(cookie, true);
                } while (true);
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (isThrow)
                {
                    throw new CookieException(SR.Format(SR.net_cookie_parse_header, uri.AbsoluteUri), e);
                }
            }

            foreach (Cookie c in cookies)
            {
                Add(c, isThrow);
            }

            return(cookies);
        }
Пример #37
0
 bool IReportServerCredentials.GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
 {
     userName = string.Empty; password = string.Empty; authority = string.Empty;     authCookie = new Cookie();
     return(false);
 }
Пример #38
0
 private static bool InternalSetNameMethod(Cookie cookie, string?value)
 {
     return(cookie.InternalSetName(value));
 }
Пример #39
0
        // This method is called *only* when cookie verification is done, so unlike with public
        // Add(Cookie cookie) the cookie is in a reasonable condition.
        internal void Add(Cookie cookie, bool throwOnError)
        {
            PathList?pathList;

            if (cookie.Value.Length > m_maxCookieSize)
            {
                if (throwOnError)
                {
                    throw new CookieException(SR.Format(SR.net_cookie_size, cookie, m_maxCookieSize));
                }
                return;
            }

            try
            {
                lock (m_domainTable.SyncRoot)
                {
                    pathList = (PathList?)m_domainTable[cookie.DomainKey];
                    if (pathList == null)
                    {
                        m_domainTable[cookie.DomainKey] = (pathList = new PathList());
                    }
                }
                int domain_count = pathList.GetCookiesCount();

                CookieCollection?cookies;
                lock (pathList.SyncRoot)
                {
                    cookies = (CookieCollection?)pathList[cookie.Path] !;

                    if (cookies == null)
                    {
                        cookies = new CookieCollection();
                        pathList[cookie.Path] = cookies;
                    }
                }

                if (cookie.Expired)
                {
                    // Explicit removal command (Max-Age == 0)
                    lock (cookies)
                    {
                        int idx = cookies.IndexOf(cookie);
                        if (idx != -1)
                        {
                            cookies.RemoveAt(idx);
                            --m_count;
                        }
                    }
                }
                else
                {
                    // This is about real cookie adding, check Capacity first
                    if (domain_count >= m_maxCookiesPerDomain && !AgeCookies(cookie.DomainKey))
                    {
                        return; // Cannot age: reject new cookie
                    }
                    else if (m_count >= m_maxCookies && !AgeCookies(null))
                    {
                        return; // Cannot age: reject new cookie
                    }

                    // About to change the collection.
                    lock (cookies)
                    {
                        m_count += cookies.InternalAdd(cookie, true);
                    }
                }

                // We don't want to cleanup m_domaintable/m_list too often. Add check to avoid overhead.
                if (m_domainTable.Count > m_count || pathList.Count > m_maxCookiesPerDomain)
                {
                    DomainTableCleanup();
                }
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (throwOnError)
                {
                    throw new CookieException(SR.net_container_add_cookie, e);
                }
            }
        }
Пример #40
0
        // This method is called *only* when cookie verification is done,
        // so unlike with public Add(Cookie cookie) the cookie is in sane condition
        internal void Add(Cookie cookie, bool throwOnError)
        {
            PathList pathList;

            if (cookie.Value.Length > m_maxCookieSize)
            {
                if (throwOnError)
                {
                    throw new CookieException(SR.GetString(SR.net_cookie_size, cookie.ToString(), m_maxCookieSize));
                }
                return;
            }

            try {
                lock (m_domainTable.SyncRoot)
                {
                    pathList = (PathList)m_domainTable[cookie.DomainKey];
                    if (pathList == null)
                    {
                        pathList = new PathList();
                        AddRemoveDomain(cookie.DomainKey, pathList);
                    }
                }
                int domain_count = pathList.GetCookiesCount();

                CookieCollection cookies;
                lock (pathList.SyncRoot)
                {
                    cookies = (CookieCollection)pathList[cookie.Path];

                    if (cookies == null)
                    {
                        cookies = new CookieCollection();
                        pathList[cookie.Path] = cookies;
                    }
                }

                if (cookie.Expired)
                {
                    //Explicit removal command (Max-Age == 0)
                    lock (cookies) {
                        int idx = cookies.IndexOf(cookie);
                        if (idx != -1)
                        {
                            cookies.RemoveAt(idx);
                            --m_count;
                        }
                    }
                }
                else
                {
                    //This is about real cookie adding, check Capacity first
                    if (domain_count >= m_maxCookiesPerDomain && !AgeCookies(cookie.DomainKey))
                    {
                        return;     //cannot age -> reject new cookie
                    }
                    else if (this.m_count >= m_maxCookies && !AgeCookies(null))
                    {
                        return;     //cannot age -> reject new cookie
                    }

                    //about to change the collection
                    lock (cookies) {
                        m_count += cookies.InternalAdd(cookie, true);
                    }
                }
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                {
                    throw;
                }

                if (throwOnError)
                {
                    throw new CookieException(SR.GetString(SR.net_container_add_cookie), e);
                }
            }
        }
Пример #41
0
        internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow)
        {
            GlobalLog.Print("CookieContainer#" + ValidationHelper.HashString(this) + "::CookieCutter() uri:" + uri + " headerName:" + headerName + " setCookieHeader:" + setCookieHeader + " isThrow:" + isThrow);
            CookieCollection cookies = new CookieCollection();
            CookieVariant    variant = CookieVariant.Unknown;

            if (headerName == null)
            {
                variant = CookieVariant.Default;
            }
            else
            {
                for (int i = 0; i < HeaderInfo.Length; ++i)
                {
                    if ((String.Compare(headerName, HeaderInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        variant = HeaderInfo[i].Variant;
                    }
                }
            }
            bool isLocalDomain = IsLocalDomain(uri.Host);

            try {
                CookieParser parser = new CookieParser(setCookieHeader);
                do
                {
                    Cookie cookie = parser.Get();
                    GlobalLog.Print("CookieContainer#" + ValidationHelper.HashString(this) + "::CookieCutter() CookieParser returned cookie:" + ValidationHelper.ToString(cookie));
                    if (cookie == null)
                    {
                        break;
                    }

                    //Parser marks invalid cookies this way
                    if (ValidationHelper.IsBlankString(cookie.Name))
                    {
                        if (isThrow)
                        {
                            throw new CookieException(SR.GetString(SR.net_cookie_format));
                        }
                        //Otherwise, ignore (reject) cookie
                        continue;
                    }

                    // this will set the default values from the response URI
                    // AND will check for cookie validity
                    if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, m_fqdnMyDomain, true, isThrow))
                    {
                        continue;
                    }
                    // If many same cookies arrive we collapse them into just one, hence setting
                    // parameter isStrict = true below
                    cookies.InternalAdd(cookie, true);
                } while (true);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                {
                    throw;
                }

                if (isThrow)
                {
                    throw new CookieException(SR.GetString(SR.net_cookie_parse_header, uri.AbsoluteUri), e);
                }
            }

            foreach (Cookie c in cookies)
            {
                Add(c, isThrow);
            }

            return(cookies);
        }
Пример #42
0
 public void SetCookie(System.Net.Cookie cookie)
 {
     Cookies.Add(cookie);
 }
        /// <summary>
        /// クッキーコンテナにクッキーを追加する
        /// domainが.hal.fscs.jpなどだと http://hal.fscs.jp でクッキーが有効にならないので.ありとなし両方指定する
        /// </summary>
        /// <param name="container"></param>
        /// <param name="cookie"></param>
        public static void AddCookieToContainer(System.Net.CookieContainer container, System.Net.Cookie cookie)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            if (cookie == null)
            {
                throw new ArgumentNullException("cookie");
            }

            container.Add(cookie);
            if (cookie.Domain.StartsWith("."))
            {
                container.Add(new System.Net.Cookie()
                {
                    Comment    = cookie.Comment,
                    CommentUri = cookie.CommentUri,
                    Discard    = cookie.Discard,
                    Domain     = cookie.Domain.Substring(1),
                    Expired    = cookie.Expired,
                    Expires    = cookie.Expires,
                    HttpOnly   = cookie.HttpOnly,
                    Name       = cookie.Name,
                    Path       = cookie.Path,
                    Port       = cookie.Port,
                    Secure     = cookie.Secure,
                    Value      = cookie.Value,
                    Version    = cookie.Version,
                });
            }
        }
Пример #44
0
        static Cookie Parse(string s)
        {
            string [] parts = s.Split(';');
            Cookie    c     = new Cookie();

            for (int i = 0; i < parts.Length; i++)
            {
                string key, value;
                int    sep = parts[i].IndexOf('=');
                if (sep == -1)
                {
                    key   = parts [i].Trim();
                    value = String.Empty;
                }
                else
                {
                    key   = parts [i].Substring(0, sep).Trim();
                    value = parts [i].Substring(sep + 1).Trim();
                }

                switch (key.ToLowerInvariant())
                {
                case "path":
                case "$path":
                    if (c.Path.Length == 0)
                    {
                        c.Path = value;
                    }
                    break;

                case "domain":
                case "$domain":
                    if (c.Domain.Length == 0)
                    {
                        c.Domain = value;
                        // here mono.com means "*.mono.com"
                        c.ExactDomain = false;
                    }
                    break;

                case "expires":
                case "$expires":
                    if (c.Expires == DateTime.MinValue)
                    {
                        c.Expires = DateTime.SpecifyKind(DateTime.ParseExact(value,
                                                                             @"ddd, dd-MMM-yyyy HH:mm:ss G\MT", CultureInfo.InvariantCulture), DateTimeKind.Utc);
                    }
                    break;

                case "httponly":
                    c.HttpOnly = true;
                    break;

                case "secure":
                    c.Secure = true;
                    break;

                default:
                    if (c.Name.Length == 0)
                    {
                        c.Name  = key;
                        c.Value = value;
                    }
                    break;
                }
            }
            return(c);
        }
        internal void AddHeader(string header)
        {
            int colon = header.IndexOf(':');

            if (colon == -1 || colon == 0)
            {
                _context.ErrorMessage = HttpStatusDescription.Get(400);
                _context.ErrorStatus  = 400;
                return;
            }

            string name  = header.Substring(0, colon).Trim();
            string val   = header.Substring(colon + 1).Trim();
            string lower = name.ToLower(CultureInfo.InvariantCulture);

            _headers.Set(name, val);
            switch (lower)
            {
            case "accept-language":
                _user_languages = val.Split(',');     // yes, only split with a ','
                break;

            case "accept":
                _accept_types = val.Split(',');     // yes, only split with a ','
                break;

            case "content-length":
                try
                {
                    _content_length = long.Parse(val.Trim());
                    if (_content_length < 0)
                    {
                        _context.ErrorMessage = "Invalid Content-Length.";
                    }
                    _cl_set = true;
                }
                catch
                {
                    _context.ErrorMessage = "Invalid Content-Length.";
                }

                break;

            case "referer":
                try
                {
                    _referrer = new Uri(val);
                }
                catch
                {
                    _referrer = null;
                }

                break;

            case "cookie":
                if (_cookies == null)
                {
                    _cookies = new CookieCollection();
                }

                string[] cookieStrings = val.Split(new char[] { ',', ';' });
                Cookie   current       = null;
                int      version       = 0;
                foreach (string cookieString in cookieStrings)
                {
                    string str = cookieString.Trim();
                    if (str.Length == 0)
                    {
                        continue;
                    }
                    if (str.StartsWith("$Version"))
                    {
                        version = Int32.Parse(Unquote(str.Substring(str.IndexOf('=') + 1)));
                    }
                    else if (str.StartsWith("$Path"))
                    {
                        if (current != null)
                        {
                            current.Path = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else if (str.StartsWith("$Domain"))
                    {
                        if (current != null)
                        {
                            current.Domain = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else if (str.StartsWith("$Port"))
                    {
                        if (current != null)
                        {
                            current.Port = str.Substring(str.IndexOf('=') + 1).Trim();
                        }
                    }
                    else
                    {
                        if (current != null)
                        {
                            _cookies.Add(current);
                        }
                        current = new Cookie();
                        int idx = str.IndexOf('=');
                        if (idx > 0)
                        {
                            current.Name  = str.Substring(0, idx).Trim();
                            current.Value = str.Substring(idx + 1).Trim();
                        }
                        else
                        {
                            current.Name  = str.Trim();
                            current.Value = String.Empty;
                        }
                        current.Version = version;
                    }
                }
                if (current != null)
                {
                    _cookies.Add(current);
                }
                break;
            }
        }
Пример #46
0
        internal Cookie?GetServer()
        {
            Cookie?cookie = _savedCookie;

            _savedCookie = null;

            // Only the first occurrence of an attribute value must be counted.
            bool domainSet = false;
            bool pathSet   = false;
            bool portSet   = false; // Special case: may have no value in header.

            do
            {
                bool        first = cookie == null || string.IsNullOrEmpty(cookie.Name);
                CookieToken token = _tokenizer.Next(first, false);

                if (first && (token == CookieToken.NameValuePair || token == CookieToken.Attribute))
                {
                    if (cookie == null)
                    {
                        cookie = new Cookie();
                    }
                    InternalSetNameMethod(cookie, _tokenizer.Name);
                    cookie.Value = _tokenizer.Value;
                }
                else
                {
                    switch (token)
                    {
                    case CookieToken.NameValuePair:
                        switch (_tokenizer.Token)
                        {
                        case CookieToken.Domain:
                            if (!domainSet)
                            {
                                domainSet       = true;
                                cookie !.Domain = CheckQuoted(_tokenizer.Value);
                                IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted);
                            }
                            break;

                        case CookieToken.Path:
                            if (!pathSet)
                            {
                                pathSet       = true;
                                cookie !.Path = _tokenizer.Value;
                            }
                            break;

                        case CookieToken.Port:
                            if (!portSet)
                            {
                                portSet = true;
                                try
                                {
                                    cookie !.Port = _tokenizer.Value;
                                }
                                catch (CookieException)
                                {
                                    // This cookie will be rejected
                                    InternalSetNameMethod(cookie !, string.Empty);
                                }
                            }
                            break;

                        case CookieToken.Version:
                            // this is a new cookie, this token is for the next cookie.
                            _savedCookie = new Cookie();
                            if (int.TryParse(_tokenizer.Value, out int parsed))
                            {
                                _savedCookie.Version = parsed;
                            }
                            return(cookie);

                        case CookieToken.Unknown:
                            // this is a new cookie, the token is for the next cookie.
                            _savedCookie = new Cookie();
                            InternalSetNameMethod(_savedCookie, _tokenizer.Name);
                            _savedCookie.Value = _tokenizer.Value;
                            return(cookie);
                        }
                        break;

                    case CookieToken.Attribute:
                        if (_tokenizer.Token == CookieToken.Port && !portSet)
                        {
                            portSet       = true;
                            cookie !.Port = string.Empty;
                        }
                        break;
                    }
                }
            } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie);
            return(cookie);
        }
Пример #47
0
        private void SetCookie(string header)
        {
            Cookie       cookie       = null;
            CookieParser cookieParser = new CookieParser(header);
            string       name;
            string       val;

            while (cookieParser.GetNextNameValue(out name, out val))
            {
                if ((name == null || name == string.Empty) && cookie == null)
                {
                    continue;
                }
                if (cookie == null)
                {
                    cookie = new Cookie(name, val);
                    continue;
                }
                name = name.ToUpper();
                switch (name)
                {
                case "COMMENT":
                    if (cookie.Comment == null)
                    {
                        cookie.Comment = val;
                    }
                    break;

                case "COMMENTURL":
                    if (cookie.CommentUri == null)
                    {
                        cookie.CommentUri = new Uri(val);
                    }
                    break;

                case "DISCARD":
                    cookie.Discard = true;
                    break;

                case "DOMAIN":
                    if (cookie.Domain == string.Empty)
                    {
                        cookie.Domain = val;
                    }
                    break;

                case "HTTPONLY":
                    cookie.HttpOnly = true;
                    break;

                case "MAX-AGE":
                    if (cookie.Expires == DateTime.MinValue)
                    {
                        try
                        {
                            cookie.Expires = cookie.TimeStamp.AddSeconds(uint.Parse(val));
                        }
                        catch
                        {
                        }
                    }
                    break;

                case "EXPIRES":
                    if (!(cookie.Expires != DateTime.MinValue))
                    {
                        cookie.Expires = TryParseCookieExpires(val);
                    }
                    break;

                case "PATH":
                    cookie.Path = val;
                    break;

                case "PORT":
                    if (cookie.Port == null)
                    {
                        cookie.Port = val;
                    }
                    break;

                case "SECURE":
                    cookie.Secure = true;
                    break;

                case "VERSION":
                    try
                    {
                        cookie.Version = (int)uint.Parse(val);
                    }
                    catch
                    {
                    }
                    break;
                }
            }
            if (cookie != null)
            {
                if (cookieCollection == null)
                {
                    cookieCollection = new CookieCollection();
                }
                if (cookie.Domain == string.Empty)
                {
                    cookie.Domain = uri.Host;
                }
                cookieCollection.Add(cookie);
                if (cookie_container != null)
                {
                    cookie_container.Add(uri, cookie);
                }
            }
        }
Пример #48
0
        internal Cookie?Get()
        {
            Cookie?cookie = null;

            // Only the first occurrence of an attribute value must be counted.
            bool commentSet    = false;
            bool commentUriSet = false;
            bool domainSet     = false;
            bool expiresSet    = false;
            bool pathSet       = false;
            bool portSet       = false; // Special case: may have no value in header.
            bool versionSet    = false;
            bool secureSet     = false;
            bool discardSet    = false;

            do
            {
                CookieToken token = _tokenizer.Next(cookie == null, true);
                if (cookie == null && (token == CookieToken.NameValuePair || token == CookieToken.Attribute))
                {
                    cookie = new Cookie();
                    InternalSetNameMethod(cookie, _tokenizer.Name);
                    cookie.Value = _tokenizer.Value;
                }
                else
                {
                    switch (token)
                    {
                    case CookieToken.NameValuePair:
                        switch (_tokenizer.Token)
                        {
                        case CookieToken.Comment:
                            if (!commentSet)
                            {
                                commentSet       = true;
                                cookie !.Comment = _tokenizer.Value;
                            }
                            break;

                        case CookieToken.CommentUrl:
                            if (!commentUriSet)
                            {
                                commentUriSet = true;
                                if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out Uri? parsed))
                                {
                                    cookie !.CommentUri = parsed;
                                }
                            }
                            break;

                        case CookieToken.Domain:
                            if (!domainSet)
                            {
                                domainSet       = true;
                                cookie !.Domain = CheckQuoted(_tokenizer.Value);
                                IsQuotedDomainField.SetValue(cookie, _tokenizer.Quoted);
                            }
                            break;

                        case CookieToken.Expires:
                            if (!expiresSet)
                            {
                                expiresSet = true;

                                if (DateTime.TryParse(CheckQuoted(_tokenizer.Value),
                                                      CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTime expires))
                                {
                                    cookie !.Expires = expires;
                                }
                                else
                                {
                                    // This cookie will be rejected
                                    InternalSetNameMethod(cookie !, string.Empty);
                                }
                            }
                            break;

                        case CookieToken.MaxAge:
                            if (!expiresSet)
                            {
                                expiresSet = true;
                                if (int.TryParse(CheckQuoted(_tokenizer.Value), out int parsed))
                                {
                                    cookie !.Expires = DateTime.Now.AddSeconds(parsed);
                                }
                                else
                                {
                                    // This cookie will be rejected
                                    InternalSetNameMethod(cookie !, string.Empty);
                                }
                            }
                            break;

                        case CookieToken.Path:
                            if (!pathSet)
                            {
                                pathSet       = true;
                                cookie !.Path = _tokenizer.Value;
                            }
                            break;

                        case CookieToken.Port:
                            if (!portSet)
                            {
                                portSet = true;
                                try
                                {
                                    cookie !.Port = _tokenizer.Value;
                                }
                                catch
                                {
                                    // This cookie will be rejected
                                    InternalSetNameMethod(cookie !, string.Empty);
                                }
                            }
                            break;

                        case CookieToken.Version:
                            if (!versionSet)
                            {
                                versionSet = true;
                                int parsed;
                                if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed))
                                {
                                    cookie !.Version = parsed;
                                    IsQuotedVersionField.SetValue(cookie, _tokenizer.Quoted);
                                }
                                else
                                {
                                    // This cookie will be rejected
                                    InternalSetNameMethod(cookie !, string.Empty);
                                }
                            }
                            break;
                        }
                        break;

                    case CookieToken.Attribute:
                        switch (_tokenizer.Token)
                        {
                        case CookieToken.Discard:
                            if (!discardSet)
                            {
                                discardSet       = true;
                                cookie !.Discard = true;
                            }
                            break;

                        case CookieToken.Secure:
                            if (!secureSet)
                            {
                                secureSet       = true;
                                cookie !.Secure = true;
                            }
                            break;

                        case CookieToken.HttpOnly:
                            cookie !.HttpOnly = true;
                            break;

                        case CookieToken.Port:
                            if (!portSet)
                            {
                                portSet       = true;
                                cookie !.Port = string.Empty;
                            }
                            break;
                        }
                        break;
                    }
                }
            } while (!_tokenizer.Eof && !_tokenizer.EndOfCookie);

            return(cookie);
        }
Пример #49
0
        private void MergeUpdateCollections(ref CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly)
        {
            lock (source)
            {
                // Cannot use foreach as we are going to update 'source'
                for (int idx = 0; idx < source.Count; ++idx)
                {
                    bool to_add = false;

                    Cookie cookie = source[idx];

                    if (cookie.Expired)
                    {
                        // If expired, remove from container and don't add to the destination
                        source.RemoveAt(idx);
                        --m_count;
                        --idx;
                    }
                    else
                    {
                        // Add only if port does match to this request URI
                        // or was not present in the original response.
                        if (isPlainOnly && cookie.Variant != CookieVariant.Plain)
                        {
                            ; // Don't add
                        }
                        else if (cookie.PortList != null)
                        {
                            foreach (int p in cookie.PortList)
                            {
                                if (p == port)
                                {
                                    to_add = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            // It was implicit Port, always OK to add.
                            to_add = true;
                        }

                        // Refuse to add a secure cookie into an 'unsecure' destination
                        if (cookie.Secure && !isSecure)
                        {
                            to_add = false;
                        }

                        if (to_add)
                        {
                            // In 'source' are already ordered.
                            // If two same cookies come from different 'source' then they
                            // will follow (not replace) each other.
                            if (destination == null)
                            {
                                destination = new CookieCollection();
                            }
                            destination.InternalAdd(cookie, false);
                        }
                    }
                }
            }
        }
Пример #50
0
 public abstract void SetCookie(System.Net.Cookie cookie);
 public override void AddCookie(System.Net.Cookie cookie)
 {
     base.AddCookie(cookie);
     // 如果 Downloader 在运行中, 需要把 Cookie 加到 Driver 中
     _driver?.Manage().Cookies.AddCookie(new OpenQA.Selenium.Cookie(cookie.Name, cookie.Value, cookie.Domain, cookie.Path, null));
 }
Пример #52
0
 // This method will construct a faked URI: the Domain property is required for param.
 public void Add(Cookie cookie !!)
 {
     if (cookie.Domain.Length == 0)
Пример #53
0
        // This method is called *only* when cookie verification is done, so unlike with public
        // Add(Cookie cookie) the cookie is in a reasonable condition.
        internal void Add(Cookie cookie, bool throwOnError)
        {
            PathList pathList;

            if (cookie.Value.Length > _maxCookieSize)
            {
                if (throwOnError)
                {
                    throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), _maxCookieSize));
                }
                return;
            }

            try
            {
                lock (_domainTable)
                {
                    if (!_domainTable.TryGetValue(cookie.DomainKey, out pathList))
                    {
                        _domainTable[cookie.DomainKey] = (pathList = PathList.Create());
                    }
                }
                int domain_count = pathList.GetCookiesCount();

                CookieCollection cookies;
                lock (pathList.SyncRoot)
                {
                    cookies = pathList[cookie.Path];

                    if (cookies == null)
                    {
                        cookies = new CookieCollection();
                        pathList[cookie.Path] = cookies;
                    }
                }

                if (cookie.Expired)
                {
                    // Explicit removal command (Max-Age == 0)
                    lock (cookies)
                    {
                        int idx = cookies.IndexOf(cookie);
                        if (idx != -1)
                        {
                            cookies.RemoveAt(idx);
                            --_count;
                        }
                    }
                }
                else
                {
                    // This is about real cookie adding, check Capacity first
                    if (domain_count >= _maxCookiesPerDomain && !AgeCookies(cookie.DomainKey))
                    {
                        return; // Cannot age: reject new cookie
                    }
                    else if (_count >= _maxCookies && !AgeCookies(null))
                    {
                        return; // Cannot age: reject new cookie
                    }

                    // About to change the collection
                    lock (cookies)
                    {
                        _count += cookies.InternalAdd(cookie, true);
                    }
                }
            }
            catch (OutOfMemoryException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (throwOnError)
                {
                    throw new CookieException(SR.net_container_add_cookie, e);
                }
            }
        }
        internal void SendHeaders(bool closing, MemoryStream ms)
        {
            Encoding @default = this.content_encoding;

            if (@default == null)
            {
                @default = Encoding.Default;
            }
            if (this.content_type != null)
            {
                if (this.content_encoding != null && this.content_type.IndexOf("charset=") == -1)
                {
                    string webName = this.content_encoding.WebName;
                    this.headers.SetInternal("Content-Type", this.content_type + "; charset=" + webName);
                }
                else
                {
                    this.headers.SetInternal("Content-Type", this.content_type);
                }
            }
            if (this.headers["Server"] == null)
            {
                this.headers.SetInternal("Server", "Mono-HTTPAPI/1.0");
            }
            CultureInfo invariantCulture = CultureInfo.InvariantCulture;

            if (this.headers["Date"] == null)
            {
                this.headers.SetInternal("Date", DateTime.UtcNow.ToString("r", invariantCulture));
            }
            if (!this.chunked)
            {
                if (!this.cl_set && closing)
                {
                    this.cl_set         = true;
                    this.content_length = 0L;
                }
                if (this.cl_set)
                {
                    this.headers.SetInternal("Content-Length", this.content_length.ToString(invariantCulture));
                }
            }
            Version protocolVersion = this.context.Request.ProtocolVersion;

            if (!this.cl_set && !this.chunked && protocolVersion >= HttpVersion.Version11)
            {
                this.chunked = true;
            }
            bool flag = this.status_code == 400 || this.status_code == 408 || this.status_code == 411 || this.status_code == 413 || this.status_code == 414 || this.status_code == 500 || this.status_code == 503;

            if (!flag)
            {
                flag  = (this.context.Request.Headers["connection"] == "close");
                flag |= (protocolVersion <= HttpVersion.Version10);
            }
            if (!this.keep_alive || flag)
            {
                this.headers.SetInternal("Connection", "close");
            }
            if (this.chunked)
            {
                this.headers.SetInternal("Transfer-Encoding", "chunked");
            }
            int chunkedUses = this.context.Connection.ChunkedUses;

            if (chunkedUses >= 100)
            {
                this.force_close_chunked = true;
                if (!flag)
                {
                    this.headers.SetInternal("Connection", "close");
                }
            }
            if (this.location != null)
            {
                this.headers.SetInternal("Location", this.location);
            }
            if (this.cookies != null)
            {
                foreach (object obj in this.cookies)
                {
                    Cookie cookie = (Cookie)obj;
                    this.headers.SetInternal("Set-Cookie", cookie.ToClientString());
                }
            }
            StreamWriter streamWriter = new StreamWriter(ms, @default);

            streamWriter.Write("HTTP/{0} {1} {2}\r\n", this.version, this.status_code, this.status_description);
            string value = this.headers.ToStringMultiValue();

            streamWriter.Write(value);
            streamWriter.Flush();
            int num = @default.GetPreamble().Length;

            if (this.output_stream == null)
            {
                this.output_stream = this.context.Connection.GetResponseStream();
            }
            ms.Position      = (long)num;
            this.HeadersSent = true;
        }
Пример #55
0
        public void SetCookies(Uri uri, string cookieHeader)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (cookieHeader == null)
            {
                throw new ArgumentNullException("cookieHeader");
            }

            if (cookieHeader.Length == 0)
            {
                return;
            }

            // Cookies must be separated by ',' (like documented on MSDN)
            // but expires uses DAY, DD-MMM-YYYY HH:MM:SS GMT, so simple ',' search is wrong.
            // See http://msdn.microsoft.com/en-us/library/aa384321%28VS.85%29.aspx
            string [] jar = cookieHeader.Split(',');
            string    tmpCookie;

            for (int i = 0; i < jar.Length; i++)
            {
                tmpCookie = jar [i];

                if (jar.Length > i + 1 &&
                    Regex.IsMatch(jar[i],
                                  @".*expires\s*=\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)",
                                  RegexOptions.IgnoreCase) &&
                    Regex.IsMatch(jar[i + 1],
                                  @"\s\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4} \d{2}:\d{2}:\d{2} GMT",
                                  RegexOptions.IgnoreCase))
                {
                    tmpCookie = new StringBuilder(tmpCookie).Append(",").Append(jar [++i]).ToString();
                }

                try {
                    Cookie c = Parse(tmpCookie);

                    // add default values from URI if missing from the string
                    if (c.Path.Length == 0)
                    {
                        c.Path = uri.AbsolutePath;
                    }
                    else if (!uri.AbsolutePath.StartsWith(c.Path))
                    {
                        string msg = String.Format("'Path'='{0}' is invalid with URI", c.Path);
                        throw new CookieException(msg);
                    }

                    if (c.Domain.Length == 0)
                    {
                        c.Domain = uri.Host;
                        // don't consider domain "a.b.com" as ".a.b.com"
                        c.ExactDomain = true;
                    }

                    AddCookie(c);
                }
                catch (Exception e) {
                    string msg = String.Format("Could not parse cookies for '{0}'.", uri);
                    throw new CookieException(msg, e);
                }
            }
        }
 public void AddCookies(System.Net.Cookie cookie)
 {
     _cookiejar.Add(cookie);
 }
Пример #57
0
        /// <summary>
        /// Parse out a list of cookies from "Set-Cookie" header.
        /// </summary>
        /// <param name="requestUri">The request uri associated with the response "Set-Cookie" header.</param>
        /// <param name="setCookieHeader">The value of "Set-Cookie" header.</param>
        /// <returns>A collection of cookies.</returns>
        public static CookieCollection ParseResponseCookie(Uri requestUri, string setCookieHeader)
        {
            CookieCollection cookies = new CookieCollection();

            string[] cookieItems = setCookieHeader.Split(new string[] { ";," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var cookieItem in cookieItems)
            {
                string[] items = cookieItem.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                var cookie = new System.Net.Cookie
                {
                    Domain = requestUri?.Host ?? string.Empty,
                    Path   = "/"
                };

                foreach (var item in items)
                {
                    string[] pairs = item.Split('=');
                    switch (pairs[0].ToLowerInvariant().Trim())
                    {
                    case "domain":
                        cookie.Domain = pairs[1].Trim();
                        break;

                    case "httponly":
                        cookie.HttpOnly = true;
                        break;

                    case "expires":
                        cookie.Expires = DateTime.Parse(pairs[1]);
                        break;

                    case "path":
                        cookie.Path = pairs[1].Trim();
                        break;

                    case "comment":
                        cookie.Comment = pairs[1].Trim();
                        break;

                    case "max-age":
                        cookie.Expires = DateTime.Now.AddSeconds(int.Parse(pairs[1]));
                        break;

                    case "version":
                        // The default value for the Version property is 0, complying with the original Netscape specification.
                        // If the value is explicitly set to 1, then this Cookie must conform to RFC 2109 when one uses
                        // System.Net.CookieContainer.Add() methods, which means that the "Domain" value must start with "."
                        // This is not the case all the time.
                        cookie.Version = int.Parse(pairs[1].Trim());
                        break;

                    case "secure":
                        cookie.Secure = true;
                        break;

                    default:
                        cookie.Name            = pairs[0].Trim();
                        cookie.Value           = pairs.Length > 1
                                ? cookie.Value = item.Substring(pairs[0].Length + 1)
                                : string.Empty;
                        break;
                    }
                }

                cookies.Add(cookie);
            }

            return(cookies);
        }
 public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
 {
     // Do not use forms credentials to authenticate.
     authCookie = null;
     user = password = authority = null;
     return false;
 }