github.com/mholt/caddy-l4@v0.0.0-20241104153248-ec8fae209322/modules/l4xmpp/matcher.go (about)

     1  // Copyright 2020 Matthew Holt
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package l4xmpp
    16  
    17  import (
    18  	"io"
    19  	"strings"
    20  
    21  	"github.com/caddyserver/caddy/v2"
    22  	"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
    23  
    24  	"github.com/mholt/caddy-l4/layer4"
    25  )
    26  
    27  func init() {
    28  	caddy.RegisterModule(&MatchXMPP{})
    29  }
    30  
    31  // MatchXMPP is able to match XMPP connections.
    32  type MatchXMPP struct{}
    33  
    34  // CaddyModule returns the Caddy module information.
    35  func (*MatchXMPP) CaddyModule() caddy.ModuleInfo {
    36  	return caddy.ModuleInfo{
    37  		ID:  "layer4.matchers.xmpp",
    38  		New: func() caddy.Module { return new(MatchXMPP) },
    39  	}
    40  }
    41  
    42  // Match returns true if the connection looks like XMPP.
    43  func (m *MatchXMPP) Match(cx *layer4.Connection) (bool, error) {
    44  	p := make([]byte, minXmppLength)
    45  	_, err := io.ReadFull(cx, p)
    46  	if err != nil { // needs at least 50 (fix for adium/pidgin)
    47  		return false, err
    48  	}
    49  	return strings.Contains(string(p), xmppWord), nil
    50  }
    51  
    52  // UnmarshalCaddyfile sets up the MatchXMPP from Caddyfile tokens. Syntax:
    53  //
    54  //	xmpp
    55  func (m *MatchXMPP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
    56  	_, wrapper := d.Next(), d.Val() // consume wrapper name
    57  
    58  	// No same-line options are supported
    59  	if d.CountRemainingArgs() > 0 {
    60  		return d.ArgErr()
    61  	}
    62  
    63  	// No blocks are supported
    64  	if d.NextBlock(d.Nesting()) {
    65  		return d.Errf("malformed layer4 connection matcher '%s': blocks are not supported", wrapper)
    66  	}
    67  
    68  	return nil
    69  }
    70  
    71  var xmppWord = "jabber"
    72  var minXmppLength = 50
    73  
    74  // Interface guards
    75  var (
    76  	_ layer4.ConnMatcher    = (*MatchXMPP)(nil)
    77  	_ caddyfile.Unmarshaler = (*MatchXMPP)(nil)
    78  )