Inheritance: Sharpen.URLConnection
Exemple #1
0
 /// <summary>Handle an authentication failure and possibly return a new response.</summary>
 /// <remarks>Handle an authentication failure and possibly return a new response.</remarks>
 /// <param name="conn">the connection that failed.</param>
 /// <returns>new authentication method to try.</returns>
 internal static HttpAuthMethod ScanResponse(HttpURLConnection conn)
 {
     string hdr = conn.GetHeaderField(HttpSupport.HDR_WWW_AUTHENTICATE);
     if (hdr == null || hdr.Length == 0)
     {
         return NONE;
     }
     int sp = hdr.IndexOf(' ');
     if (sp < 0)
     {
         return NONE;
     }
     string type = Sharpen.Runtime.Substring(hdr, 0, sp);
     if (Sharpen.Runtime.EqualsIgnoreCase(HttpAuthMethod.Basic.NAME, type))
     {
         return new HttpAuthMethod.Basic();
     }
     else
     {
         if (Sharpen.Runtime.EqualsIgnoreCase(HttpAuthMethod.Digest.NAME, type))
         {
             return new HttpAuthMethod.Digest(Sharpen.Runtime.Substring(hdr, sp + 1));
         }
         else
         {
             return NONE;
         }
     }
 }
Exemple #2
0
        const string SCHEMA_NAME_SEPARATOR = " "; //$NON-NLS-1$

        #endregion Fields

        #region Methods

        /// <summary>Handle an authentication failure and possibly return a new response.</summary>
        /// <remarks>Handle an authentication failure and possibly return a new response.</remarks>
        /// <param name="conn">the connection that failed.</param>
        /// <returns>new authentication method to try.</returns>
        internal static HttpAuthMethod ScanResponse(HttpURLConnection conn)
        {
            HttpAuthMethod authentication = NONE;
            var headers = conn.GetHeaders();

            if (headers != null)
            {
                foreach (var authHeader in headers.GetValues(HttpSupport.HDR_WWW_AUTHENTICATE))
                {
                    if (!string.IsNullOrEmpty(authHeader))
                    {
                        var valueParts = authHeader.Split(SCHEMA_NAME_SEPARATOR.ToCharArray(), 2);
                        var method = valueParts[0];
                        var param = valueParts.Length == 1 ? string.Empty : valueParts[1];

                        if (Sharpen.Runtime.EqualsIgnoreCase(HttpAuthMethod.Digest.NAME, method))
                        {
                            return new HttpAuthMethod.Digest(param);
                        }

                        if (Sharpen.Runtime.EqualsIgnoreCase(HttpAuthMethod.Basic.NAME, method))
                        {
                            authentication = new HttpAuthMethod.Basic();
                        }
                    }
                }
            }

            return authentication;
        }
Exemple #3
0
		/// <exception cref="System.IO.IOException"></exception>
		protected internal virtual void ValidateImpl(HttpURLConnection u, string p, string
			 version, string name)
		{
			string v;
			v = u.GetHeaderField(p + JETS3T_CRYPTO_VER);
			if (v == null)
			{
				v = string.Empty;
			}
			if (!version.Equals(v))
			{
				throw new IOException(MessageFormat.Format(JGitText.Get().unsupportedEncryptionVersion
					, v));
			}
			v = u.GetHeaderField(p + JETS3T_CRYPTO_ALG);
			if (v == null)
			{
				v = string.Empty;
			}
			if (!name.Equals(v))
			{
				throw new IOException(JGitText.Get().unsupportedEncryptionAlgorithm + v);
			}
		}
Exemple #4
0
		/// <exception cref="System.IO.IOException"></exception>
		private IOException Error(string action, string key, HttpURLConnection c)
		{
			IOException err = new IOException(MessageFormat.Format(JGitText.Get().amazonS3ActionFailed
				, action, key, HttpSupport.Response(c), c.GetResponseMessage()));
			ByteArrayOutputStream b = new ByteArrayOutputStream();
			byte[] buf = new byte[2048];
			for (; ; )
			{
				int n = c.GetErrorStream().Read(buf);
				if (n < 0)
				{
					break;
				}
				if (n > 0)
				{
					b.Write(buf, 0, n);
				}
			}
			buf = b.ToByteArray();
			if (buf.Length > 0)
			{
				Sharpen.Extensions.InitCause(err, new IOException("\n" + Sharpen.Extensions.CreateString
					(buf)));
			}
			return err;
		}
Exemple #5
0
		/// <summary>Get the HTTP response code from the request.</summary>
		/// <remarks>
		/// Get the HTTP response code from the request.
		/// <p>
		/// Roughly the same as <code>c.getResponseCode()</code> but the
		/// ConnectException is translated to be more understandable.
		/// </remarks>
		/// <param name="c">connection the code should be obtained from.</param>
		/// <returns>
		/// r HTTP status code, usually 200 to indicate success. See
		/// <see cref="Sharpen.HttpURLConnection">Sharpen.HttpURLConnection</see>
		/// for other defined constants.
		/// </returns>
		/// <exception cref="System.IO.IOException">communications error prevented obtaining the response code.
		/// 	</exception>
		public static int Response(HttpURLConnection c)
		{
			try
			{
				return c.GetResponseCode();
			}
			catch (ConnectException ce)
			{
				string host = c.GetURL().GetHost();
				// The standard J2SE error message is not very useful.
				//
				if ("Connection timed out: connect".Equals(ce.Message))
				{
					throw new ConnectException(MessageFormat.Format(JGitText.Get().connectionTimeOut, 
						host));
				}
				throw new ConnectException(ce.Message + " " + host);
			}
		}
Exemple #6
0
 // Do nothing when no authentication is enabled.
 /// <exception cref="System.IO.IOException"></exception>
 internal override void ConfigureRequest(HttpURLConnection conn)
 {
 }
Exemple #7
0
 /// <exception cref="System.IO.IOException"></exception>
 internal override void ConfigureRequest(HttpURLConnection conn)
 {
     IDictionary<string, string> r = new LinkedHashMap<string, string>();
     string realm = @params.Get("realm");
     string nonce = @params.Get("nonce");
     string cnonce = @params.Get("cnonce");
     string uri = Uri(conn.GetURL());
     string qop = @params.Get("qop");
     string method = conn.GetRequestMethod();
     string A1 = user + ":" + realm + ":" + pass;
     string A2 = method + ":" + uri;
     r.Put("username", user);
     r.Put("realm", realm);
     r.Put("nonce", nonce);
     r.Put("uri", uri);
     string response;
     string nc;
     if ("auth".Equals(qop))
     {
         nc = string.Format("%08x", ++requestCount);
         response = KD(H(A1), nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + H(A2));
     }
     else
     {
         nc = null;
         response = KD(H(A1), nonce + ":" + H(A2));
     }
     r.Put("response", response);
     if (@params.ContainsKey("algorithm"))
     {
         r.Put("algorithm", "MD5");
     }
     if (cnonce != null && qop != null)
     {
         r.Put("cnonce", cnonce);
     }
     if (@params.ContainsKey("opaque"))
     {
         r.Put("opaque", @params.Get("opaque"));
     }
     if (qop != null)
     {
         r.Put("qop", qop);
     }
     if (nc != null)
     {
         r.Put("nc", nc);
     }
     StringBuilder v = new StringBuilder();
     foreach (KeyValuePair<string, string> e in r.EntrySet())
     {
         if (v.Length > 0)
         {
             v.Append(", ");
         }
         v.Append(e.Key);
         v.Append('=');
         v.Append('"');
         v.Append(e.Value);
         v.Append('"');
     }
     conn.SetRequestProperty(HttpSupport.HDR_AUTHORIZATION, NAME + " " + v);
 }
Exemple #8
0
 /// <exception cref="System.IO.IOException"></exception>
 internal override void ConfigureRequest(HttpURLConnection conn)
 {
     string ident = user + ":" + pass;
     string enc = Base64.EncodeBytes(Sharpen.Runtime.GetBytesForString(ident, "UTF-8")
         );
     conn.SetRequestProperty(HttpSupport.HDR_AUTHORIZATION, NAME + " " + enc);
 }
			internal override void Request(HttpURLConnection u, string prefix)
			{
				u.SetRequestProperty(prefix + JETS3T_CRYPTO_VER, "2");
				u.SetRequestProperty(prefix + JETS3T_CRYPTO_ALG, algorithmName);
			}
Exemple #10
0
		/// <exception cref="System.IO.IOException"></exception>
		internal abstract void Validate(HttpURLConnection u, string p);
Exemple #11
0
		internal abstract void Request(HttpURLConnection u, string prefix);
Exemple #12
0
			// Don't store any request properties.
			/// <exception cref="System.IO.IOException"></exception>
			internal override void Validate(HttpURLConnection u, string p)
			{
				ValidateImpl(u, p, string.Empty, string.Empty);
			}
Exemple #13
0
			internal override void Request(HttpURLConnection u, string prefix)
			{
			}
			/// <exception cref="System.IO.IOException"></exception>
			internal override void ConfigureRequest(HttpURLConnection conn)
			{
				IDictionary<string, string> p = new Dictionary<string, string>(@params);
				p.Put("username", user);
				string realm = p.Get("realm");
				string nonce = p.Get("nonce");
				string uri = p.Get("uri");
				string qop = p.Get("qop");
				string method = conn.GetRequestMethod();
				string A1 = user + ":" + realm + ":" + pass;
				string A2 = method + ":" + uri;
				string expect;
				if ("auth".Equals(qop))
				{
					string c = p.Get("cnonce");
					string nc = string.Format("%08x", ++requestCount);
					p.Put("nc", nc);
					expect = KD(H(A1), nonce + ":" + nc + ":" + c + ":" + qop + ":" + H(A2));
				}
				else
				{
					expect = KD(H(A1), nonce + ":" + H(A2));
				}
				p.Put("response", expect);
				StringBuilder v = new StringBuilder();
				foreach (KeyValuePair<string, string> e in p.EntrySet())
				{
					if (v.Length > 0)
					{
						v.Append(", ");
					}
					v.Append(e.Key);
					v.Append('=');
					v.Append('"');
					v.Append(e.Value);
					v.Append('"');
				}
				conn.SetRequestProperty(HttpSupport.HDR_AUTHORIZATION, NAME + " " + v);
			}
			/// <exception cref="System.IO.IOException"></exception>
			internal override void Validate(HttpURLConnection u, string p)
			{
				ValidateImpl(u, p, "2", algorithmName);
			}
Exemple #16
0
		/// <exception cref="System.IO.IOException"></exception>
		private void Authorize(HttpURLConnection c)
		{
			IDictionary<string, IList<string>> reqHdr = c.GetRequestProperties();
			SortedDictionary<string, string> sigHdr = new SortedDictionary<string, string>();
			foreach (KeyValuePair<string, IList<string>> entry in reqHdr.EntrySet())
			{
				string hdr = entry.Key;
				if (IsSignedHeader(hdr))
				{
					sigHdr.Put(StringUtils.ToLowerCase(hdr), ToCleanString(entry.Value));
				}
			}
			StringBuilder s = new StringBuilder();
			s.Append(c.GetRequestMethod());
			s.Append('\n');
			s.Append(Remove(sigHdr, "content-md5"));
			s.Append('\n');
			s.Append(Remove(sigHdr, "content-type"));
			s.Append('\n');
			s.Append(Remove(sigHdr, "date"));
			s.Append('\n');
			foreach (KeyValuePair<string, string> e in sigHdr.EntrySet())
			{
				s.Append(e.Key);
				s.Append(':');
				s.Append(e.Value);
				s.Append('\n');
			}
			string host = c.GetURL().GetHost();
			s.Append('/');
			s.Append(Sharpen.Runtime.Substring(host, 0, host.Length - DOMAIN.Length - 1));
			s.Append(c.GetURL().AbsolutePath);
			string sec;
			try
			{
				Mac m = Mac.GetInstance(HMAC);
				m.Init(privateKey);
				sec = Base64.EncodeBytes(m.DoFinal(Sharpen.Runtime.GetBytesForString(s.ToString()
					, "UTF-8")));
			}
			catch (NoSuchAlgorithmException e_1)
			{
				throw new IOException(MessageFormat.Format(JGitText.Get().noHMACsupport, HMAC, e_1
					.Message));
			}
			catch (InvalidKeyException e_1)
			{
				throw new IOException(MessageFormat.Format(JGitText.Get().invalidKey, e_1.Message
					));
			}
			c.SetRequestProperty("Authorization", "AWS " + publicKey + ":" + sec);
		}
        internal virtual object ParseJSONResponse(HttpURLConnection conn)
        {
            Object result = null;
            var stream = conn.GetOutputStream();
            var bytesRead = 0L;
            const Int32 chunkSize = 8192;
             
            var bytes = stream.ReadAllBytes();

            var responseBody = new Body(bytes);
            if (responseBody != null)
            {
                var json = responseBody.GetJson();
                String jsonString = null;
                if (json != null)
                {
                    jsonString = Runtime.GetStringForBytes(json);
                    try
                    {
                        result = mapper.ReadValue<object>(jsonString);
                    }
                    catch (Exception)
                    {
                        Assert.Fail();
                    }
                }
            }
            return result;
        }
Exemple #18
0
 /// <summary>Update connection properties based on this authentication method.</summary>
 /// <remarks>Update connection properties based on this authentication method.</remarks>
 /// <param name="conn"></param>
 /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
 internal abstract void ConfigureRequest(HttpURLConnection conn);