14 char = charRange('\x01', '\x7f')
15 ctl = charRange('\x01', '\x19')
18 atomChar = charRemove(char, "(){ "+ctl+listWildcards+quotedSpecials+respSpecials)
19 astringChar = atomChar + respSpecials
22func charRange(first, last rune) string {
33func charRemove(s, remove string) string {
37 for _, x := range remove {
48 // Orig is the line in original casing, and upper in upper casing. We often match
49 // against upper for easy case insensitive handling as IMAP requires, but sometimes
50 // return from orig to keep the original case.
53 o int // Current offset in parsing.
54 contexts []string // What we're parsing, for error messages.
58// toUpper upper cases bytes that are a-z. strings.ToUpper does too much. and
59// would replace invalid bytes with unicode replacement characters, which would
60// break our requirement that offsets into the original and upper case strings
61// point to the same character.
62func toUpper(s string) string {
65 if c >= 'a' && c <= 'z' {
72func newParser(s string, conn *conn) *parser {
73 return &parser{s, toUpper(s), 0, nil, conn}
76func (p *parser) xerrorf(format string, args ...any) {
78 errmsg := fmt.Sprintf(format, args...)
79 remaining := fmt.Sprintf("remaining %q", p.orig[p.o:])
80 if len(p.contexts) > 0 {
81 remaining += ", context " + strings.Join(p.contexts, ",")
83 remaining = " (" + remaining + ")"
84 if p.conn.account != nil {
86 err = errors.New(errmsg)
88 err = errors.New(errmsg + remaining)
90 panic(syntaxError{"", "", errmsg, err})
93func (p *parser) context(s string) func() {
94 p.contexts = append(p.contexts, s)
96 p.contexts = p.contexts[:len(p.contexts)-1]
100func (p *parser) empty() bool {
101 return p.o == len(p.upper)
104func (p *parser) xempty() {
106 p.xerrorf("leftover data")
110func (p *parser) hasPrefix(s string) bool {
111 return strings.HasPrefix(p.upper[p.o:], s)
114func (p *parser) take(s string) bool {
122func (p *parser) xtake(s string) {
124 p.xerrorf("expected %s", s)
128func (p *parser) xnonempty() {
130 p.xerrorf("unexpected end")
134func (p *parser) xtakeall() string {
140func (p *parser) xtake1n(n int, what string) string {
142 p.xerrorf("expected chars from %s", what)
147func (p *parser) xtakechars(s string, what string) string {
149 for i, c := range p.orig[p.o:] {
151 return p.xtake1n(i, what)
157func (p *parser) xtaken(n int) string {
158 if p.o+n > len(p.orig) {
159 p.xerrorf("not enough data")
161 r := p.orig[p.o : p.o+n]
166func (p *parser) space() bool {
170func (p *parser) xspace() {
172 p.xerrorf("expected space")
176func (p *parser) digits() string {
178 for _, c := range p.upper[p.o:] {
179 if c < '0' || c > '9' {
187 s := p.upper[p.o : p.o+n]
192func (p *parser) nznumber() (uint32, bool) {
194 for o < len(p.upper) && p.upper[o] >= '0' && p.upper[o] <= '9' {
200 if n, err := strconv.ParseUint(p.upper[p.o:o], 10, 32); err != nil {
206 return uint32(n), true
210func (p *parser) xnznumber() uint32 {
211 n, ok := p.nznumber()
213 p.xerrorf("expected non-zero number")
218func (p *parser) number() (uint32, bool) {
220 for o < len(p.upper) && p.upper[o] >= '0' && p.upper[o] <= '9' {
226 n, err := strconv.ParseUint(p.upper[p.o:o], 10, 32)
231 return uint32(n), true
234func (p *parser) xnumber() uint32 {
237 p.xerrorf("expected number")
242func (p *parser) xnumber64() int64 {
245 p.xerrorf("expected number64")
249 p.xerrorf("parsing number64 %q: %v", s, err)
254func (p *parser) xnznumber64() int64 {
257 p.xerrorf("expected non-zero number64")
262// l should be a list of uppercase words, the first match is returned
263func (p *parser) takelist(l ...string) (string, bool) {
264 for _, w := range l {
272func (p *parser) xtakelist(l ...string) string {
273 w, ok := p.takelist(l...)
275 p.xerrorf("expected one of %s", strings.Join(l, ","))
280func (p *parser) xstring() (r string) {
284 for i, c := range p.orig[p.o:] {
287 } else if c == '\x00' || c == '\r' || c == '\n' {
288 p.xerrorf("invalid nul, cr or lf in string")
290 if c == '\\' || c == '"' {
294 p.xerrorf("invalid escape char %c", c)
303 p.xerrorf("missing closing dquote in string")
305 size, sync := p.xliteralSize(100*1024, false)
306 s := p.conn.xreadliteral(size, sync)
307 line := p.conn.readline(false)
308 p.orig, p.upper, p.o = line, toUpper(line), 0
312func (p *parser) xnil() {
316// Returns NIL as empty string.
317func (p *parser) xnilString() string {
324func (p *parser) xastring() string {
325 if p.hasPrefix(`"`) || p.hasPrefix("{") || p.hasPrefix("~{") {
328 return p.xtakechars(astringChar, "astring")
331func contains(s string, c rune) bool {
332 for _, x := range s {
340func (p *parser) xtag() string {
342 for i, c := range p.orig[p.o:] {
343 if c == '+' || !contains(astringChar, c) {
344 return p.xtake1n(i, "tag")
350func (p *parser) xcommand() string {
351 for i, c := range p.upper[p.o:] {
352 if !(c >= 'A' && c <= 'Z' || c == ' ' && p.upper[p.o:p.o+i] == "UID") {
353 return p.xtake1n(i, "command")
359func (p *parser) remainder() string {
364func (p *parser) xflag() string {
365 w, _ := p.takelist(`\`, "$")
368 switch strings.ToLower(s) {
369 case `\answered`, `\flagged`, `\deleted`, `\seen`, `\draft`:
371 p.xerrorf("unknown system flag %s", s)
377func (p *parser) xflagList() (l []string) {
379 if !p.hasPrefix(")") {
380 l = append(l, p.xflag())
384 l = append(l, p.xflag())
389func (p *parser) xatom() string {
390 return p.xtakechars(atomChar, "atom")
393func (p *parser) xdecodeMailbox(s string) string {
394 // UTF-7 is deprecated for IMAP4rev2-only clients, and not used with UTF8=ACCEPT.
395 // The future should be without UTF-7, we don't encode/decode it with modern
396 // clients. Most clients are IMAP4rev1, we need to handle UTF-7.
399 if p.conn.utf8strings() {
402 ns, err := utf7decode(s)
404 p.xerrorf("decoding utf7 mailbox name: %v", err)
409func (p *parser) xmailbox() string {
411 return p.xdecodeMailbox(s)
415func (p *parser) xlistMailbox() string {
417 if p.hasPrefix(`"`) || p.hasPrefix("{") {
420 s = p.xtakechars(atomChar+listWildcards+respSpecials, "list-char")
422 // Presumably UTF-7 encoding applies to mailbox patterns too.
423 return p.xdecodeMailbox(s)
427func (p *parser) xmboxOrPat() ([]string, bool) {
429 return []string{p.xlistMailbox()}, false
431 l := []string{p.xlistMailbox()}
434 l = append(l, p.xlistMailbox())
440func (p *parser) xstatusAtt() string {
441 w := p.xtakelist("MESSAGES", "UIDNEXT", "UIDVALIDITY", "UNSEEN", "DELETED-STORAGE", "DELETED", "SIZE", "RECENT", "APPENDLIMIT", "HIGHESTMODSEQ")
442 if w == "HIGHESTMODSEQ" {
444 p.conn.enabled[capCondstore] = true
450func (p *parser) xnumSet0(allowStar, allowSearch bool) (r numSet) {
451 defer p.context("numSet")()
452 if allowSearch && p.take("$") {
453 return numSet{searchResult: true}
455 r.ranges = append(r.ranges, p.xnumRange0(allowStar))
457 r.ranges = append(r.ranges, p.xnumRange0(allowStar))
462func (p *parser) xnumSet() (r numSet) {
463 return p.xnumSet0(true, true)
466// parse numRange, which can be just a setNumber.
467func (p *parser) xnumRange0(allowStar bool) (r numRange) {
468 if allowStar && p.take("*") {
471 r.first.number = p.xnznumber()
474 r.last = &setNumber{}
475 if allowStar && p.take("*") {
478 r.last.number = p.xnznumber()
485func (p *parser) xsectionMsgtext() (r *sectionMsgtext) {
486 defer p.context("sectionMsgtext")()
487 msgtextWords := []string{"HEADER.FIELDS.NOT", "HEADER.FIELDS", "HEADER", "TEXT"}
488 w := p.xtakelist(msgtextWords...)
489 r = §ionMsgtext{s: w}
490 if strings.HasPrefix(w, "HEADER.FIELDS") {
493 r.headers = append(r.headers, textproto.CanonicalMIMEHeaderKey(p.xastring()))
499 r.headers = append(r.headers, textproto.CanonicalMIMEHeaderKey(p.xastring()))
506func (p *parser) xsectionSpec() (r *sectionSpec) {
507 defer p.context("parseSectionSpec")()
509 n, ok := p.nznumber()
511 return §ionSpec{msgtext: p.xsectionMsgtext()}
513 defer p.context("part...")()
515 pt.part = append(pt.part, n)
520 if n, ok := p.nznumber(); ok {
521 pt.part = append(pt.part, n)
525 pt.text = §ionText{mime: true}
528 pt.text = §ionText{msgtext: p.xsectionMsgtext()}
531 return §ionSpec{part: pt}
535func (p *parser) xsection() *sectionSpec {
536 defer p.context("parseSection")()
539 return §ionSpec{}
541 r := p.xsectionSpec()
547func (p *parser) xpartial() *partial {
549 offset := p.xnumber()
551 count := p.xnznumber()
553 return &partial{offset, count}
557func (p *parser) xsectionBinary() (r []uint32) {
562 r = append(r, p.xnznumber())
567 r = append(r, p.xnznumber())
573var fetchAttWords = []string{
574 "ENVELOPE", "FLAGS", "INTERNALDATE", "RFC822.SIZE", "BODYSTRUCTURE", "UID", "BODY.PEEK", "BODY", "BINARY.PEEK", "BINARY.SIZE", "BINARY",
575 "RFC822.HEADER", "RFC822.TEXT", "RFC822", // older IMAP
576 "MODSEQ", // CONDSTORE extension.
580func (p *parser) xfetchAtt(isUID bool) (r fetchAtt) {
581 defer p.context("fetchAtt")()
582 f := p.xtakelist(fetchAttWords...)
583 r.peek = strings.HasSuffix(f, ".PEEK")
584 r.field = strings.TrimSuffix(f, ".PEEK")
588 if p.hasPrefix("[") {
589 r.section = p.xsection()
590 if p.hasPrefix("<") {
591 r.partial = p.xpartial()
595 r.sectionBinary = p.xsectionBinary()
596 if p.hasPrefix("<") {
597 r.partial = p.xpartial()
600 r.sectionBinary = p.xsectionBinary()
602 // The RFC text mentions MODSEQ is only for FETCH, not UID FETCH, but the ABNF adds
603 // the attribute to the shared syntax, so UID FETCH also implements it.
607 p.conn.xensureCondstore(nil)
613func (p *parser) xfetchAtts(isUID bool) []fetchAtt {
614 defer p.context("fetchAtts")()
616 fields := func(l ...string) []fetchAtt {
617 r := make([]fetchAtt, len(l))
618 for i, s := range l {
619 r[i] = fetchAtt{field: s}
624 if w, ok := p.takelist("ALL", "FAST", "FULL"); ok {
627 return fields("FLAGS", "INTERNALDATE", "RFC822.SIZE", "ENVELOPE")
629 return fields("FLAGS", "INTERNALDATE", "RFC822.SIZE")
631 return fields("FLAGS", "INTERNALDATE", "RFC822.SIZE", "ENVELOPE", "BODY")
633 panic("missing case")
636 if !p.hasPrefix("(") {
637 return []fetchAtt{p.xfetchAtt(isUID)}
643 l = append(l, p.xfetchAtt(isUID))
652func xint(p *parser, s string) int {
653 v, err := strconv.ParseInt(s, 10, 32)
655 p.xerrorf("bad int %q: %v", s, err)
660func (p *parser) digit() (string, bool) {
665 if c < '0' || c > '9' {
668 s := p.orig[p.o : p.o+1]
673func (p *parser) xdigit() string {
676 p.xerrorf("expected digit")
682func (p *parser) xdateDayFixed() int {
684 return xint(p, p.xdigit())
686 return xint(p, p.xdigit()+p.xdigit())
689var months = []string{"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}
692func (p *parser) xdateMonth() time.Month {
693 s := strings.ToLower(p.xtaken(3))
694 for i, m := range months {
696 return time.Month(1 + i)
699 p.xerrorf("unknown month %q", s)
704func (p *parser) xtime() (int, int, int) {
705 h := xint(p, p.xtaken(2))
707 m := xint(p, p.xtaken(2))
709 s := xint(p, p.xtaken(2))
714func (p *parser) xzone() (string, int) {
715 sign := p.xtakelist("+", "-")
718 seconds := (v/100)*3600 + (v%100)*60
722 return sign + s, seconds
726func (p *parser) xdateTime() time.Time {
727 // DQUOTE date-day-fixed "-" date-month "-" date-year SP time SP zone DQUOTE
729 day := p.xdateDayFixed()
731 month := p.xdateMonth()
733 year := xint(p, p.xtaken(4))
735 hours, minutes, seconds := p.xtime()
737 name, zoneSeconds := p.xzone()
739 loc := time.FixedZone(name, zoneSeconds)
740 return time.Date(year, month, day, hours, minutes, seconds, 0, loc)
744func (p *parser) xliteralSize(maxSize int64, lit8 bool) (size int64, sync bool) {
745 // todo: enforce that we get non-binary when ~ isn't present?
751 if maxSize > 0 && size > maxSize {
753 line := fmt.Sprintf("* BYE [ALERT] Max literal size %d is larger than allowed %d in this context", size, maxSize)
754 err := errors.New("literal too big")
755 panic(syntaxError{line, "TOOBIG", err.Error(), err})
764var searchKeyWords = []string{
765 "ALL", "ANSWERED", "BCC",
767 "CC", "DELETED", "FLAGGED",
769 "NEW", "OLD", "ON", "RECENT", "SEEN",
772 "UNANSWERED", "UNDELETED", "UNFLAGGED",
773 "UNKEYWORD", "UNSEEN",
777 "SENTBEFORE", "SENTON",
778 "SENTSINCE", "SMALLER",
780 "MODSEQ", // CONDSTORE extension.
784// differences: rfc 9051 removes NEW, OLD, RECENT and makes SMALLER and LARGER number64 instead of number.
785func (p *parser) xsearchKey() *searchKey {
788 l := []searchKey{*sk}
791 l = append(l, *p.xsearchKey())
793 return &searchKey{searchKeys: l}
796 w, ok := p.takelist(searchKeyWords...)
799 return &searchKey{seqSet: &seqs}
802 sk := &searchKey{op: w}
808 sk.astring = p.xastring()
814 sk.astring = p.xastring()
817 sk.astring = p.xastring()
822 sk.astring = p.xastring()
838 sk.astring = p.xastring()
841 sk.astring = p.xastring()
844 sk.astring = p.xastring()
855 sk.headerField = p.xastring()
857 sk.astring = p.xastring()
860 sk.number = p.xnumber64()
863 sk.searchKey = p.xsearchKey()
866 sk.searchKey = p.xsearchKey()
868 sk.searchKey2 = p.xsearchKey()
880 sk.number = p.xnumber64()
883 sk.uidSet = p.xnumSet()
889 // We don't do anything with this field, so parse and ignore.
897 p.xtakelist("PRIV", "SHARED", "ALL")
903 p.conn.enabled[capCondstore] = true
905 p.xerrorf("missing case for op %q", sk.op)
910// hasModseq returns whether there is a modseq filter anywhere in the searchkey.
911func (sk searchKey) hasModseq() bool {
912 if sk.clientModseq != nil {
915 for _, e := range sk.searchKeys {
920 if sk.searchKey != nil && sk.searchKey.hasModseq() {
923 if sk.searchKey2 != nil && sk.searchKey2.hasModseq() {
930func (p *parser) xdateDay() int {
932 if s, ok := p.digit(); ok {
939func (p *parser) xdate() time.Time {
940 dquote := p.take(`"`)
943 mon := p.xdateMonth()
945 year := xint(p, p.xtaken(4))
949 return time.Date(year, mon, day, 0, 0, 0, 0, time.UTC)