Ejemplo n.º 1
0
        internal MimeMessage(ParserOptions options, IEnumerable <Header> headers)
        {
            addresses = new Dictionary <string, InternetAddressList> (icase);
            Headers   = new HeaderList(options);

            // initialize our address lists
            foreach (var name in StandardAddressHeaders)
            {
                var list = new InternetAddressList();
                list.Changed += InternetAddressListChanged;
                addresses.Add(name, list);
            }

            references          = new MessageIdList();
            references.Changed += ReferencesChanged;
            inreplyto           = null;

            Headers.Changed += HeadersChanged;

            // add all of our message headers...
            foreach (var header in headers)
            {
                if (header.Field.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                Headers.Add(header);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.MimeEntity"/> class.
        /// </summary>
        /// <param name="entity">Information used by the constructor.</param>
        /// <remarks>
        /// Custom <see cref="MimeEntity"/> subclasses MUST implement this constructor
        /// in order to register it using <see cref="MimeEntity.Register"/>.
        /// </remarks>
        protected MimeEntity(MimeEntityConstructorInfo entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            Headers     = new HeaderList(entity.ParserOptions);
            ContentType = entity.ContentType;

            ContentType.Changed += ContentTypeChanged;
            Headers.Changed     += HeadersChanged;

            IsInitializing = true;
            foreach (var header in entity.Headers)
            {
                if (entity.IsTopLevel && !header.Field.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                Headers.Add(header);
            }
            IsInitializing = false;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.MimeEntity"/> class.
        /// </summary>
        /// <param name="mediaType">The media type.</param>
        /// <param name="mediaSubtype">The media subtype.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="mediaType"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="mediaSubtype"/> is <c>null</c>.</para>
        /// </exception>
        protected MimeEntity(string mediaType, string mediaSubtype)
        {
            ContentType = new ContentType(mediaType, mediaSubtype);
            Headers     = new HeaderList();

            ContentType.Changed += ContentTypeChanged;
            Headers.Changed     += HeadersChanged;

            SerializeContentType();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.MimeEntity"/> class.
        /// </summary>
        /// <remarks>
        /// Initializes the <see cref="ContentType"/> to the one provided.
        /// </remarks>
        /// <param name="contentType">The content type.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="contentType"/> is <c>null</c>.
        /// </exception>
        protected MimeEntity(ContentType contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            Headers     = new HeaderList();
            ContentType = contentType;

            ContentType.Changed += ContentTypeChanged;
            Headers.Changed     += HeadersChanged;

            SerializeContentType();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Asynchronously parses a list of headers from the stream.
        /// </summary>
        /// <remarks>
        /// Parses a list of headers from the stream.
        /// </remarks>
        /// <returns>The parsed list of headers.</returns>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.FormatException">
        /// There was an error parsing the headers.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public async Task <HeaderList> ParseHeadersAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            state = MimeParserState.Headers;
            if (await StepAsync(cancellationToken).ConfigureAwait(false) == MimeParserState.Error)
            {
                throw new FormatException("Failed to parse headers.");
            }

            state = eos ? MimeParserState.Eos : MimeParserState.Complete;

            var parsed = new HeaderList(options);

            foreach (var header in headers)
            {
                parsed.Add(header);
            }

            return(parsed);
        }
Ejemplo n.º 6
0
        internal MimeMessage(ParserOptions options)
        {
            addresses = new Dictionary <string, InternetAddressList> (icase);
            Headers   = new HeaderList(options);

            // initialize our address lists
            foreach (var name in StandardAddressHeaders)
            {
                var list = new InternetAddressList();
                list.Changed += InternetAddressListChanged;
                addresses.Add(name, list);
            }

            references          = new MessageIdList();
            references.Changed += ReferencesChanged;
            inreplyto           = null;

            Headers.Changed += HeadersChanged;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.MimeEntity"/> class
        /// based on the <see cref="MimeEntityConstructorArgs"/>.
        /// </summary>
        /// <remarks>
        /// Custom <see cref="MimeEntity"/> subclasses MUST implement this constructor
        /// in order to register it using <see cref="ParserOptions.RegisterMimeType"/>.
        /// </remarks>
        /// <param name="args">Information used by the constructor.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="args"/> is <c>null</c>.
        /// </exception>
        protected MimeEntity(MimeEntityConstructorArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            Headers     = new HeaderList(args.ParserOptions);
            ContentType = args.ContentType;

            ContentType.Changed += ContentTypeChanged;
            Headers.Changed     += HeadersChanged;

            foreach (var header in args.Headers)
            {
                if (args.IsTopLevel && !header.Field.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                Headers.Add(header);
            }
        }
Ejemplo n.º 8
0
        public ReadForm(MainForm main, Folder folder, string id)
        {
            InitializeComponent();
            Main      = main;
            email_ref = main.emails.Find(em => em.id == main.curr_id);
            this.id   = id;
            try
            {
                switch (folder)
                {
                case Folder.inbox:
                    Main.curr_client.Inbox.Open(MailKit.FolderAccess.ReadOnly);
                    message = Main.curr_client.Inbox.First(msg => msg.MessageId == id);
                    break;

                case Folder.sent:
                    Main.curr_client.GetFolder(MailKit.SpecialFolder.Sent).Open(MailKit.FolderAccess.ReadOnly);
                    message = Main.curr_client.GetFolder(MailKit.SpecialFolder.Sent).First(msg => msg.MessageId == id);
                    break;

                case Folder.junk:
                    Main.curr_client.GetFolder(MailKit.SpecialFolder.Junk).Open(MailKit.FolderAccess.ReadOnly);
                    message = Main.curr_client.GetFolder(MailKit.SpecialFolder.Junk).First(msg => msg.MessageId == id);
                    break;

                case Folder.trash:
                    Main.curr_client.GetFolder(MailKit.SpecialFolder.Trash).Open(MailKit.FolderAccess.ReadOnly);
                    message = Main.curr_client.GetFolder(MailKit.SpecialFolder.Trash).First(msg => msg.MessageId == id);
                    break;

                default:
                    break;
                }
            }
            catch (Exception)
            {
                message = MimeMessage.Load("Saved/" + email_ref.Address + "/" + folder.ToString() + "/" + id);
            }
            tb_opentext.Text = message.TextBody;
            tb_subject.Text  = message.Subject;
            tb_from.Text     = message.From.Mailboxes.First().Address;
            b_attach.Enabled = message.Attachments.Count() > 0;
            MimeKit.HeaderList headers = new MimeKit.HeaderList();
            if (message.Headers.Contains("keyswap"))
            {
                if (message.Headers["keyswap"] == "0")//Пришёл запрос
                {
                    if (MessageBox.Show("Произвести обмен ключами шифрования?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        Main.KeyHolders.AddReciever(email_ref.Address, message.From.Mailboxes.First().Address);
                        Main.KeyHolders.SetKey(email_ref.Address, message.From.Mailboxes.First().Address, message.Headers["keypub"], false);
                        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                        {
                            MailMessage replyMail = new MailMessage(new MailAddress(email_ref.Address, email_ref.Name), new MailAddress(message.From.Mailboxes.First().Address))
                            {
                                Subject = "ОТВЕТ НА ЗАПРОС ОБМЕНА КЛЮЧАМИ"
                            };
                            replyMail.Headers.Add("keyswap", "1");
                            replyMail.Headers.Add("keypub", rsa.ToXmlString(false));
                            SmtpClient smtp = new SmtpClient
                            {
                                Port                  = Main.snd_port,
                                Host                  = "smtp." + Main.host,
                                EnableSsl             = true,
                                Timeout               = 10000,
                                DeliveryMethod        = SmtpDeliveryMethod.Network,
                                UseDefaultCredentials = false,
                                Credentials           = new System.Net.NetworkCredential(email_ref.Address, email_ref.Password)
                            };
                            try
                            {
                                smtp.Send(replyMail);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Не удалось отправить запрос\n" + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                throw;
                            }
                            Main.KeyHolders.AddReciever(email_ref.Address, message.From.Mailboxes.First().Address);
                            Main.KeyHolders.SetKey(email_ref.Address, message.From.Mailboxes.First().Address, rsa.ToXmlString(true), true);
                            Main.SerializeKeyFile();
                        }
                    }
                }
                else //Пришёл ответ
                {
                    Main.KeyHolders.SetKey(email_ref.Address, message.From.Mailboxes.First().Address, message.Headers["keypub"], false);
                    Main.SerializeKeyFile();
                    MessageBox.Show("Запрос подверждён. Теперь можно шифровать письма с данным пользователем", "Запрс подтверждён", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                Close();
            }
            else
            {
                if (message.Headers.Contains("crypt")) //Есть флаги-признаки шифрования => отправлено с этого клиента
                {
                    byte   cryptF = byte.Parse(message.Headers["crypt"]);
                    string str    = (cryptF & 2) != 0 ? message.TextBody.Substring(0, message.TextBody.IndexOf("\r")) : message.TextBody;
                    if ((cryptF & 1) != 0)//Флаг подписи
                    {
                        byte[] sign   = Convert.FromBase64String(message.Headers["dsasign"]);
                        string dsaKey = message.Headers["dsakey"];
                        if (Encryption.VerifySign(Encoding.Default.GetBytes(str), dsaKey, sign))
                        {
                            MessageBox.Show("Цифровая подпись прошла верификацию", "DSAGuardian", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show("Цифровая подпись не прошла верификацию. Данные могли быть повреждены", "DSAGuardian", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    if ((cryptF & 2) != 0)//Флаг шифрования
                    {
                        byte[] buff = Convert.FromBase64String(message.Headers["deskey"]);
                        byte[] Key;
                        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                        {
                            rsa.FromXmlString(Main.KeyHolders.GetKey(email_ref.Address, message.From.Mailboxes.First().Address, true));
                            Key = Encryption.DecRSA(buff, rsa.ExportParameters(true), true);
                        }
                        byte[] IV = Convert.FromBase64String(message.Headers["desiv"]);
                        tb_opentext.Text = Encryption.DecDES(Convert.FromBase64String(str), Key, IV);
                    }
                }
            }
        }