From 9ee2b35eaa585d85e587a092f85d598d8765c826 Mon Sep 17 00:00:00 2001 From: Leander Beernaert Date: Thu, 16 Feb 2023 10:31:56 +0100 Subject: [PATCH] fix(GODT-2021): Indefinite parser stall after new line Can't consume new line or we will be stuck waiting on more data which does not arrive until the client has received the response. --- imap/command/parser.go | 10 ++++++-- imap/command/parser_test.go | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/imap/command/parser.go b/imap/command/parser.go index 3d1a424f..a602aa07 100644 --- a/imap/command/parser.go +++ b/imap/command/parser.go @@ -115,8 +115,14 @@ func (p *Parser) Parse() (Command, error) { result.Payload = payload - if err := p.parser.ConsumeNewLine(); err != nil { - return result, err + if err := p.parser.Consume(rfcparser.TokenTypeCR, "expected CR"); err != nil { + return Command{}, err + } + + // Can't fully consume the last new line here or we will hang forever as the clients don't send the next token. + // In the next loop, the call to advance will ensure the next token in the stream gets loaded properly. + if !p.parser.Check(rfcparser.TokenTypeLF) { + return Command{}, p.parser.MakeError("expected LF after CR") } return result, nil diff --git a/imap/command/parser_test.go b/imap/command/parser_test.go index 9c97e270..48afc755 100644 --- a/imap/command/parser_test.go +++ b/imap/command/parser_test.go @@ -120,3 +120,54 @@ func TestParser_LiteralWithContinuationSubmission(t *testing.T) { require.NoError(t, err) require.Equal(t, expected, cmd) } + +func TestParser_TwoCommandsInSuccession(t *testing.T) { + // Run one go routine that submits bytes until the continuation call has been received + continueCh := make(chan struct{}) + reader, writer := io.Pipe() + + go func() { + defer writer.Close() + + firstLine := toIMAPLine(`A003 CAPABILITY`) + + secondLine := toIMAPLine(`B002 LIST "" %`) + + if l, err := writer.Write(firstLine); err != nil || l != len(firstLine) { + writer.CloseWithError(fmt.Errorf("failed to write first line: %w", err)) + return + } + + <-continueCh + + if l, err := writer.Write(secondLine); err != nil || l != len(secondLine) { + writer.CloseWithError(fmt.Errorf("failed to write second line: %w", err)) + return + } + }() + + s := rfcparser.NewScanner(reader) + p := NewParser(s) + + // First command + { + expected := Command{Tag: "A003", Payload: &Capability{}} + + cmd, err := p.Parse() + require.NoError(t, err) + require.Equal(t, expected, cmd) + } + + // Submit next command. + close(continueCh) + { + expected := Command{Tag: "B002", Payload: &List{ + Mailbox: "", + ListMailbox: "%", + }} + + cmd, err := p.Parse() + require.NoError(t, err) + require.Equal(t, expected, cmd) + } +}