Fixing to have the proper version of go-imap from foxcpp.

This commit is contained in:
2025-12-08 22:52:36 +02:00
parent d8ddb6be71
commit 226c7e6cf0
207 changed files with 15166 additions and 15437 deletions

16
backend/backend.go Normal file
View File

@@ -0,0 +1,16 @@
// Package backend defines an IMAP server backend interface.
package backend
import "errors"
// ErrInvalidCredentials is returned by Backend.Login when a username or a
// password is incorrect.
var ErrInvalidCredentials = errors.New("Invalid credentials")
// Backend is an IMAP server backend. A backend operation always deals with
// users.
type Backend interface {
// Login authenticates a user. If the username or the password is incorrect,
// it returns ErrInvalidCredentials.
Login(username, password string) (User, error)
}

View File

@@ -0,0 +1,2 @@
// Package backendutil provides utility functions to implement IMAP backends.
package backendutil

View File

@@ -0,0 +1,55 @@
package backendutil
import (
"time"
)
var testDate, _ = time.Parse(time.RFC1123Z, "Sat, 18 Jun 2016 12:00:00 +0900")
const testHeaderString = "Content-Type: multipart/mixed; boundary=message-boundary\r\n" +
"Date: Sat, 18 Jun 2016 12:00:00 +0900\r\n" +
"From: Mitsuha Miyamizu <mitsuha.miyamizu@example.org>\r\n" +
"Message-Id: 42@example.org\r\n" +
"Subject: Your Name.\r\n" +
"To: Taki Tachibana <taki.tachibana@example.org>\r\n" +
"\r\n"
const testAltHeaderString = "Content-Type: multipart/alternative; boundary=b2\r\n" +
"\r\n"
const testTextHeaderString = "Content-Disposition: inline\r\n" +
"Content-Type: text/plain\r\n" +
"\r\n"
const testTextBodyString = "What's your name?"
const testTextString = testTextHeaderString + testTextBodyString
const testHTMLHeaderString = "Content-Disposition: inline\r\n" +
"Content-Type: text/html\r\n" +
"\r\n"
const testHTMLBodyString = "<div>What's <i>your</i> name?</div>"
const testHTMLString = testHTMLHeaderString + testHTMLBodyString
const testAttachmentHeaderString = "Content-Disposition: attachment; filename=note.txt\r\n" +
"Content-Type: text/plain\r\n" +
"\r\n"
const testAttachmentBodyString = "My name is Mitsuha."
const testAttachmentString = testAttachmentHeaderString + testAttachmentBodyString
const testBodyString = "--message-boundary\r\n" +
testAltHeaderString +
"\r\n--b2\r\n" +
testTextString +
"\r\n--b2\r\n" +
testHTMLString +
"\r\n--b2--\r\n" +
"\r\n--message-boundary\r\n" +
testAttachmentString +
"\r\n--message-boundary--\r\n"
const testMailString = testHeaderString + testBodyString

View File

@@ -0,0 +1,75 @@
package backendutil
import (
"bytes"
"errors"
"io"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
)
var errNoSuchPart = errors.New("backendutil: no such message body part")
// FetchBodySection extracts a body section from a message.
func FetchBodySection(e *message.Entity, section *imap.BodySectionName) (imap.Literal, error) {
// First, find the requested part using the provided path
for i := 0; i < len(section.Path); i++ {
n := section.Path[i]
mr := e.MultipartReader()
if mr == nil {
return nil, errNoSuchPart
}
for j := 1; j <= n; j++ {
p, err := mr.NextPart()
if err == io.EOF {
return nil, errNoSuchPart
} else if err != nil {
return nil, err
}
if j == n {
e = p
break
}
}
}
// Then, write the requested data to a buffer
b := new(bytes.Buffer)
// Write the header
mw, err := message.CreateWriter(b, e.Header)
if err != nil {
return nil, err
}
defer mw.Close()
switch section.Specifier {
case imap.TextSpecifier:
// The header hasn't been requested. Discard it.
b.Reset()
case imap.EntireSpecifier:
if len(section.Path) > 0 {
// When selecting a specific part by index, IMAP servers
// return only the text, not the associated MIME header.
b.Reset()
}
}
// Write the body, if requested
switch section.Specifier {
case imap.EntireSpecifier, imap.TextSpecifier:
if _, err := io.Copy(mw, e.Body); err != nil {
return nil, err
}
}
var l imap.Literal = b
if section.Partial != nil {
l = bytes.NewReader(section.ExtractPartial(b.Bytes()))
}
return l, nil
}

View File

@@ -0,0 +1,109 @@
package backendutil
import (
"io/ioutil"
"strings"
"testing"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
)
var bodyTests = []struct {
section string
body string
}{
{
section: "BODY[]",
body: testMailString,
},
{
section: "BODY[1.1]",
body: testTextBodyString,
},
{
section: "BODY[1.2]",
body: testHTMLBodyString,
},
{
section: "BODY[2]",
body: testAttachmentBodyString,
},
{
section: "BODY[HEADER]",
body: testHeaderString,
},
{
section: "BODY[1.1.HEADER]",
body: testTextHeaderString,
},
{
section: "BODY[2.HEADER]",
body: testAttachmentHeaderString,
},
{
section: "BODY[2.MIME]",
body: testAttachmentHeaderString,
},
{
section: "BODY[TEXT]",
body: testBodyString,
},
{
section: "BODY[1.1.TEXT]",
body: testTextBodyString,
},
{
section: "BODY[2.TEXT]",
body: testAttachmentBodyString,
},
{
section: "BODY[2.1]",
body: "",
},
{
section: "BODY[3]",
body: "",
},
{
section: "BODY[2.TEXT]<0.9>",
body: testAttachmentBodyString[:9],
},
}
func TestFetchBodySection(t *testing.T) {
for _, test := range bodyTests {
test := test
t.Run(test.section, func(t *testing.T) {
e, err := message.Read(strings.NewReader(testMailString))
if err != nil {
t.Fatal("Expected no error while reading mail, got:", err)
}
section, err := imap.ParseBodySectionName(imap.FetchItem(test.section))
if err != nil {
t.Fatal("Expected no error while parsing body section name, got:", err)
}
r, err := FetchBodySection(e, section)
if test.body == "" {
if err == nil {
t.Error("Expected an error while extracting non-existing body section")
}
} else {
if err != nil {
t.Fatal("Expected no error while extracting body section, got:", err)
}
b, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal("Expected no error while reading body section, got:", err)
}
if s := string(b); s != test.body {
t.Errorf("Expected body section %q to be \n%s\n but got \n%s", test.section, test.body, s)
}
}
})
}
}

View File

@@ -0,0 +1,60 @@
package backendutil
import (
"io"
"strings"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
)
// FetchBodyStructure computes a message's body structure from its content.
func FetchBodyStructure(e *message.Entity, extended bool) (*imap.BodyStructure, error) {
bs := new(imap.BodyStructure)
mediaType, mediaParams, _ := e.Header.ContentType()
typeParts := strings.SplitN(mediaType, "/", 2)
bs.MIMEType = typeParts[0]
if len(typeParts) == 2 {
bs.MIMESubType = typeParts[1]
}
bs.Params = mediaParams
bs.Id = e.Header.Get("Content-Id")
bs.Description = e.Header.Get("Content-Description")
bs.Encoding = e.Header.Get("Content-Encoding")
// TODO: bs.Size
if mr := e.MultipartReader(); mr != nil {
var parts []*imap.BodyStructure
for {
p, err := mr.NextPart()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
pbs, err := FetchBodyStructure(p, extended)
if err != nil {
return nil, err
}
parts = append(parts, pbs)
}
bs.Parts = parts
}
// TODO: bs.Envelope, bs.BodyStructure
// TODO: bs.Lines
if extended {
bs.Extended = true
bs.Disposition, bs.DispositionParams, _ = e.Header.ContentDisposition()
// TODO: bs.Language, bs.Location
// TODO: bs.MD5
}
return bs, nil
}

View File

@@ -0,0 +1,67 @@
package backendutil
import (
"reflect"
"strings"
"testing"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
)
var testBodyStructure = &imap.BodyStructure{
MIMEType: "multipart",
MIMESubType: "mixed",
Params: map[string]string{"boundary": "message-boundary"},
Parts: []*imap.BodyStructure{
{
MIMEType: "multipart",
MIMESubType: "alternative",
Params: map[string]string{"boundary": "b2"},
Extended: true,
Parts: []*imap.BodyStructure{
{
MIMEType: "text",
MIMESubType: "plain",
Params: map[string]string{},
Extended: true,
Disposition: "inline",
DispositionParams: map[string]string{},
},
{
MIMEType: "text",
MIMESubType: "html",
Params: map[string]string{},
Extended: true,
Disposition: "inline",
DispositionParams: map[string]string{},
},
},
},
{
MIMEType: "text",
MIMESubType: "plain",
Params: map[string]string{},
Extended: true,
Disposition: "attachment",
DispositionParams: map[string]string{"filename": "note.txt"},
},
},
Extended: true,
}
func TestFetchBodyStructure(t *testing.T) {
e, err := message.Read(strings.NewReader(testMailString))
if err != nil {
t.Fatal("Expected no error while reading mail, got:", err)
}
bs, err := FetchBodyStructure(e, true)
if err != nil {
t.Fatal("Expected no error while fetching body structure, got:", err)
}
if !reflect.DeepEqual(testBodyStructure, bs) {
t.Errorf("Expected body structure \n%+v\n but got \n%+v", testBodyStructure, bs)
}
}

View File

@@ -0,0 +1,50 @@
package backendutil
import (
"strings"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
"github.com/emersion/go-message/mail"
)
func headerAddressList(h mail.Header, key string) ([]*imap.Address, error) {
addrs, err := h.AddressList(key)
list := make([]*imap.Address, len(addrs))
for i, a := range addrs {
parts := strings.SplitN(a.Address, "@", 2)
mailbox := parts[0]
var hostname string
if len(parts) == 2 {
hostname = parts[1]
}
list[i] = &imap.Address{
PersonalName: a.Name,
MailboxName: mailbox,
HostName: hostname,
}
}
return list, err
}
// FetchEnvelope returns a message's envelope from its header.
func FetchEnvelope(h message.Header) (*imap.Envelope, error) {
mh := mail.Header{h}
env := new(imap.Envelope)
env.Date, _ = mh.Date()
env.Subject, _ = mh.Subject()
env.From, _ = headerAddressList(mh, "From")
env.Sender, _ = headerAddressList(mh, "Sender")
env.ReplyTo, _ = headerAddressList(mh, "Reply-To")
env.To, _ = headerAddressList(mh, "To")
env.Cc, _ = headerAddressList(mh, "Cc")
env.Bcc, _ = headerAddressList(mh, "Bcc")
env.InReplyTo = mh.Get("In-Reply-To")
env.MessageId = mh.Get("Message-Id")
return env, nil
}

View File

@@ -0,0 +1,39 @@
package backendutil
import (
"reflect"
"strings"
"testing"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
)
var testEnvelope = &imap.Envelope{
Date: testDate,
Subject: "Your Name.",
From: []*imap.Address{{PersonalName: "Mitsuha Miyamizu", MailboxName: "mitsuha.miyamizu", HostName: "example.org"}},
Sender: []*imap.Address{},
ReplyTo: []*imap.Address{},
To: []*imap.Address{{PersonalName: "Taki Tachibana", MailboxName: "taki.tachibana", HostName: "example.org"}},
Cc: []*imap.Address{},
Bcc: []*imap.Address{},
InReplyTo: "",
MessageId: "42@example.org",
}
func TestFetchEnvelope(t *testing.T) {
e, err := message.Read(strings.NewReader(testMailString))
if err != nil {
t.Fatal("Expected no error while reading mail, got:", err)
}
env, err := FetchEnvelope(e.Header)
if err != nil {
t.Fatal("Expected no error while fetching envelope, got:", err)
}
if !reflect.DeepEqual(env, testEnvelope) {
t.Errorf("Expected envelope \n%+v\n but got \n%+v", testEnvelope, env)
}
}

View File

@@ -0,0 +1,40 @@
package backendutil
import (
"github.com/emersion/go-imap"
)
// UpdateFlags executes a flag operation on the flag set current.
func UpdateFlags(current []string, op imap.FlagsOp, flags []string) []string {
switch op {
case imap.SetFlags:
// TODO: keep \Recent if it is present
return flags
case imap.AddFlags:
// Check for duplicates
for _, flag := range current {
for i, addFlag := range flags {
if addFlag == flag {
flags = append(flags[:i], flags[i+1:]...)
break
}
}
}
return append(current, flags...)
case imap.RemoveFlags:
// Iterate through flags from the last one to the first one, to be able to
// delete some of them.
for i := len(current) - 1; i >= 0; i-- {
flag := current[i]
for _, removeFlag := range flags {
if removeFlag == flag {
current = append(current[:i], current[i+1:]...)
break
}
}
}
return current
}
return current
}

View File

@@ -0,0 +1,46 @@
package backendutil
import (
"reflect"
"testing"
"github.com/emersion/go-imap"
)
var updateFlagsTests = []struct {
op imap.FlagsOp
flags []string
res []string
}{
{
op: imap.AddFlags,
flags: []string{"d", "e"},
res: []string{"a", "b", "c", "d", "e"},
},
{
op: imap.AddFlags,
flags: []string{"a", "d", "b"},
res: []string{"a", "b", "c", "d"},
},
{
op: imap.RemoveFlags,
flags: []string{"b", "v", "e", "a"},
res: []string{"c"},
},
{
op: imap.SetFlags,
flags: []string{"a", "d", "e"},
res: []string{"a", "d", "e"},
},
}
func TestUpdateFlags(t *testing.T) {
current := []string{"a", "b", "c"}
for _, test := range updateFlagsTests {
got := UpdateFlags(current[:], test.op, test.flags)
if !reflect.DeepEqual(got, test.res) {
t.Errorf("Expected result to be \n%v\n but got \n%v", test.res, got)
}
}
}

View File

@@ -0,0 +1,225 @@
package backendutil
import (
"bytes"
"fmt"
"io"
"strings"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
"github.com/emersion/go-message/mail"
)
func matchString(s, substr string) bool {
return strings.Contains(strings.ToLower(s), strings.ToLower(substr))
}
func bufferBody(e *message.Entity) (*bytes.Buffer, error) {
b := new(bytes.Buffer)
if _, err := io.Copy(b, e.Body); err != nil {
return nil, err
}
e.Body = b
return b, nil
}
func matchBody(e *message.Entity, substr string) (bool, error) {
if s, ok := e.Body.(fmt.Stringer); ok {
return matchString(s.String(), substr), nil
}
b, err := bufferBody(e)
if err != nil {
return false, err
}
return matchString(b.String(), substr), nil
}
type lengther interface {
Len() int
}
func bodyLen(e *message.Entity) (int, error) {
if l, ok := e.Body.(lengther); ok {
return l.Len(), nil
}
b, err := bufferBody(e)
if err != nil {
return 0, err
}
return b.Len(), nil
}
// Match returns true if a message matches the provided criteria. Sequence
// number, UID, flag and internal date contrainsts are not checked.
func Match(e *message.Entity, c *imap.SearchCriteria) (bool, error) {
// TODO: support encoded header fields for Bcc, Cc, From, To
// TODO: add header size for Larger and Smaller
h := mail.Header{e.Header}
if !c.SentBefore.IsZero() || !c.SentSince.IsZero() {
t, err := h.Date()
if err != nil {
return false, err
}
t = t.Round(24 * time.Hour)
if !c.SentBefore.IsZero() && !t.Before(c.SentBefore) {
return false, nil
}
if !c.SentSince.IsZero() && !t.After(c.SentSince) {
return false, nil
}
}
for key, wantValues := range c.Header {
values, ok := e.Header[key]
for _, wantValue := range wantValues {
if wantValue == "" && !ok {
return false, nil
}
if wantValue != "" {
ok := false
for _, v := range values {
if matchString(v, wantValue) {
ok = true
break
}
}
if !ok {
return false, nil
}
}
}
}
for _, body := range c.Body {
if ok, err := matchBody(e, body); err != nil || !ok {
return false, err
}
}
for _, text := range c.Text {
// TODO: also match header fields
if ok, err := matchBody(e, text); err != nil || !ok {
return false, err
}
}
if c.Larger > 0 || c.Smaller > 0 {
n, err := bodyLen(e)
if err != nil {
return false, err
}
if c.Larger > 0 && uint32(n) < c.Larger {
return false, nil
}
if c.Smaller > 0 && uint32(n) > c.Smaller {
return false, nil
}
}
for _, not := range c.Not {
ok, err := Match(e, not)
if err != nil || ok {
return false, err
}
}
for _, or := range c.Or {
ok1, err := Match(e, or[0])
if err != nil {
return ok1, err
}
ok2, err := Match(e, or[1])
if err != nil || (!ok1 && !ok2) {
return false, err
}
}
return true, nil
}
func matchFlags(flags map[string]bool, c *imap.SearchCriteria) bool {
for _, f := range c.WithFlags {
if !flags[f] {
return false
}
}
for _, f := range c.WithoutFlags {
if flags[f] {
return false
}
}
for _, not := range c.Not {
if matchFlags(flags, not) {
return false
}
}
for _, or := range c.Or {
if !matchFlags(flags, or[0]) && !matchFlags(flags, or[1]) {
return false
}
}
return true
}
// MatchFlags returns true if a flag list matches the provided criteria.
func MatchFlags(flags []string, c *imap.SearchCriteria) bool {
flagsMap := make(map[string]bool)
for _, f := range flags {
flagsMap[f] = true
}
return matchFlags(flagsMap, c)
}
// MatchSeqNumAndUid returns true if a sequence number and a UID matches the
// provided criteria.
func MatchSeqNumAndUid(seqNum uint32, uid uint32, c *imap.SearchCriteria) bool {
if c.SeqNum != nil && !c.SeqNum.Contains(seqNum) {
return false
}
if c.Uid != nil && !c.Uid.Contains(uid) {
return false
}
for _, not := range c.Not {
if MatchSeqNumAndUid(seqNum, uid, not) {
return false
}
}
for _, or := range c.Or {
if !MatchSeqNumAndUid(seqNum, uid, or[0]) && !MatchSeqNumAndUid(seqNum, uid, or[1]) {
return false
}
}
return true
}
// MatchDate returns true if a date matches the provided criteria.
func MatchDate(date time.Time, c *imap.SearchCriteria) bool {
date = date.Round(24 * time.Hour)
if !c.Since.IsZero() && !date.After(c.Since) {
return false
}
if !c.Before.IsZero() && !date.Before(c.Before) {
return false
}
for _, not := range c.Not {
if MatchDate(date, not) {
return false
}
}
for _, or := range c.Or {
if !MatchDate(date, or[0]) && !MatchDate(date, or[1]) {
return false
}
}
return true
}

View File

@@ -0,0 +1,264 @@
package backendutil
import (
"net/textproto"
"strings"
"testing"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-message"
)
var matchTests = []struct {
criteria *imap.SearchCriteria
res bool
}{
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"From": {"Mitsuha"}},
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"To": {"Mitsuha"}},
},
res: false,
},
{
criteria: &imap.SearchCriteria{SentBefore: testDate.Add(48 * time.Hour)},
res: true,
},
{
criteria: &imap.SearchCriteria{
Not: []*imap.SearchCriteria{{SentSince: testDate.Add(48 * time.Hour)}},
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Not: []*imap.SearchCriteria{{Body: []string{"name"}}},
},
res: false,
},
{
criteria: &imap.SearchCriteria{
Text: []string{"name"},
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Or: [][2]*imap.SearchCriteria{{
{Text: []string{"i'm not in the text"}},
{Body: []string{"i'm not in the body"}},
}},
},
res: false,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"Message-Id": {"42@example.org"}},
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"Message-Id": {"43@example.org"}},
},
res: false,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"Message-Id": {""}},
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"Reply-To": {""}},
},
res: false,
},
{
criteria: &imap.SearchCriteria{
Larger: 10,
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Smaller: 10,
},
res: false,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"Subject": {"your"}},
},
res: true,
},
{
criteria: &imap.SearchCriteria{
Header: textproto.MIMEHeader{"Subject": {"Taki"}},
},
res: false,
},
}
func TestMatch(t *testing.T) {
for i, test := range matchTests {
e, err := message.Read(strings.NewReader(testMailString))
if err != nil {
t.Fatal("Expected no error while reading entity, got:", err)
}
ok, err := Match(e, test.criteria)
if err != nil {
t.Fatal("Expected no error while matching entity, got:", err)
}
if test.res && !ok {
t.Errorf("Expected #%v to match search criteria", i+1)
}
if !test.res && ok {
t.Errorf("Expected #%v not to match search criteria", i+1)
}
}
}
var flagsTests = []struct {
flags []string
criteria *imap.SearchCriteria
res bool
}{
{
flags: []string{imap.SeenFlag},
criteria: &imap.SearchCriteria{
WithFlags: []string{imap.SeenFlag},
WithoutFlags: []string{imap.FlaggedFlag},
},
res: true,
},
{
flags: []string{imap.SeenFlag},
criteria: &imap.SearchCriteria{
WithFlags: []string{imap.DraftFlag},
WithoutFlags: []string{imap.FlaggedFlag},
},
res: false,
},
{
flags: []string{imap.SeenFlag, imap.FlaggedFlag},
criteria: &imap.SearchCriteria{
WithFlags: []string{imap.SeenFlag},
WithoutFlags: []string{imap.FlaggedFlag},
},
res: false,
},
{
flags: []string{imap.SeenFlag, imap.FlaggedFlag},
criteria: &imap.SearchCriteria{
Or: [][2]*imap.SearchCriteria{{
{WithFlags: []string{imap.DraftFlag}},
{WithoutFlags: []string{imap.SeenFlag}},
}},
},
res: false,
},
{
flags: []string{imap.SeenFlag, imap.FlaggedFlag},
criteria: &imap.SearchCriteria{
Not: []*imap.SearchCriteria{
{WithFlags: []string{imap.SeenFlag}},
},
},
res: false,
},
}
func TestMatchFlags(t *testing.T) {
for i, test := range flagsTests {
ok := MatchFlags(test.flags, test.criteria)
if test.res && !ok {
t.Errorf("Expected #%v to match search criteria", i+1)
}
if !test.res && ok {
t.Errorf("Expected #%v not to match search criteria", i+1)
}
}
}
func TestMatchSeqNumAndUid(t *testing.T) {
seqNum := uint32(42)
uid := uint32(69)
c := &imap.SearchCriteria{
Or: [][2]*imap.SearchCriteria{{
{
Uid: new(imap.SeqSet),
Not: []*imap.SearchCriteria{{SeqNum: new(imap.SeqSet)}},
},
{
SeqNum: new(imap.SeqSet),
},
}},
}
if MatchSeqNumAndUid(seqNum, uid, c) {
t.Error("Expected not to match criteria")
}
c.Or[0][0].Uid.AddNum(uid)
if !MatchSeqNumAndUid(seqNum, uid, c) {
t.Error("Expected to match criteria")
}
c.Or[0][0].Not[0].SeqNum.AddNum(seqNum)
if MatchSeqNumAndUid(seqNum, uid, c) {
t.Error("Expected not to match criteria")
}
c.Or[0][1].SeqNum.AddNum(seqNum)
if !MatchSeqNumAndUid(seqNum, uid, c) {
t.Error("Expected to match criteria")
}
}
func TestMatchDate(t *testing.T) {
date := time.Unix(1483997966, 0)
c := &imap.SearchCriteria{
Or: [][2]*imap.SearchCriteria{{
{
Since: date.Add(48 * time.Hour),
Not: []*imap.SearchCriteria{{
Since: date.Add(48 * time.Hour),
}},
},
{
Before: date.Add(-48 * time.Hour),
},
}},
}
if MatchDate(date, c) {
t.Error("Expected not to match criteria")
}
c.Or[0][0].Since = date.Add(-48 * time.Hour)
if !MatchDate(date, c) {
t.Error("Expected to match criteria")
}
c.Or[0][0].Not[0].Since = date.Add(-48 * time.Hour)
if MatchDate(date, c) {
t.Error("Expected not to match criteria")
}
c.Or[0][1].Before = date.Add(48 * time.Hour)
if !MatchDate(date, c) {
t.Error("Expected to match criteria")
}
}

78
backend/mailbox.go Normal file
View File

@@ -0,0 +1,78 @@
package backend
import (
"time"
"github.com/emersion/go-imap"
)
// Mailbox represents a mailbox belonging to a user in the mail storage system.
// A mailbox operation always deals with messages.
type Mailbox interface {
// Name returns this mailbox name.
Name() string
// Info returns this mailbox info.
Info() (*imap.MailboxInfo, error)
// Status returns this mailbox status. The fields Name, Flags, PermanentFlags
// and UnseenSeqNum in the returned MailboxStatus must be always populated.
// This function does not affect the state of any messages in the mailbox. See
// RFC 3501 section 6.3.10 for a list of items that can be requested.
Status(items []imap.StatusItem) (*imap.MailboxStatus, error)
// SetSubscribed adds or removes the mailbox to the server's set of "active"
// or "subscribed" mailboxes.
SetSubscribed(subscribed bool) error
// Check 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). 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.
Check() error
// ListMessages returns a list of messages. seqset must be interpreted as UIDs
// if uid is set to true and as message sequence numbers otherwise. See RFC
// 3501 section 6.4.5 for a list of items that can be requested.
//
// Messages must be sent to ch. When the function returns, ch must be closed.
ListMessages(uid bool, seqset *imap.SeqSet, items []imap.FetchItem, ch chan<- *imap.Message) error
// SearchMessages searches messages. The returned list must contain UIDs if
// uid is set to true, or sequence numbers otherwise.
SearchMessages(uid bool, criteria *imap.SearchCriteria) ([]uint32, error)
// CreateMessage appends a new message to this mailbox. The \Recent flag will
// be added no matter flags is empty or not. If date is nil, the current time
// will be used.
//
// If the Backend implements Updater, it must notify the client immediately
// via a mailbox update.
CreateMessage(flags []string, date time.Time, body imap.Literal) error
// UpdateMessagesFlags alters flags for the specified message(s).
//
// If the Backend implements Updater, it must notify the client immediately
// via a message update.
UpdateMessagesFlags(uid bool, seqset *imap.SeqSet, operation imap.FlagsOp, flags []string) error
// CopyMessages copies the specified message(s) to the end of the specified
// destination mailbox. The flags and internal date of the message(s) SHOULD
// be preserved, and the Recent flag SHOULD be set, in the copy.
//
// If the destination mailbox does not exist, a server SHOULD return an error.
// It SHOULD NOT automatically create the mailbox.
//
// If the Backend implements Updater, it must notify the client immediately
// via a mailbox update.
CopyMessages(uid bool, seqset *imap.SeqSet, dest string) error
// Expunge permanently removes all messages that have the \Deleted flag set
// from the currently selected mailbox.
//
// If the Backend implements Updater, it must notify the client immediately
// via an expunge update.
Expunge() error
}

55
backend/memory/backend.go Normal file
View File

@@ -0,0 +1,55 @@
// A memory backend.
package memory
import (
"errors"
"time"
"github.com/emersion/go-imap/backend"
)
type Backend struct {
users map[string]*User
}
func (be *Backend) Login(username, password string) (backend.User, error) {
user, ok := be.users[username]
if ok && user.password == password {
return user, nil
}
return nil, errors.New("Bad username or password")
}
func New() *Backend {
user := &User{username: "username", password: "password"}
body := `From: contact@example.org
To: contact@example.org
Subject: A little message, just for you
Date: Wed, 11 May 2016 14:31:59 +0000
Message-ID: <0000000@localhost/>
Content-Type: text/plain
Hi there :)`
user.mailboxes = map[string]*Mailbox{
"INBOX": {
name: "INBOX",
user: user,
Messages: []*Message{
{
Uid: 6,
Date: time.Now(),
Flags: []string{"\\Seen"},
Size: uint32(len(body)),
Body: []byte(body),
},
},
},
}
return &Backend{
users: map[string]*User{user.username: user},
}
}

243
backend/memory/mailbox.go Normal file
View File

@@ -0,0 +1,243 @@
package memory
import (
"io/ioutil"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/backend"
"github.com/emersion/go-imap/backend/backendutil"
)
var Delimiter = "/"
type Mailbox struct {
Subscribed bool
Messages []*Message
name string
user *User
}
func (mbox *Mailbox) Name() string {
return mbox.name
}
func (mbox *Mailbox) Info() (*imap.MailboxInfo, error) {
info := &imap.MailboxInfo{
Delimiter: Delimiter,
Name: mbox.name,
}
return info, nil
}
func (mbox *Mailbox) uidNext() uint32 {
var uid uint32
for _, msg := range mbox.Messages {
if msg.Uid > uid {
uid = msg.Uid
}
}
uid++
return uid
}
func (mbox *Mailbox) flags() []string {
flagsMap := make(map[string]bool)
for _, msg := range mbox.Messages {
for _, f := range msg.Flags {
if !flagsMap[f] {
flagsMap[f] = true
}
}
}
var flags []string
for f := range flagsMap {
flags = append(flags, f)
}
return flags
}
func (mbox *Mailbox) unseenSeqNum() uint32 {
for i, msg := range mbox.Messages {
seqNum := uint32(i + 1)
seen := false
for _, flag := range msg.Flags {
if flag == imap.SeenFlag {
seen = true
break
}
}
if !seen {
return seqNum
}
}
return 0
}
func (mbox *Mailbox) Status(items []imap.StatusItem) (*imap.MailboxStatus, error) {
status := imap.NewMailboxStatus(mbox.name, items)
status.Flags = mbox.flags()
status.PermanentFlags = []string{"\\*"}
status.UnseenSeqNum = mbox.unseenSeqNum()
for _, name := range items {
switch name {
case imap.StatusMessages:
status.Messages = uint32(len(mbox.Messages))
case imap.StatusUidNext:
status.UidNext = mbox.uidNext()
case imap.StatusUidValidity:
status.UidValidity = 1
case imap.StatusRecent:
status.Recent = 0 // TODO
case imap.StatusUnseen:
status.Unseen = 0 // TODO
}
}
return status, nil
}
func (mbox *Mailbox) SetSubscribed(subscribed bool) error {
mbox.Subscribed = subscribed
return nil
}
func (mbox *Mailbox) Check() error {
return nil
}
func (mbox *Mailbox) ListMessages(uid bool, seqSet *imap.SeqSet, items []imap.FetchItem, ch chan<- *imap.Message) error {
defer close(ch)
for i, msg := range mbox.Messages {
seqNum := uint32(i + 1)
var id uint32
if uid {
id = msg.Uid
} else {
id = seqNum
}
if !seqSet.Contains(id) {
continue
}
m, err := msg.Fetch(seqNum, items)
if err != nil {
continue
}
ch <- m
}
return nil
}
func (mbox *Mailbox) SearchMessages(uid bool, criteria *imap.SearchCriteria) ([]uint32, error) {
var ids []uint32
for i, msg := range mbox.Messages {
seqNum := uint32(i + 1)
ok, err := msg.Match(seqNum, criteria)
if err != nil || !ok {
continue
}
var id uint32
if uid {
id = msg.Uid
} else {
id = seqNum
}
ids = append(ids, id)
}
return ids, nil
}
func (mbox *Mailbox) CreateMessage(flags []string, date time.Time, body imap.Literal) error {
if date.IsZero() {
date = time.Now()
}
b, err := ioutil.ReadAll(body)
if err != nil {
return err
}
mbox.Messages = append(mbox.Messages, &Message{
Uid: mbox.uidNext(),
Date: date,
Size: uint32(len(b)),
Flags: flags,
Body: b,
})
return nil
}
func (mbox *Mailbox) UpdateMessagesFlags(uid bool, seqset *imap.SeqSet, op imap.FlagsOp, flags []string) error {
for i, msg := range mbox.Messages {
var id uint32
if uid {
id = msg.Uid
} else {
id = uint32(i + 1)
}
if !seqset.Contains(id) {
continue
}
msg.Flags = backendutil.UpdateFlags(msg.Flags, op, flags)
}
return nil
}
func (mbox *Mailbox) CopyMessages(uid bool, seqset *imap.SeqSet, destName string) error {
dest, ok := mbox.user.mailboxes[destName]
if !ok {
return backend.ErrNoSuchMailbox
}
for i, msg := range mbox.Messages {
var id uint32
if uid {
id = msg.Uid
} else {
id = uint32(i + 1)
}
if !seqset.Contains(id) {
continue
}
msgCopy := *msg
msgCopy.Uid = dest.uidNext()
dest.Messages = append(dest.Messages, &msgCopy)
}
return nil
}
func (mbox *Mailbox) Expunge() error {
for i := len(mbox.Messages) - 1; i >= 0; i-- {
msg := mbox.Messages[i]
deleted := false
for _, flag := range msg.Flags {
if flag == imap.DeletedFlag {
deleted = true
break
}
}
if deleted {
mbox.Messages = append(mbox.Messages[:i], mbox.Messages[i+1:]...)
}
}
return nil
}

70
backend/memory/message.go Normal file
View File

@@ -0,0 +1,70 @@
package memory
import (
"bytes"
"time"
"github.com/emersion/go-imap"
"github.com/emersion/go-imap/backend/backendutil"
"github.com/emersion/go-message"
)
type Message struct {
Uid uint32
Date time.Time
Size uint32
Flags []string
Body []byte
}
func (m *Message) entity() (*message.Entity, error) {
return message.Read(bytes.NewReader(m.Body))
}
func (m *Message) Fetch(seqNum uint32, items []imap.FetchItem) (*imap.Message, error) {
fetched := imap.NewMessage(seqNum, items)
for _, item := range items {
switch item {
case imap.FetchEnvelope:
e, _ := m.entity()
fetched.Envelope, _ = backendutil.FetchEnvelope(e.Header)
case imap.FetchBody, imap.FetchBodyStructure:
e, _ := m.entity()
fetched.BodyStructure, _ = backendutil.FetchBodyStructure(e, item == imap.FetchBodyStructure)
case imap.FetchFlags:
fetched.Flags = m.Flags
case imap.FetchInternalDate:
fetched.InternalDate = m.Date
case imap.FetchRFC822Size:
fetched.Size = m.Size
case imap.FetchUid:
fetched.Uid = m.Uid
default:
section, err := imap.ParseBodySectionName(item)
if err != nil {
break
}
e, _ := m.entity()
l, _ := backendutil.FetchBodySection(e, section)
fetched.Body[section] = l
}
}
return fetched, nil
}
func (m *Message) Match(seqNum uint32, c *imap.SearchCriteria) (bool, error) {
if !backendutil.MatchSeqNumAndUid(seqNum, m.Uid, c) {
return false, nil
}
if !backendutil.MatchDate(m.Date, c) {
return false, nil
}
if !backendutil.MatchFlags(m.Flags, c) {
return false, nil
}
e, _ := m.entity()
return backendutil.Match(e, c)
}

82
backend/memory/user.go Normal file
View File

@@ -0,0 +1,82 @@
package memory
import (
"errors"
"github.com/emersion/go-imap/backend"
)
type User struct {
username string
password string
mailboxes map[string]*Mailbox
}
func (u *User) Username() string {
return u.username
}
func (u *User) ListMailboxes(subscribed bool) (mailboxes []backend.Mailbox, err error) {
for _, mailbox := range u.mailboxes {
if subscribed && !mailbox.Subscribed {
continue
}
mailboxes = append(mailboxes, mailbox)
}
return
}
func (u *User) GetMailbox(name string) (mailbox backend.Mailbox, err error) {
mailbox, ok := u.mailboxes[name]
if !ok {
err = errors.New("No such mailbox")
}
return
}
func (u *User) CreateMailbox(name string) error {
if _, ok := u.mailboxes[name]; ok {
return errors.New("Mailbox already exists")
}
u.mailboxes[name] = &Mailbox{name: name, user: u}
return nil
}
func (u *User) DeleteMailbox(name string) error {
if name == "INBOX" {
return errors.New("Cannot delete INBOX")
}
if _, ok := u.mailboxes[name]; !ok {
return errors.New("No such mailbox")
}
delete(u.mailboxes, name)
return nil
}
func (u *User) RenameMailbox(existingName, newName string) error {
mbox, ok := u.mailboxes[existingName]
if !ok {
return errors.New("No such mailbox")
}
u.mailboxes[newName] = &Mailbox{
name: newName,
Messages: mbox.Messages,
user: u,
}
mbox.Messages = nil
if existingName != "INBOX" {
delete(u.mailboxes, existingName)
}
return nil
}
func (u *User) Logout() error {
return nil
}

92
backend/updates.go Normal file
View File

@@ -0,0 +1,92 @@
package backend
import (
"github.com/emersion/go-imap"
)
// Update contains user and mailbox information about an unilateral backend
// update.
type Update interface {
// The user targeted by this update. If empty, all connected users will
// be notified.
Username() string
// The mailbox targeted by this update. If empty, the update targets all
// mailboxes.
Mailbox() string
// Done returns a channel that is closed when the update has been broadcast to
// all clients.
Done() chan struct{}
}
// NewUpdate creates a new update.
func NewUpdate(username, mailbox string) Update {
return &update{
username: username,
mailbox: mailbox,
}
}
type update struct {
username string
mailbox string
done chan struct{}
}
func (u *update) Username() string {
return u.username
}
func (u *update) Mailbox() string {
return u.mailbox
}
func (u *update) Done() chan struct{} {
if u.done == nil {
u.done = make(chan struct{})
}
return u.done
}
// StatusUpdate is a status update. See RFC 3501 section 7.1 for a list of
// status responses.
type StatusUpdate struct {
Update
*imap.StatusResp
}
// MailboxUpdate is a mailbox update.
type MailboxUpdate struct {
Update
*imap.MailboxStatus
}
// MessageUpdate is a message update.
type MessageUpdate struct {
Update
*imap.Message
}
// ExpungeUpdate is an expunge update.
type ExpungeUpdate struct {
Update
SeqNum uint32
}
// BackendUpdater is a Backend that implements Updater is able to send
// unilateral backend updates. Backends not implementing this interface don't
// correctly send unilateral updates, for instance if a user logs in from two
// connections and deletes a message from one of them, the over is not aware
// that such a mesage has been deleted. More importantly, backends implementing
// Updater can notify the user for external updates such as new message
// notifications.
type BackendUpdater interface {
// Updates returns a set of channels where updates are sent to.
Updates() <-chan Update
}
// MailboxPoller is a Mailbox that is able to poll updates for new messages or
// message status updates during a period of inactivity.
type MailboxPoller interface {
// Poll requests mailbox updates.
Poll() error
}

92
backend/user.go Normal file
View File

@@ -0,0 +1,92 @@
package backend
import "errors"
var (
// ErrNoSuchMailbox is returned by User.GetMailbox, User.DeleteMailbox and
// User.RenameMailbox when retrieving, deleting or renaming a mailbox that
// doesn't exist.
ErrNoSuchMailbox = errors.New("No such mailbox")
// ErrMailboxAlreadyExists is returned by User.CreateMailbox and
// User.RenameMailbox when creating or renaming mailbox that already exists.
ErrMailboxAlreadyExists = errors.New("Mailbox already exists")
)
// User represents a user in the mail storage system. A user operation always
// deals with mailboxes.
type User interface {
// Username returns this user's username.
Username() string
// ListMailboxes returns a list of mailboxes belonging to this user. If
// subscribed is set to true, only returns subscribed mailboxes.
ListMailboxes(subscribed bool) ([]Mailbox, error)
// GetMailbox returns a mailbox. If it doesn't exist, it returns
// ErrNoSuchMailbox.
GetMailbox(name string) (Mailbox, error)
// CreateMailbox creates a new mailbox.
//
// If the mailbox already exists, an error must be returned. If the mailbox
// name is suffixed with the server's hierarchy separator character, this is a
// declaration that the client intends to create mailbox names under this name
// in the hierarchy.
//
// If the server's hierarchy separator character appears elsewhere in the
// name, the server SHOULD create any superior hierarchical names that are
// needed for the CREATE command to be successfully completed. In other
// words, an attempt to create "foo/bar/zap" on a server in which "/" is the
// hierarchy separator character SHOULD create foo/ and foo/bar/ if they do
// not already exist.
//
// If a new mailbox is created with the same name as a mailbox which was
// deleted, its unique identifiers MUST be greater than any unique identifiers
// used in the previous incarnation of the mailbox UNLESS the new incarnation
// has a different unique identifier validity value.
CreateMailbox(name string) error
// DeleteMailbox permanently remove the mailbox with the given name. It is an
// error to // attempt to delete INBOX or a mailbox name that does not exist.
//
// The DELETE command MUST NOT remove inferior hierarchical names. For
// example, if a mailbox "foo" has an inferior "foo.bar" (assuming "." is the
// hierarchy delimiter character), removing "foo" MUST NOT remove "foo.bar".
//
// The value of the highest-used unique identifier of the deleted mailbox MUST
// be preserved so that a new mailbox created with the same name will not
// reuse the identifiers of the former incarnation, UNLESS the new incarnation
// has a different unique identifier validity value.
DeleteMailbox(name string) error
// RenameMailbox changes the name of a mailbox. It is an error to attempt to
// rename from a mailbox name that does not exist or to a mailbox name that
// already exists.
//
// If the name has inferior hierarchical names, then the inferior hierarchical
// names MUST also be renamed. For example, a rename of "foo" to "zap" will
// rename "foo/bar" (assuming "/" is the hierarchy delimiter character) to
// "zap/bar".
//
// If the server's hierarchy separator character appears in the name, the
// server SHOULD create any superior hierarchical names that are needed for
// the RENAME command to complete successfully. In other words, an attempt to
// rename "foo/bar/zap" to baz/rag/zowie on a server in which "/" is the
// hierarchy separator character SHOULD create baz/ and baz/rag/ if they do
// not already exist.
//
// The value of the highest-used unique identifier of the old mailbox name
// MUST be preserved so that a new mailbox created with the same name will not
// reuse the identifiers of the former incarnation, UNLESS the new incarnation
// has a different unique identifier validity value.
//
// Renaming INBOX is permitted, and has special behavior. It moves all
// messages in INBOX to a new mailbox with the given name, leaving INBOX
// empty. If the server implementation supports inferior hierarchical names
// of INBOX, these are unaffected by a rename of INBOX.
RenameMailbox(existingName, newName string) error
// Logout is called when this User will no longer be used, likely because the
// client closed the connection.
Logout() error
}