protected override Response HandleCommand(Command cmd)
        {
            ImapCommand command = cmd as ImapCommand;

            ImapResponse response = null;

            Console.WriteLine(cmd.Raw);

            switch (command.Code)
            {
                case "CAPABILITY":
                    response = new ImapResponse { Code = "OK", Tag = command.Tag, Text = "CAPABILITY completed" };
                    response.AddResponseLine(new ImapResponse { Code = "CAPABILITY", Text = "IMAP4rev1 AUTH=PLAIN" });
                    break;
                case "LOGIN":
                    _currentUser = cmd.Arguments[0];
                    response = new ImapResponse { Code = "OK", Tag = command.Tag, Text = "LOGIN completed" };
                    break;
                case "NOOP":
                case "LOGOUT":
                default:
                    response = new ImapResponse { Code = "BAD", Tag = command.Tag };
                    break;
            }

            Console.WriteLine(response);

            return response;
        }
Example #2
0
        /// <summary>
        ///   The APPEND command appends the literal argument as a new message
        ///   to the end of the specified destination mailbox.
        ///   http://tools.ietf.org/html/rfc3501#section-6.3.11
        /// </summary>
        /// <param name = "mailboxName">The name of the malbox to insert the message.</param>
        /// <param name = "message">The message to append.</param>
        /// <param name = "flags">Sets the flags of the message. This is optional.</param>
        public ImapResponse Append(string mailboxName, Message message, MessageFlags flags = (MessageFlags)0x0000)
        {
            // we need to convert non ASCII names according to IMAP specs.
            // http://tools.ietf.org/html/rfc2060#section-5.1.3
            var name = MailboxNameEncoder.Encode(mailboxName);

            var mime       = message.ToMime();
            var size       = mime.Length;
            var flagString = flags == 0x0000 ? string.Empty : string.Format(" ({0})", flags.ToMimeFormat());
            var text       = string.Format("APPEND {0}{1} {{{2}}}", name, flagString, size);
            var reader     = SendAndReceive(new ImapCommand(text));

            if (reader.IsContinuation)
            {
                var finalReader = SendAndReceive(new BlankImapCommand(mime));

                var validResponse = new ImapResponse();
                validResponse.Parse(finalReader);
                return(validResponse);
            }

            var invalidResponse = new ImapResponse();

            invalidResponse.Parse(reader);
            return(invalidResponse);
        }
Example #3
0
        /// <summary>
        ///   The STORE command alters data associated with a message in the mailbox.
        ///   http://tools.ietf.org/html/rfc2060#section-6.4.6
        /// </summary>
        /// <param name = "set">The sequence set representing the targeted messages, e.g. "1"; "1,2"; "2:4".</param>
        /// <param name = "value">The keywords to add or remove.</param>
        /// <param name = "procedure">The procedure, whether to add or remove the flags.</param>
        public ImapResponse StoreSilent(SequenceSet set, string value, StoreProcedures procedure)
        {
            var reader   = StoreInternal(set, value, procedure, "FLAGS.SILENT");
            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #4
0
        /// <summary>
        ///   The NOOP command always succeeds.  It does nothing.
        ///   http://tools.ietf.org/html/rfc3501#section-6.1.2
        /// </summary>
        public ImapResponse Noop()
        {
            var command = new ImapCommand("NOOP");
            var reader  = SendAndReceive(command);

            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #5
0
        /// <summary>
        ///   The LOGOUT command informs the server that the client is done with the connection.
        ///   http://tools.ietf.org/html/rfc3501#section-6.1.3
        /// </summary>
        public ImapResponse Logout()
        {
            var command = new ImapCommand("LOGOUT");
            var reader  = SendAndReceive(command);

            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #6
0
 public static async Task SendResponse(ImapSession session, ImapResponse response)
 {
     if (response.Line == null)
     {
         await session.Stream.WriteAsync(response.Binary);
     }
     else
     {
         await session.Stream.WriteLineAsync(response.Line);
     }
 }
Example #7
0
        /// <summary>
        ///   The CHECK command requests a checkpoint of the currently selected
        ///   mailbox.  A checkpoint refers to any implementation-dependent
        ///   housekeeping associated with the mailbox (e.g., resolving the
        ///   server's in-memory state of the mailbox with the state on its
        ///   disk) that is not normally executed as part of each command.  A
        ///   checkpoint MAY take a non-instantaneous amount of real time to
        ///   complete.  If a server implementation has no such housekeeping
        ///   considerations, CHECK is equivalent to NOOP.
        ///   http://tools.ietf.org/html/rfc2060#section-6.4.1
        /// </summary>
        public ImapResponse Check()
        {
            var text    = string.Format("CHECK");
            var command = new ImapCommand(text);
            var reader  = SendAndReceive(command);

            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #8
0
        /// <summary>
        ///   The COPY command copies the specified message(s) to the end of the specified destination mailbox.
        ///   http://tools.ietf.org/html/rfc3501#section-6.4.7
        /// </summary>
        public ImapResponse Copy(SequenceSet set, string destinationMailboxName)
        {
            // we need to convert non ASCII names according to IMAP specs.
            // http://tools.ietf.org/html/rfc2060#section-5.1.3
            var name = MailboxNameEncoder.Encode(destinationMailboxName);

            var text    = string.Format("COPY {0} \"{1}\"", set, name);
            var command = new ImapCommand(text);
            var reader  = SendAndReceive(command);

            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #9
0
        /// <summary>
        ///   The CREATE command creates a mailbox with the given name.
        ///   http://tools.ietf.org/html/rfc3501#section-6.3.3
        /// </summary>
        /// <param name = "mailboxName">The name of the mailbox to create.</param>
        public ImapResponse Create(string mailboxName)
        {
            // we need to convert non ASCII names according to IMAP specs.
            // http://tools.ietf.org/html/rfc2060#section-5.1.3
            var name = MailboxNameEncoder.Encode(mailboxName);

            var text    = string.Format("CREATE \"{0}\"", name);
            var command = new ImapCommand(text);
            var reader  = SendAndReceive(command);

            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #10
0
        /// <summary>
        ///   The RENAME command changes the name of a mailbox.  A tagged OK
        ///   response is returned only if the mailbox has been renamed.  It is
        ///   an error to attempt to rename from a mailbox name that does not
        ///   exist or to a mailbox name that already exists.  Any error in
        ///   renaming will return a tagged NO response.
        /// </summary>
        /// <param name = "sourceName">The fullname of the mailbox to rename.</param>
        /// <param name = "targetName">The new name for the mailbox.</param>
        /// <returns>Returns the server response.</returns>
        public ImapResponse Rename(string sourceName, string targetName)
        {
            // we need to convert non ASCII names according to IMAP specs.
            // http://tools.ietf.org/html/rfc2060#section-5.1.3
            var source = MailboxNameEncoder.Encode(sourceName);

            // we need to convert non ASCII names according to IMAP specs.
            // http://tools.ietf.org/html/rfc2060#section-5.1.3
            var target = MailboxNameEncoder.Encode(targetName);

            var text    = string.Format("RENAME \"{0}\" \"{1}\"", source, target);
            var command = new ImapCommand(text);
            var reader  = SendAndReceive(command);

            var response = new ImapResponse();

            response.Parse(reader);
            return(response);
        }
Example #11
0
        protected override Response HandleCommand(Command cmd)
        {
            ImapCommand command = cmd as ImapCommand;

            ImapResponse response = null;

            Console.WriteLine(cmd.Raw);

            switch (command.Code)
            {
            case "CAPABILITY":
                response = new ImapResponse {
                    Code = "OK", Tag = command.Tag, Text = "CAPABILITY completed"
                };
                response.AddResponseLine(new ImapResponse {
                    Code = "CAPABILITY", Text = "IMAP4rev1 AUTH=PLAIN"
                });
                break;

            case "LOGIN":
                _currentUser = cmd.Arguments[0];
                response     = new ImapResponse {
                    Code = "OK", Tag = command.Tag, Text = "LOGIN completed"
                };
                break;

            case "NOOP":
            case "LOGOUT":
            default:
                response = new ImapResponse {
                    Code = "BAD", Tag = command.Tag
                };
                break;
            }

            Console.WriteLine(response);

            return(response);
        }
Example #12
0
        // Token: 0x06000151 RID: 337 RVA: 0x000080A8 File Offset: 0x000062A8
        private void LogFailureDetails(string command, ImapResponse response)
        {
            this.Log.Error("Error while executing [{0}]", new object[]
            {
                command
            });
            IList <string> responseLines = response.ResponseLines;

            if (responseLines == null || responseLines.Count <= 0)
            {
                return;
            }
            int num = Math.Max(0, responseLines.Count - 10);

            for (int i = num; i < responseLines.Count; i++)
            {
                this.Log.Error("Response line [{0}]: {1}", new object[]
                {
                    i,
                    responseLines[i]
                });
            }
        }
Example #13
0
 public void AddResponseLine(ImapResponse response)
 {
     _responses.Add(response);
 }
 public void AddResponseLine(ImapResponse response)
 {
     _responses.Add(response);
 }
Example #15
0
 // Token: 0x06000150 RID: 336 RVA: 0x00008096 File Offset: 0x00006296
 private void LogFailureDetails(ImapCommand command, ImapResponse response)
 {
     this.LogFailureDetails(command.ToPiiCleanString(), response);
 }
Example #16
0
 // Token: 0x0600014A RID: 330 RVA: 0x00007AA4 File Offset: 0x00005CA4
 private void OnReadMoreResponse(IAsyncResult asyncResult)
 {
     lock (this.syncRoot)
     {
         if (this.ShouldCancelCallback())
         {
             NetworkConnection networkConnection = this.ExtractNetworkConnectionFrom(asyncResult);
             byte[]            data;
             int    offset;
             int    num;
             object obj2;
             networkConnection.EndRead(asyncResult, out data, out offset, out num, out obj2);
         }
         else
         {
             base.CheckDisposed();
             AsyncResult <ImapConnectionContext, ImapResultData> asyncResult2 = (AsyncResult <ImapConnectionContext, ImapResultData>)asyncResult.AsyncState;
             ImapResponse imapResponse = this.currentResponse;
             byte[]       data;
             int          offset;
             int          num;
             object       obj2;
             this.networkConnection.EndRead(asyncResult, out data, out offset, out num, out obj2);
             if (obj2 != null)
             {
                 ImapNetworkFacade.HandleError(obj2, asyncResult2);
             }
             else if (this.cancellationRequested)
             {
                 this.HandleCancellation(asyncResult2);
             }
             else
             {
                 ExTraceGlobals.FaultInjectionTracer.TraceTest(2674273597U);
                 this.totalBytesReceived += (long)num;
                 DownloadCompleteEventArgs eventArgs = new DownloadCompleteEventArgs((long)num, 0L);
                 asyncResult2.State.ActivatePerfDownloadEvent(asyncResult2.State, eventArgs);
                 if (this.totalBytesReceived > this.connectionParameters.MaxBytesToTransfer)
                 {
                     ImapNetworkFacade.HandleError(ImapNetworkFacade.MaxBytesReceivedExceeded(), asyncResult2);
                 }
                 else
                 {
                     int num2 = imapResponse.AddData(data, offset, num);
                     int num3 = num - num2;
                     this.Log.Assert(num3 >= 0, "The unconsumed bytes must be non-negative.", new object[0]);
                     if (num3 > 0)
                     {
                         this.networkConnection.PutBackReceivedBytes(num3);
                     }
                     if (imapResponse.IsComplete)
                     {
                         ImapNetworkFacade.CountCommand(asyncResult2, true);
                         asyncResult2.State.Log.Debug("Command complete: [{0}].  Status = {1}", new object[]
                         {
                             this.currentCommand.ToPiiCleanString(),
                             imapResponse.Status
                         });
                         this.currentResultData.Status = imapResponse.Status;
                         if (asyncResult.CompletedSynchronously)
                         {
                             asyncResult2.SetCompletedSynchronously();
                         }
                         if (imapResponse.Status == ImapStatus.No || imapResponse.Status == ImapStatus.Bad || imapResponse.Status == ImapStatus.Bye)
                         {
                             this.LogFailureDetails(this.currentCommand, imapResponse);
                             asyncResult2.ProcessCompleted(this.currentResultData);
                         }
                         else if (imapResponse.Status != ImapStatus.Ok)
                         {
                             this.LogFailureDetails(this.currentCommand, imapResponse);
                             asyncResult2.ProcessCompleted(this.BuildAndLogUnknownCommandFailureException(asyncResult2.State));
                         }
                         else
                         {
                             if (!imapResponse.TryParseIntoResult(this.currentCommand, ref this.currentResultData))
                             {
                                 if (this.currentResultData.FailureException == null)
                                 {
                                     if (this.currentResultData.MessageStream != null)
                                     {
                                         this.totalMessagesReceived += 1UL;
                                     }
                                     asyncResult2.ProcessCompleted(this.currentResultData, this.BuildAndLogUnknownParseFailureException(asyncResult2.State));
                                     return;
                                 }
                                 ImapUtilities.LogExceptionDetails(asyncResult2.State.Log, this.currentCommand, this.currentResultData.FailureException);
                                 this.LogFailureDetails(this.currentCommand, this.currentResponse);
                             }
                             else
                             {
                                 asyncResult2.State.Log.Debug("Parsed server response succesfully.", new object[0]);
                             }
                             asyncResult2.ProcessCompleted(this.currentResultData);
                         }
                     }
                     else if (imapResponse.IsWaitingForLiteral)
                     {
                         Exception ex = null;
                         Stream    commandParameterStream = this.currentCommand.GetCommandParameterStream(this.serverParameters.Server, imapResponse.GetLastResponseLine(), out ex);
                         if (ex != null)
                         {
                             if (commandParameterStream != null)
                             {
                                 commandParameterStream.Close();
                             }
                             ImapNetworkFacade.CountCommand(asyncResult2, false);
                             asyncResult2.ProcessCompleted(ex);
                         }
                         else if (commandParameterStream == null)
                         {
                             ImapNetworkFacade.CountCommand(asyncResult2, false);
                             asyncResult2.ProcessCompleted(this.BuildAndLogUnexpectedLiteralRequestException(asyncResult2.State));
                         }
                         else
                         {
                             this.totalBytesSent += commandParameterStream.Length;
                             if (this.totalBytesSent > this.connectionParameters.MaxBytesToTransfer)
                             {
                                 ImapNetworkFacade.HandleError(ImapNetworkFacade.MaxBytesSentExceeded(), asyncResult2);
                             }
                             else
                             {
                                 eventArgs = new DownloadCompleteEventArgs(0L, commandParameterStream.Length);
                                 asyncResult2.State.ActivatePerfDownloadEvent(asyncResult2.State, eventArgs);
                                 asyncResult2.State.Log.Debug("Begin writing literal stream.", new object[0]);
                                 asyncResult2.PendingAsyncResult = this.networkConnection.BeginWrite(commandParameterStream, new AsyncCallback(this.OnEndWriteLiteral), asyncResult2);
                             }
                         }
                     }
                     else if (imapResponse.TotalLiteralBytesExpected > 0 && this.totalBytesReceived + (long)imapResponse.LiteralBytesRemaining > this.connectionParameters.MaxBytesToTransfer)
                     {
                         this.totalBytesReceived += (long)imapResponse.LiteralBytesRemaining;
                         ImapNetworkFacade.HandleError(ImapNetworkFacade.MaxBytesReceivedExceeded(), asyncResult2);
                     }
                     else
                     {
                         asyncResult2.PendingAsyncResult = this.BeginNetworkRead(asyncResult2, new AsyncCallback(this.OnReadMoreResponse));
                     }
                 }
             }
         }
     }
 }
Example #17
0
 // Token: 0x06000147 RID: 327 RVA: 0x000075E4 File Offset: 0x000057E4
 private void OnReadAndDiscardLine(IAsyncResult asyncResult)
 {
     lock (this.syncRoot)
     {
         if (this.ShouldCancelCallback())
         {
             NetworkConnection networkConnection = this.ExtractNetworkConnectionFrom(asyncResult);
             byte[]            data;
             int    offset;
             int    num;
             object obj2;
             networkConnection.EndRead(asyncResult, out data, out offset, out num, out obj2);
         }
         else
         {
             base.CheckDisposed();
             AsyncResult <ImapConnectionContext, ImapResultData> asyncResult2 = (AsyncResult <ImapConnectionContext, ImapResultData>)asyncResult.AsyncState;
             ImapResponse imapResponse = this.currentResponse;
             byte[]       data;
             int          offset;
             int          num;
             object       obj2;
             this.networkConnection.EndRead(asyncResult, out data, out offset, out num, out obj2);
             if (obj2 != null)
             {
                 ImapNetworkFacade.HandleError(obj2, asyncResult2);
             }
             else if (this.cancellationRequested)
             {
                 this.HandleCancellation(asyncResult2);
             }
             else
             {
                 ExTraceGlobals.FaultInjectionTracer.TraceTest(4284886333U);
                 this.totalBytesReceived += (long)num;
                 DownloadCompleteEventArgs eventArgs = new DownloadCompleteEventArgs((long)num, 0L);
                 asyncResult2.State.ActivatePerfDownloadEvent(asyncResult2.State, eventArgs);
                 if (this.totalBytesReceived > this.connectionParameters.MaxBytesToTransfer)
                 {
                     ImapNetworkFacade.HandleError(ImapNetworkFacade.MaxBytesReceivedExceeded(), asyncResult2);
                 }
                 else
                 {
                     int num2 = imapResponse.AddData(data, offset, num);
                     int num3 = num - num2;
                     this.Log.Assert(num3 >= 0, "The unconsumed bytes must be non-negative.", new object[0]);
                     if (num3 > 0)
                     {
                         this.networkConnection.PutBackReceivedBytes(num3);
                     }
                     if (imapResponse.IsComplete)
                     {
                         this.currentResultData.Clear();
                         this.currentResultData.Status = imapResponse.Status;
                         if (asyncResult.CompletedSynchronously)
                         {
                             asyncResult2.SetCompletedSynchronously();
                         }
                         asyncResult2.State.Log.Assert(this.currentCommand == null, "this.currentCommand is expected to be null", new object[0]);
                         if (imapResponse.Status == ImapStatus.No || imapResponse.Status == ImapStatus.Bad || imapResponse.Status == ImapStatus.Bye)
                         {
                             this.LogFailureDetails("Connecting", imapResponse);
                             asyncResult2.ProcessCompleted(this.currentResultData);
                         }
                         else
                         {
                             asyncResult2.State.Log.Assert(imapResponse.ResponseLines != null && imapResponse.ResponseLines.Count > 0, "ResponseLines was null or had no content", new object[0]);
                             if (imapResponse.Status != ImapStatus.Ok)
                             {
                                 asyncResult2.ProcessCompleted(this.BuildAndLogUnknownCommandFailureException(asyncResult2.State, "Connecting"));
                             }
                             else
                             {
                                 asyncResult2.ProcessCompleted(this.currentResultData);
                             }
                         }
                     }
                     else
                     {
                         asyncResult2.PendingAsyncResult = this.BeginNetworkRead(asyncResult2, new AsyncCallback(this.OnReadAndDiscardLine));
                     }
                 }
             }
         }
     }
 }