コード例 #1
0
ファイル: SaslMechanismPlain.cs プロジェクト: hl46000/MailKit
        /// <summary>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </summary>
        /// <remarks>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </remarks>
        /// <returns>The next challenge response.</returns>
        /// <param name="token">The server's challenge token.</param>
        /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
        /// <param name="length">The length of the server's challenge.</param>
        /// <exception cref="System.InvalidOperationException">
        /// The SASL mechanism is already authenticated.
        /// </exception>
        /// <exception cref="SaslException">
        /// An error has occurred while parsing the server's challenge token.
        /// </exception>
        protected override byte[] Challenge(byte[] token, int startIndex, int length)
        {
            if (IsAuthenticated)
            {
                throw new InvalidOperationException();
            }

            var cred     = Credentials.GetCredential(Uri, MechanismName);
            var userName = encoding.GetBytes(cred.UserName);
            var password = encoding.GetBytes(cred.Password);
            var buffer   = new byte[userName.Length + password.Length + 2];
            int offset   = 0;

            buffer[offset++] = 0;
            for (int i = 0; i < userName.Length; i++)
            {
                buffer[offset++] = userName[i];
            }

            buffer[offset++] = 0;
            for (int i = 0; i < password.Length; i++)
            {
                buffer[offset++] = password[i];
            }

            IsAuthenticated = true;

            return(buffer);
        }
コード例 #2
0
ファイル: ImapUtils.cs プロジェクト: tfreitasleal/MailKit
        static string ReadNStringToken(ImapEngine engine, bool rfc2047, CancellationToken cancellationToken)
        {
            var    token = engine.ReadToken(cancellationToken);
            string value;

            switch (token.Type)
            {
            case ImapTokenType.Literal:
                value = engine.ReadLiteral(cancellationToken);
                break;

            case ImapTokenType.QString:
            case ImapTokenType.Atom:
                value = (string)token.Value;
                break;

            case ImapTokenType.Nil:
                return(null);

            default:
                throw ImapEngine.UnexpectedToken(token, false);
            }

            return(rfc2047 ? Rfc2047.DecodeText(Latin1.GetBytes(value)) : value);
        }
コード例 #3
0
ファイル: SaslMechanismPlain.cs プロジェクト: shekky/MailKit
        /// <summary>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </summary>
        /// <remarks>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </remarks>
        /// <returns>The next challenge response.</returns>
        /// <param name="token">The server's challenge token.</param>
        /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
        /// <param name="length">The length of the server's challenge.</param>
        /// <exception cref="System.InvalidOperationException">
        /// The SASL mechanism is already authenticated.
        /// </exception>
        /// <exception cref="SaslException">
        /// An error has occurred while parsing the server's challenge token.
        /// </exception>
        protected override byte[] Challenge(byte[] token, int startIndex, int length)
        {
            if (IsAuthenticated)
            {
                throw new InvalidOperationException();
            }

            var authzid = encoding.GetBytes(Credentials.Domain ?? string.Empty);
            var authcid = encoding.GetBytes(Credentials.UserName);
            var passwd  = encoding.GetBytes(Credentials.Password);
            var buffer  = new byte[authzid.Length + authcid.Length + passwd.Length + 2];
            int offset  = 0;

            for (int i = 0; i < authzid.Length; i++)
            {
                buffer[offset++] = authzid[i];
            }

            buffer[offset++] = 0;
            for (int i = 0; i < authcid.Length; i++)
            {
                buffer[offset++] = authcid[i];
            }

            buffer[offset++] = 0;
            for (int i = 0; i < passwd.Length; i++)
            {
                buffer[offset++] = passwd[i];
            }

            IsAuthenticated = true;

            return(buffer);
        }
コード例 #4
0
        /// <summary>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </summary>
        /// <remarks>
        /// Parses the server's challenge token and returns the next challenge response.
        /// </remarks>
        /// <returns>The next challenge response.</returns>
        /// <param name="token">The server's challenge token.</param>
        /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
        /// <param name="length">The length of the server's challenge.</param>
        /// <exception cref="System.InvalidOperationException">
        /// The SASL mechanism is already authenticated.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The SASL mechanism does not support SASL-IR.
        /// </exception>
        /// <exception cref="SaslException">
        /// An error has occurred while parsing the server's challenge token.
        /// </exception>
        protected override byte[] Challenge(byte[] token, int startIndex, int length)
        {
            byte[] challenge;

            if (token == null)
            {
                throw new NotSupportedException("LOGIN does not support SASL-IR.");
            }

            switch (state)
            {
            case LoginState.UserName:
                challenge = encoding.GetBytes(Credentials.UserName);
                state     = LoginState.Password;
                break;

            case LoginState.Password:
                challenge       = encoding.GetBytes(Credentials.Password);
                IsAuthenticated = true;
                break;

            default:
                throw new InvalidOperationException();
            }

            return(challenge);
        }
コード例 #5
0
ファイル: Header.cs プロジェクト: tfreitasleal/MimeKit
        static byte[] EncodeReferencesHeader(ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
        {
            var encoded    = new StringBuilder();
            int lineLength = field.Length + 1;
            int count      = 0;

            foreach (var reference in MimeUtils.EnumerateReferences(value))
            {
                if (count > 0 && lineLength + reference.Length + 3 > format.MaxLineLength)
                {
                    encoded.Append(format.NewLine);
                    encoded.Append('\t');
                    lineLength = 1;
                    count      = 0;
                }
                else
                {
                    encoded.Append(' ');
                    lineLength++;
                }

                encoded.Append('<').Append(reference).Append('>');
                lineLength += reference.Length + 2;
                count++;
            }

            encoded.Append(format.NewLine);

            return(charset.GetBytes(encoded.ToString()));
        }
コード例 #6
0
        public static string UrlEncode(string s, Encoding Enc)
        {
            if (s == null)
            {
                return(null);
            }
            if (s == string.Empty)
            {
                return(string.Empty);
            }
            bool flag   = false;
            int  length = s.Length;

            for (int i = 0; i < length; i++)
            {
                char c = s[i];
                if (((((c < '0') || ((c < 'A') && (c > '9'))) || ((c > 'Z') && (c < 'a'))) || (c > 'z')) && !HttpEncoder.NotEncoded(c))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                return(s);
            }
            byte[] bytes = new byte[Enc.GetMaxByteCount(s.Length)];
            int    count = Enc.GetBytes(s, 0, s.Length, bytes, 0);

            return(Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, count)));
        }
コード例 #7
0
        public byte[] Encode(Encoding encoding)
        {
            var builder = new StringBuilder();

            builder.AppendFormat("username={0}", Quote(UserName));
            builder.AppendFormat(",realm=\"{0}\"", Realm);
            builder.AppendFormat(",nonce=\"{0}\"", Nonce);
            builder.AppendFormat(",cnonce=\"{0}\"", CNonce);
            builder.AppendFormat(",nc={0:x8}", Nc);
            builder.AppendFormat(",qop=\"{0}\"", Qop);
            builder.AppendFormat(",digest-uri=\"{0}\"", DigestUri);
            builder.AppendFormat(",response={0}", Response);
            if (MaxBuf.HasValue)
            {
                builder.AppendFormat(",maxbuf={0}", MaxBuf.Value);
            }
            if (!string.IsNullOrEmpty(Charset))
            {
                builder.AppendFormat(",charset={0}", Charset);
            }
            if (!string.IsNullOrEmpty(Algorithm))
            {
                builder.AppendFormat(",algorithm={0}", Algorithm);
            }
            if (!string.IsNullOrEmpty(Cipher))
            {
                builder.AppendFormat(",cipher=\"{0}\"", Cipher);
            }
            if (!string.IsNullOrEmpty(AuthZid))
            {
                builder.AppendFormat(",authzid=\"{0}\"", AuthZid);
            }

            return(encoding.GetBytes(builder.ToString()));
        }
コード例 #8
0
ファイル: ImapUtils.cs プロジェクト: kannan-ar/MailKit
        static void AddEnvelopeAddress(InternetAddressList list, ImapEngine engine, CancellationToken cancellationToken)
        {
            var values = new string[4];
            ImapToken token;
            int index = 0;

            do {
                token = engine.ReadToken (cancellationToken);

                switch (token.Type) {
                case ImapTokenType.Literal:
                    values[index] = engine.ReadLiteral (cancellationToken);
                    break;
                case ImapTokenType.QString:
                case ImapTokenType.Atom:
                    values[index] = (string) token.Value;
                    break;
                case ImapTokenType.Nil:
                    break;
                default:
                    throw ImapEngine.UnexpectedToken (token, false);
                }

                index++;
            } while (index < 4);

            token = engine.ReadToken (cancellationToken);

            if (token.Type != ImapTokenType.CloseParen)
                throw ImapEngine.UnexpectedToken (token, false);

            string name = null;

            if (values[0] != null) {
                // Note: since the ImapEngine.ReadLiteral() uses iso-8859-1
                // to convert bytes to unicode, we can undo that here:
                name = Rfc2047.DecodePhrase (Latin1.GetBytes (values[0]));
            }

            string address = values[3] != null ? values[2] + "@" + values[3] : values[2];
            DomainList route;

            if (values[1] != null && DomainList.TryParse (values[1], out route))
                list.Add (new MailboxAddress (name, route, address));
            else
                list.Add (new MailboxAddress (name, address));
        }
コード例 #9
0
        public string ComputeHash(Encoding encoding, string password, bool client)
        {
            string text, a1, a2;

            byte[] buf, digest;

            // compute A1
            text = string.Format("{0}:{1}:{2}", UserName, Realm, password);
            buf  = encoding.GetBytes(text);
            using (var md5 = MD5.Create())
                digest = md5.ComputeHash(buf);

            using (var md5 = MD5.Create()) {
                md5.TransformBlock(digest, 0, digest.Length, null, 0);
                text = string.Format(":{0}:{1}", Nonce, CNonce);
                if (!string.IsNullOrEmpty(AuthZid))
                {
                    text += ":" + AuthZid;
                }
                buf = encoding.GetBytes(text);
                md5.TransformFinalBlock(buf, 0, buf.Length);
                a1 = HexEncode(md5.Hash);
            }

            // compute A2
            text  = client ? "AUTHENTICATE:" : ":";
            text += DigestUri;

            if (Qop == "auth-int" || Qop == "auth-conf")
            {
                text += ":00000000000000000000000000000000";
            }

            buf = encoding.GetBytes(text);
            using (var md5 = MD5.Create())
                digest = md5.ComputeHash(buf);
            a2 = HexEncode(digest);

            // compute KD
            text = string.Format("{0}:{1}:{2:x8}:{3}:{4}:{5}", a1, Nonce, Nc, CNonce, Qop, a2);
            buf  = encoding.GetBytes(text);
            using (var md5 = MD5.Create())
                digest = md5.ComputeHash(buf);

            return(HexEncode(digest));
        }
コード例 #10
0
 public static byte[] UrlDecodeToBytes(string str, Encoding e)
 {
     if (str == null)
     {
         return(null);
     }
     if (e == null)
     {
         throw new ArgumentNullException("e");
     }
     return(UrlDecodeToBytes(e.GetBytes(str)));
 }
コード例 #11
0
ファイル: TextPart.cs プロジェクト: shekky/MimeKit
		/// <summary>
		/// Sets the text content and the charset parameter in the Content-Type header.
		/// </summary>
		/// <remarks>
		/// This method is similar to setting the <see cref="TextPart.Text"/> property,
		/// but allows specifying a charset encoding to use. Also updates the
		/// <see cref="ContentType.Charset"/> property.
		/// </remarks>
		/// <param name="encoding">The charset encoding.</param>
		/// <param name="text">The text content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="encoding"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="text"/> is <c>null</c>.</para>
		/// </exception>
		public void SetText (Encoding encoding, string text)
		{
			if (encoding == null)
				throw new ArgumentNullException (nameof (encoding));

			if (text == null)
				throw new ArgumentNullException (nameof (text));

			ContentType.Parameters["charset"] = CharsetUtils.GetMimeCharset (encoding);
			var content = new MemoryStream (encoding.GetBytes (text));
			Content = new MimeContent (content);
		}
コード例 #12
0
 public static byte[] UrlEncodeToBytes(string str, Encoding e)
 {
     if (str == null)
     {
         return(null);
     }
     if (str.Length == 0)
     {
         return(new byte[0]);
     }
     byte[] bytes = e.GetBytes(str);
     return(UrlEncodeToBytes(bytes, 0, bytes.Length));
 }
コード例 #13
0
 private static void WriteCharBytes(IList buf, char ch, Encoding e)
 {
     if (ch > '\x00ff')
     {
         foreach (byte num in e.GetBytes(new char[] { ch }))
         {
             buf.Add(num);
         }
     }
     else
     {
         buf.Add((byte)ch);
     }
 }
コード例 #14
0
ファイル: TextPart.cs プロジェクト: rajeshwarn/MimeKit
        /// <summary>
        /// Sets the text content and the charset parameter in the Content-Type header.
        /// </summary>
        /// <remarks>
        /// This method is similar to setting the <see cref="Text"/> property, but allows
        /// specifying a charset encoding to use. Also updates the
        /// <see cref="ContentType.Charset"/> property.
        /// </remarks>
        /// <param name="charset">The charset encoding.</param>
        /// <param name="text">The text content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="charset"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="text"/> is <c>null</c>.</para>
        /// </exception>
        public void SetText(Encoding charset, string text)
        {
            if (charset == null)
            {
                throw new ArgumentNullException("charset");
            }

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

            var content = new MemoryStream(charset.GetBytes(text));

            ContentObject = new ContentObject(content, ContentEncoding.Default);
            ContentType.Parameters["charset"] = CharsetUtils.GetMimeCharset(charset);
        }
コード例 #15
0
		/// <summary>
		/// Sets the text content and the charset parameter in the Content-Type header.
		/// </summary>
		/// <remarks>
		/// This method is similar to setting the <see cref="Text"/> property, but allows
		/// specifying a charset encoding to use. Also updates the
		/// <see cref="ContentType.Charset"/> property.
		/// </remarks>
		/// <param name="encoding">The charset encoding.</param>
		/// <param name="text">The text content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="encoding"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="text"/> is <c>null</c>.</para>
		/// </exception>
		public void SetText (Encoding encoding, string text)
		{
			if (encoding == null)
				throw new ArgumentNullException ("encoding");

			if (text == null)
				throw new ArgumentNullException ("text");

			ContentType.Parameters["charset"] = CharsetUtils.GetMimeCharset (encoding);
			var content = new MemoryStream (encoding.GetBytes (text));
			ContentObject = new ContentObject (content);
		}
コード例 #16
0
ファイル: Header.cs プロジェクト: naeemkhedarun/MimeKit
		static byte[] EncodeReferencesHeader (ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
		{
			var encoded = new StringBuilder ();
			int lineLength = field.Length + 1;
			int count = 0;

			foreach (var reference in MimeUtils.EnumerateReferences (value)) {
				if (count > 0 && lineLength + reference.Length + 3 > format.MaxLineLength) {
					encoded.Append (format.NewLine);
					encoded.Append ('\t');
					lineLength = 1;
					count = 0;
				} else {
					encoded.Append (' ');
					lineLength++;
				}

				encoded.Append ('<').Append (reference).Append ('>');
				lineLength += reference.Length + 2;
				count++;
			}

			encoded.Append (format.NewLine);

			return charset.GetBytes (encoded.ToString ());
		}
コード例 #17
0
ファイル: Header.cs プロジェクト: naeemkhedarun/MimeKit
		static byte[] EncodeDkimSignatureHeader (ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
		{
			var encoded = new StringBuilder ();
			int lineLength = field.Length + 1;
			var token = new StringBuilder ();
			int index = 0;

			while (index < value.Length) {
				while (index < value.Length && IsWhiteSpace (value[index]))
					index++;

				int startIndex = index;
				string name;

				while (index < value.Length && value[index] != '=') {
					if (!IsWhiteSpace (value[index]))
						token.Append (value[index]);
					index++;
				}

				name = value.Substring (startIndex, index - startIndex);

				while (index < value.Length && value[index] != ';') {
					if (!IsWhiteSpace (value[index]))
						token.Append (value[index]);
					index++;
				}

				if (index < value.Length && value[index] == ';') {
					token.Append (';');
					index++;
				}

				if (lineLength + token.Length + 1 > format.MaxLineLength || name == "bh" || name == "b") {
					encoded.Append (format.NewLine);
					encoded.Append ('\t');
					lineLength = 1;
				} else {
					encoded.Append (' ');
					lineLength++;
				}

				if (token.Length > format.MaxLineLength) {
					switch (name) {
					case "z":
						EncodeDkimHeaderList (format, encoded, ref lineLength, token.ToString (), '|');
						break;
					case "h":
						EncodeDkimHeaderList (format, encoded, ref lineLength, token.ToString (), ':');
						break;
					default:
						EncodeDkimLongValue (format, encoded, ref lineLength, token.ToString ());
						break;
					}
				} else {
					encoded.Append (token.ToString ());
					lineLength += token.Length;
				}

				token.Length = 0;
			}

			encoded.Append (format.NewLine);

			return charset.GetBytes (encoded.ToString ());
		}
コード例 #18
0
ファイル: Header.cs プロジェクト: naeemkhedarun/MimeKit
		static byte[] EncodeReceivedHeader (ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
		{
			var tokens = new List<ReceivedTokenValue> ();
			var rawValue = charset.GetBytes (value);
			var encoded = new StringBuilder ();
			int lineLength = field.Length + 1;
			bool date = false;
			int index = 0;
			int count = 0;

			while (index < rawValue.Length) {
				ReceivedTokenValue token = null;
				int startIndex = index;

				if (!ParseUtils.SkipCommentsAndWhiteSpace (rawValue, ref index, rawValue.Length, false) || index >= rawValue.Length) {
					tokens.Add (new ReceivedTokenValue (startIndex, index - startIndex));
					break;
				}

				while (index < rawValue.Length && !rawValue[index].IsWhitespace ())
					index++;

				var atom = charset.GetString (rawValue, startIndex, index - startIndex);

				for (int i = 0; i < ReceivedTokens.Length; i++) {
					if (atom == ReceivedTokens[i].Atom) {
						ReceivedTokens[i].Skip (rawValue, ref index);

						if (ParseUtils.SkipCommentsAndWhiteSpace (rawValue, ref index, rawValue.Length, false)) {
							if (index < rawValue.Length && rawValue[index] == (byte) ';') {
								date = true;
								index++;
							}
						}

						token = new ReceivedTokenValue (startIndex, index - startIndex);
						break;
					}
				}

				if (token == null) {
					if (ParseUtils.SkipCommentsAndWhiteSpace (rawValue, ref index, rawValue.Length, false)) {
						while (index < rawValue.Length && !rawValue[index].IsWhitespace ())
							index++;
					}

					token = new ReceivedTokenValue (startIndex, index - startIndex);
				}

				tokens.Add (token);

				ParseUtils.SkipWhiteSpace (rawValue, ref index, rawValue.Length);

				if (date && index < rawValue.Length) {
					// slurp up the date (the final token)
					tokens.Add (new ReceivedTokenValue (index, rawValue.Length - index));
					break;
				}
			}

			foreach (var token in tokens) {
				var text = charset.GetString (rawValue, token.StartIndex, token.Length).TrimEnd ();

				if (count > 0 && lineLength + text.Length + 1 > format.MaxLineLength) {
					encoded.Append (format.NewLine);
					encoded.Append ('\t');
					lineLength = 1;
					count = 0;
				} else {
					encoded.Append (' ');
					lineLength++;
				}

				lineLength += text.Length;
				encoded.Append (text);
				count++;
			}

			encoded.Append (format.NewLine);

			return charset.GetBytes (encoded.ToString ());
		}
コード例 #19
0
ファイル: Header.cs プロジェクト: naeemkhedarun/MimeKit
		static byte[] EncodeMessageIdHeader (ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
		{
			return charset.GetBytes (" " + value + format.NewLine);
		}
コード例 #20
0
ファイル: Header.cs プロジェクト: tfreitasleal/MimeKit
        static byte[] EncodeReceivedHeader(ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
        {
            var  tokens     = new List <ReceivedTokenValue> ();
            var  rawValue   = charset.GetBytes(value);
            var  encoded    = new StringBuilder();
            int  lineLength = field.Length + 1;
            bool date       = false;
            int  index      = 0;
            int  count      = 0;

            while (index < rawValue.Length)
            {
                ReceivedTokenValue token = null;
                int startIndex           = index;

                if (!ParseUtils.SkipCommentsAndWhiteSpace(rawValue, ref index, rawValue.Length, false) || index >= rawValue.Length)
                {
                    tokens.Add(new ReceivedTokenValue(startIndex, index - startIndex));
                    break;
                }

                while (index < rawValue.Length && !rawValue[index].IsWhitespace())
                {
                    index++;
                }

                var atom = charset.GetString(rawValue, startIndex, index - startIndex);

                for (int i = 0; i < ReceivedTokens.Length; i++)
                {
                    if (atom == ReceivedTokens[i].Atom)
                    {
                        ReceivedTokens[i].Skip(rawValue, ref index);

                        if (ParseUtils.SkipCommentsAndWhiteSpace(rawValue, ref index, rawValue.Length, false))
                        {
                            if (index < rawValue.Length && rawValue[index] == (byte)';')
                            {
                                date = true;
                                index++;
                            }
                        }

                        token = new ReceivedTokenValue(startIndex, index - startIndex);
                        break;
                    }
                }

                if (token == null)
                {
                    if (ParseUtils.SkipCommentsAndWhiteSpace(rawValue, ref index, rawValue.Length, false))
                    {
                        while (index < rawValue.Length && !rawValue[index].IsWhitespace())
                        {
                            index++;
                        }
                    }

                    token = new ReceivedTokenValue(startIndex, index - startIndex);
                }

                tokens.Add(token);

                ParseUtils.SkipWhiteSpace(rawValue, ref index, rawValue.Length);

                if (date && index < rawValue.Length)
                {
                    // slurp up the date (the final token)
                    tokens.Add(new ReceivedTokenValue(index, rawValue.Length - index));
                    break;
                }
            }

            foreach (var token in tokens)
            {
                var text = charset.GetString(rawValue, token.StartIndex, token.Length).TrimEnd();

                if (count > 0 && lineLength + text.Length + 1 > format.MaxLineLength)
                {
                    encoded.Append(format.NewLine);
                    encoded.Append('\t');
                    lineLength = 1;
                    count      = 0;
                }
                else
                {
                    encoded.Append(' ');
                    lineLength++;
                }

                lineLength += text.Length;
                encoded.Append(text);
                count++;
            }

            encoded.Append(format.NewLine);

            return(charset.GetBytes(encoded.ToString()));
        }
コード例 #21
0
ファイル: Header.cs プロジェクト: tfreitasleal/MimeKit
 static byte[] EncodeMessageIdHeader(ParserOptions options, FormatOptions format, Encoding charset, string field, string value)
 {
     return(charset.GetBytes(" " + value + format.NewLine));
 }