Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions docs/reference/endpoints/smtp.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,12 @@ Supported limits:

### _scope_ rate _burst_ _period_

Rate limit. Restrict the amount of messages processed in _period_ to
Rate limit. Allow an average of _burst_ messages per _period_, with bursts of
_burst_ messages. If period is not specified, 1 second is used.

Periods longer than 1 minute are not recommended for "ip", "source", or
"destination" scopes, which may be exceeded under high load.

### _scope_ concurrency _max_
Concurrency limit. Restrict the amount of messages processed in parallel
to _max_.
Expand All @@ -276,9 +279,10 @@ For each supported limitation, _scope_ determines whether it should be applied
for all messages ("all"), per-sender IP ("ip"), per-sender domain ("source") or
per-recipient domain ("destination"). Having a scope other than "all" means
that the restriction will be enforced independently for each group determined
by scope. E.g. "ip rate 20" means that the same IP cannot send more than 20
messages per second. "destination concurrency 5" means that no more than 5
messages can be sent in parallel to a single domain.
by scope. E.g. "ip rate 20" limits each IP to a long-term average of no more
than 20 messages per second, with bursts of up to 20 messages at once.
"destination concurrency 5" means that no more than 5 messages can be sent in
parallel to a single domain.

**Note**: At the moment, SMTP endpoint on its own does not support per-recipient
limits. They will be no-op. If you want to enforce a per-recipient restriction
Expand Down
51 changes: 22 additions & 29 deletions internal/endpoint/smtp/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import (
"github.com/foxcpp/maddy/framework/log"
"github.com/foxcpp/maddy/framework/module"
"github.com/foxcpp/maddy/internal/auth"
"github.com/foxcpp/maddy/internal/limits"
)

func limitReader(r io.Reader, n int64, err error) *limitedReader {
Expand Down Expand Up @@ -88,14 +89,15 @@ type Session struct {
// It is the subcontext of sessionCtx.
// Mutex is used to prevent Close from accessing inconsistent state when it
// is called asynchronously to any SMTP command.
msgLock sync.Mutex
msgCtx context.Context
msgTask *trace.Task
mailFrom string
opts smtp.MailOptions
msgMeta *module.MsgMetadata
delivery module.Delivery
deliveryErr error
msgLock sync.Mutex
msgCtx context.Context
msgTask *trace.Task
mailFrom string
opts smtp.MailOptions
msgMeta *module.MsgMetadata
delivery module.Delivery
deliveryErr error
releaseLimits limits.ReleaseFunc

log *log.Logger
}
Expand Down Expand Up @@ -186,23 +188,6 @@ func (s *Session) Reset() {
}
}

func (s *Session) releaseLimits() {
domain := ""
if s.mailFrom != "" {
var err error
_, domain, err = address.Split(s.mailFrom)
if err != nil {
return
}
}

addr, ok := s.msgMeta.Conn.RemoteAddr.(*net.TCPAddr)
if !ok {
addr = &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}
}
s.endp.limits.ReleaseMsg(addr.IP, domain)
}

func (s *Session) abort(ctx context.Context) {
if err := s.delivery.Abort(ctx); err != nil {
s.endp.log.Error("delivery abort failed", err)
Expand All @@ -213,7 +198,10 @@ func (s *Session) abort(ctx context.Context) {
}

func (s *Session) cleanSession() {
s.releaseLimits()
if s.releaseLimits != nil {
s.releaseLimits()
s.releaseLimits = nil
}

s.mailFrom = ""
s.opts = smtp.MailOptions{}
Expand Down Expand Up @@ -315,7 +303,8 @@ func (s *Session) startDelivery(ctx context.Context, from string, opts smtp.Mail
if !ok {
remoteIP = &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}
}
if err := s.endp.limits.TakeMsg(context.Background(), remoteIP.IP, domain); err != nil {
releaseMsg, err := s.endp.limits.TakeMsg(context.Background(), remoteIP.IP, domain)
if err != nil {
return "", err
}

Expand All @@ -328,7 +317,7 @@ func (s *Session) startDelivery(ctx context.Context, from string, opts smtp.Mail
if err != nil {
s.msgCtx = nil
s.msgTask.End()
s.endp.limits.ReleaseMsg(remoteIP.IP, domain)
releaseMsg()
return msgMeta.ID, err
}

Expand All @@ -337,6 +326,10 @@ func (s *Session) startDelivery(ctx context.Context, from string, opts smtp.Mail
s.msgMeta = msgMeta
s.mailFrom = cleanFrom
s.delivery = delivery
if s.releaseLimits != nil {
s.releaseLimits()
}
s.releaseLimits = releaseMsg

return msgMeta.ID, nil
}
Expand Down Expand Up @@ -631,7 +624,7 @@ func (endp *Endpoint) wrapErr(msgId string, mangleUTF8 bool, command string, err
return nil
}

if errors.Is(err, context.DeadlineExceeded) {
if limits.IsErrHighLoad(err) {
return &smtp.SMTPError{
Code: 451,
EnhancedCode: smtp.EnhancedCode{4, 4, 5},
Expand Down
106 changes: 38 additions & 68 deletions internal/limits/limiters/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
)

Expand All @@ -32,10 +33,9 @@ var ErrBucketSetFull = errors.New("limiters: Bucket set is full")
// BucketSet is to apply per-resource rate limiting.
//
// Amount of buckets is limited to a certain value. When the size of internal
// map is around or equal to that value, next Take call will attempt to remove
// any stale buckets from the group. If it is not possible to do so (all
// buckets are in active use), Take will return false. Alternatively, in some
// rare cases, some other (undefined) waiting Take can return false.
// map is around or equal to that value, next TakeContext call will attempt to
// remove any stale buckets from the group. If it is not possible to do so (all
// buckets are in active use), TakeContext will return an ErrBucketSetFull.
//
// A BucksetSet without a New function assigned is no-op: Take and TakeContext
// always succeed and Release does nothing.
Expand All @@ -54,48 +54,35 @@ type BucketSet struct {
MaxBuckets int

mLck sync.Mutex
m map[string]*struct {
r L
lastUse time.Time
}
m map[string]*bucketItem
}

type bucketItem struct {
r L
refCount atomic.Int64
lastUse time.Time
}

func NewBucketSet(new_ func() L, reapInterval time.Duration, maxBuckets int) *BucketSet {
return &BucketSet{
New: new_,
ReapInterval: reapInterval,
MaxBuckets: maxBuckets,
m: map[string]*struct {
r L
lastUse time.Time
}{},
m: map[string]*bucketItem{},
}
}

func (r *BucketSet) Close() {
r.mLck.Lock()
defer r.mLck.Unlock()

for _, v := range r.m {
v.r.Close()
}
}

func (r *BucketSet) take(key string) L {
func (r *BucketSet) take(key string) *bucketItem {
r.mLck.Lock()
defer r.mLck.Unlock()
bucket, ok := r.m[key]

if len(r.m) > r.MaxBuckets {
// Reap stale buckets when need create new bucket
if !ok && len(r.m) > r.MaxBuckets {
now := time.Now()
// Attempt to get rid of stale buckets.
for k, v := range r.m {
if now.Sub(v.lastUse) > r.ReapInterval {
// Drop the bucket, if there happen to be any waiting Take for it.
// It will return 'false', but this is fine for us since this
// whole 'reaping' process will run only when we are under a
// high load and dropping random requests in this case is a
// more or less reasonable thing to do.
v.r.Close()
if now.Sub(v.lastUse) > r.ReapInterval && v.refCount.Load() == 0 {
delete(r.m, k)
}
}
Expand All @@ -106,58 +93,41 @@ func (r *BucketSet) take(key string) L {
}
}

bucket, ok := r.m[key]
if !ok {
r.m[key] = &struct {
r L
lastUse time.Time
}{
r: r.New(),
lastUse: time.Now(),
r.m[key] = &bucketItem{
r: r.New(),
refCount: atomic.Int64{},
lastUse: time.Now(),
}
bucket = r.m[key]
}
r.m[key].lastUse = time.Now()
bucket.refCount.Add(1)

return bucket.r
return bucket
}

func (r *BucketSet) Take(key string) bool {
func (r *BucketSet) TakeContext(ctx context.Context, key string) (ReleaseFunc, error) {
if r.New == nil {
return true
return func() {}, nil
}

bucket := r.take(key)
for bucket == nil {
return false
}
return bucket.Take()
}

func (r *BucketSet) Release(key string) {
if r.New == nil {
return
}

r.mLck.Lock()
defer r.mLck.Unlock()

bucket, ok := r.m[key]
if !ok {
return
}
bucket.r.Release()
}

func (r *BucketSet) TakeContext(ctx context.Context, key string) error {
if r.New == nil {
return nil
if bucket == nil {
return nil, ErrBucketSetFull
}

bucket := r.take(key)
if bucket == nil {
return ErrBucketSetFull
release, err := bucket.r.TakeContext(ctx)
if err != nil {
bucket.refCount.Add(-1)
return nil, err
}

return bucket.TakeContext(ctx)
var once sync.Once
return func() {
once.Do(func() {
release()
bucket.refCount.Add(-1)
})
}, nil
}
53 changes: 23 additions & 30 deletions internal/limits/limiters/concurrency.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,51 +18,44 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.

package limiters

import "context"
import (
"context"
"sync"

"golang.org/x/sync/semaphore"
)

// Semaphore is a convenience wrapper for a channel that implements
// semaphore-kind synchronization.
//
// If the argument given to the NewSemaphore is negative or zero,
// all methods are no-op.
type Semaphore struct {
c chan struct{}
weighted *semaphore.Weighted
}

func NewSemaphore(max int) Semaphore {
return Semaphore{c: make(chan struct{}, max)}
}

func (s Semaphore) Take() bool {
if cap(s.c) <= 0 {
return true
s := Semaphore{weighted: nil}
if max > 0 {
s.weighted = semaphore.NewWeighted(int64(max))
}
s.c <- struct{}{}
return true
return s
}

func (s Semaphore) TakeContext(ctx context.Context) error {
if cap(s.c) <= 0 {
return nil
}
select {
case s.c <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
func (s Semaphore) TakeContext(ctx context.Context) (ReleaseFunc, error) {
if s.weighted == nil {
return func() {}, nil
}
}

func (s Semaphore) Release() {
if cap(s.c) <= 0 {
return
}
select {
case <-s.c:
default:
panic("limiters: mismatched Release call")
err := s.weighted.Acquire(ctx, 1)
if err != nil {
return nil, err
}
}

func (s Semaphore) Close() {
var once sync.Once
return func() {
once.Do(func() {
s.weighted.Release(1)
})
}, nil
}
13 changes: 6 additions & 7 deletions internal/limits/limiters/limiters.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,15 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
// of resources consumed by the server.
package limiters

import "context"
import (
"context"
)

type ReleaseFunc func()

// The L interface represents a blocking limiter that has some upper bound of
// resource use and blocks when it is exceeded until enough resources are
// freed.
type L interface {
Take() bool
TakeContext(context.Context) error
Release()

// Close frees any resources used internally by Limiter for book-keeping.
Close()
TakeContext(context.Context) (ReleaseFunc, error)
}
Loading
Loading