Newer
Older
zangtumb / backend.go
package main

import (
	"bufio"
	"log"
	"os"
	"strings"
)

// The Backend implements SMTP server methods.
type Backend struct {
	MailBaseFolder      string
	ValidRecipientsFile string
	ValidRecipientsMap  map[string]struct{}
	MaxRecipients       int
}

var SmtpBackend *Backend

// Load Valid Recipients
func (bkd *Backend) LoadValidRecipients() error {
	bkd.MaxRecipients = 0
	var void struct{}
	file, err := os.Open(bkd.ValidRecipientsFile)
	if err != nil {
		log.Println(err)
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		s := strings.Trim(scanner.Text(), " ")
		bkd.ValidRecipientsMap[s] = void
		log.Printf("RCPT: <%s>", s)
		bkd.MaxRecipients++
	}

	return nil

}

// Checks if Mail is a valid recipient
func (bkd *Backend) CheckValidRcpt(to string) bool {

	_, isValid := bkd.ValidRecipientsMap[to]

	return isValid

}

func init() {
	SmtpBackend = new(Backend)
	SmtpBackend.ValidRecipientsMap = make(map[string]struct{})
	SmtpBackend.ValidRecipientsFile = os.Getenv("RECIPIENTS")
	if SmtpBackend.ValidRecipientsFile == "" {
		SmtpBackend.ValidRecipientsFile = "./recipients.conf"
	}

	SmtpBackend.MailBaseFolder = os.Getenv("MAILFOLDER")
	if SmtpBackend.MailBaseFolder == "" {
		SmtpBackend.MailBaseFolder = "./mail"
	}
	if err := SmtpBackend.LoadValidRecipients(); err != nil {
		log.Println("Failed to load Recipients", err)
	} else {
		log.Println("Recipients Loaded")
	}

}