maildir.go 6.71 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
package main

import (
	"bufio"
	"bytes"
	"crypto/rand"
	"encoding/hex"
	"io"
	"net/mail"
	"net/textproto"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync/atomic"
	"time"
)

// Maildir type, inspired by github.com/luksen/maildir but without the
// accidentally quadratic behavior.
type Maildir string

// Create a maildir if it does not already exist.
func (d Maildir) Create() error {
	for _, sub := range []string{"cur", "new", "tmp"} {
		p := filepath.Join(string(d), sub)
		if _, err := os.Stat(p); os.IsNotExist(err) {
			if err := os.MkdirAll(p, 0700); err != nil {
				return err
			}
		}
	}
	return nil
}

// Unseen moves messages from the 'new' directory to 'cur', and
// returns their list.
func (d Maildir) Unseen() ([]string, error) {
	f, err := os.Open(filepath.Join(string(d), "new"))
	if err != nil {
		return nil, err
	}
ale's avatar
ale committed
43
	defer f.Close() // nolint
ale's avatar
ale committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	names, err := f.Readdirnames(0)
	if err != nil {
		return nil, err
	}
	var keys []string
	for _, n := range names {
		if n[0] == '.' {
			continue
		}
		if err := os.Rename(filepath.Join(string(d), "new", n), filepath.Join(string(d), "cur", n)); err == nil {
			keys = append(keys, n)
		}
	}
	return keys, nil
}

// Keys returns keys for all messages in a folder.
func (d Maildir) Keys() ([]string, error) {
	f, err := os.Open(filepath.Join(string(d), "cur"))
	if err != nil {
		return nil, err
	}
ale's avatar
ale committed
66
	defer f.Close() // nolint
ale's avatar
ale committed
67 68 69 70 71 72 73
	names, err := f.Readdirnames(0)
	return names, err
}

// Header returns a parsed message header.
func (d Maildir) Header(key string) (mail.Header, error) {
	filename := filepath.Join(string(d), "cur", key)
ale's avatar
ale committed
74
	file, err := os.Open(filename) // #nosec
ale's avatar
ale committed
75 76 77
	if err != nil {
		return nil, err
	}
ale's avatar
ale committed
78
	defer file.Close() // nolint
ale's avatar
ale committed
79 80 81 82 83 84 85 86 87 88 89
	tp := textproto.NewReader(bufio.NewReader(file))
	hdr, err := tp.ReadMIMEHeader()
	if err != nil {
		return nil, err
	}
	return mail.Header(hdr), nil
}

// Message returns a Message by key.
func (d Maildir) Message(key string) (*mail.Message, error) {
	filename := filepath.Join(string(d), "cur", key)
ale's avatar
ale committed
90
	r, err := os.Open(filename) // #nosec
ale's avatar
ale committed
91 92 93
	if err != nil {
		return nil, err
	}
ale's avatar
ale committed
94
	defer r.Close() // nolint
ale's avatar
ale committed
95 96 97 98 99 100 101 102
	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, r)
	if err != nil {
		return nil, err
	}
	return mail.ReadMessage(buf)
}

103 104 105 106 107
// Purge removes a message from the maildir.
func (d Maildir) Purge(key string) error {
	return os.Remove(filepath.Join(string(d), "cur", key))
}

ale's avatar
ale committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
// Delivery tracks the delivery of a single message to a maildir.
type Delivery struct {
	curPath, dstPath string
	f                *os.File
}

// Close the delivery successfully.
func (d *Delivery) Close() error {
	if err := d.f.Close(); err != nil {
		return err
	}
	return os.Rename(d.curPath, d.dstPath)
}

// Abort the delivery (remove temporary file).
func (d *Delivery) Abort() {
ale's avatar
ale committed
124 125
	d.f.Close()          // nolint
	os.Remove(d.curPath) // nolint
ale's avatar
ale committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

// Write the message body.
func (d *Delivery) Write(b []byte) (int, error) {
	return d.f.Write(b)
}

// NewDelivery starts writing a new message to the maildir.
func (d Maildir) NewDelivery() (*Delivery, error) {
	key, err := maildirKey()
	if err != nil {
		return nil, err
	}

	curPath := filepath.Join(string(d), "tmp", key)
	dstPath := filepath.Join(string(d), "new", key)
	f, err := os.Create(curPath)
	if err != nil {
		return nil, err
	}
	return &Delivery{
		f:       f,
		curPath: curPath,
		dstPath: dstPath,
	}, nil
}

var id int64

// maildirKey generates a new unique key as described in the Maildir
// specification.  For the third part of the key (delivery identifier)
// it uses an internal counter, the process id and a cryptographical
// random number to ensure uniqueness among messages delivered in the
// same second.
func maildirKey() (string, error) {
	var key string
	key += strconv.FormatInt(time.Now().Unix(), 10)
	key += "."
	host, err := os.Hostname()
	if err != nil {
		return "", err
	}
	host = strings.Replace(host, "/", "\057", -1)
	host = strings.Replace(host, ":", "\072", -1)
	key += host
	key += "."
	key += strconv.FormatInt(int64(os.Getpid()), 10)
	key += strconv.FormatInt(id, 10)
	atomic.AddInt64(&id, 1)
	bs := make([]byte, 10)
	_, err = io.ReadFull(rand.Reader, bs)
	if err != nil {
		return "", err
	}
	key += hex.EncodeToString(bs)
	return key, nil
}

type maildirMessage struct {
	key string
	hdr mail.Header
}

func (m *maildirMessage) Date() time.Time {
ale's avatar
ale committed
190 191
	// Return the zero value on error.
	t, _ := mail.ParseDate(m.hdr.Get("Date")) // nolint
ale's avatar
ale committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
	return t
}

func (m *maildirMessage) MessageID() string {
	return parseMessageID(m.hdr.Get("Message-ID"))
}

type maildirSource struct {
	root string
}

func (s *maildirSource) Close() {}

func isMaildir(path string) bool {
	stat, err := os.Stat(filepath.Join(path, "cur"))
	return err == nil && stat.IsDir()
}

func (s *maildirSource) ListFolders() ([]string, error) {
	var mboxes []string
	root := strings.TrimSuffix(s.root, "/")
	err := filepath.Walk(
		root,
		func(path string, fi os.FileInfo, err error) error {
			if err != nil {
				return nil
			}
			var relPath string
			if path != root {
				relPath = strings.TrimPrefix(path, root+"/")
			}
			if isMaildir(path) {
				mboxes = append(mboxes, relPath)
			}
			return nil
		},
	)
	return mboxes, err
}

func (s *maildirSource) ListMessages(folder string) ([]message, error) {
	dir := Maildir(filepath.Join(s.root, folder))

	var msgs []message
	keys, err := dir.Keys()
	if err != nil {
		return nil, err
	}
ale's avatar
ale committed
240
	unseen, _ := dir.Unseen() // nolint
ale's avatar
ale committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
	if len(unseen) > 0 {
		keys = append(keys, unseen...)
	}

	for _, key := range keys {
		hdr, err := dir.Header(key)
		if err != nil {
			continue
		}
		msgs = append(msgs, &maildirMessage{key: key, hdr: hdr})
	}
	return msgs, nil
}

func (s *maildirSource) FetchMessages(folder string, msgs []message) <-chan *mail.Message {
	dir := Maildir(filepath.Join(s.root, folder))

	ch := make(chan *mail.Message, 100)
	go func() {
		defer close(ch)
		for _, m := range msgs {
			msg, err := dir.Message(m.(*maildirMessage).key)
			if err == nil {
				ch <- msg
			}
		}
	}()
	return ch
}
270

271
func (s *maildirSource) DeleteMessages(folder string, msgs []message) error {
272
	dir := Maildir(filepath.Join(s.root, folder))
273 274 275 276 277 278
	for _, msg := range msgs {
		if err := dir.Purge(msg.(*maildirMessage).key); err != nil {
			return err
		}
	}
	return nil
279 280
}

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
type maildirDest struct {
	*maildirSource
}

func newMaildirDest(root string) *maildirDest {
	return &maildirDest{
		&maildirSource{
			root: root,
		},
	}
}

func (d *maildirDest) CreateFolder(folder string) error {
	dir := Maildir(filepath.Join(d.root, folder))
	return dir.Create()
}

func (d *maildirDest) WriteMessage(folder string, msg *mail.Message) error {
	dir := Maildir(filepath.Join(d.root, folder))
	delivery, err := dir.NewDelivery()
	if err != nil {
		return err
	}
	if err := writeMessage(msg, delivery); err != nil {
		delivery.Abort()
		return err
	}
	return delivery.Close()
}