~samwhited/xmpp

9f227b859efa8a8693fbd651c8df753a3728b985 — Sam Whited 6 years ago 60f92de
Move the server package into the xmpp package
3 files changed, 96 insertions(+), 0 deletions(-)

A server/doc.go
A server/options.go
A server/server.go
A server/doc.go => server/doc.go +3 -0
@@ 0,0 1,3 @@
// The server package is used to manage C2S, S2S, and component connections to
// your XMPP server or component. It does most of the heavy lifting.
package server

A server/options.go => server/options.go +45 -0
@@ 0,0 1,45 @@
package server

import (
	"crypto/tls"
)

type Option func(*options)
type options struct {
	clientAddr string // TCP address to listen on, ":xmpp-client" if empty.
	tlsConfig  *tls.Config
}

func getOpts(o ...Option) (res options) {
	for _, f := range o {
		f(&res)
	}
	return
}

// The ClientAddr option sets the interface and port that the server will listen
// on for inbounc connections from XMPP clients.
func ClientAddr(addr string) Option {
	return func(o *options) {
		o.clientAddr = addr
	}
}

// The TLSConfig option fully configures the servers TLS including the
// certificate chains used, cipher suites, etc. based on the given tls.Config.
func TLSConfig(config *tls.Config) Option {
	return func(o *options) {
		o.tlsConfig = config
	}
}

var (
	PreferClientCipherSuites = preferClientCipherSuites // Prefer cipher suite order indicated by the client (not recommended).
)

var preferClientCipherSuites = func(o *options) {
	if o.tlsConfig == nil {
		o.tlsConfig = &tls.Config{}
	}
	o.tlsConfig.PreferServerCipherSuites = true
}

A server/server.go => server/server.go +48 -0
@@ 0,0 1,48 @@
package server

import (
	"net"
)

// A Server defines parameters for running an XMPP server.
type Server struct {
	options
	// handler ConnHandler // Connection handler to invoke.
}

// New creates a new XMPP server with the given options.
func New(opts ...Option) *Server {
	return &Server{
		options: getOpts(opts...),
	}
}

// ListenAndServe listens on the TCP network address ClientAddr and then calls
// Serve to handle requests on incoming connections. If ClientAddr is blank,
// ":xmpp-client" (":5222")is used.
func (srv *Server) ListenAndServe() error {
	clientaddr := srv.options.clientAddr
	if clientaddr == "" {
		clientaddr = ":5222"
	}
	ln, err := net.Listen("tcp", srv.options.clientAddr)
	if err != nil {
		return err
	}
	return srv.Serve(ln.(*net.TCPListener))
}

// Serve accepts incoming connections on the Listener, spawning a new service
// goroutine for each.
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	for {
		_, e := l.Accept()
		if e != nil {
			// TODO(ssw): Figure out how to handle logging
			continue
		} else {
			// go srv.Handler.Handle(rw, l)
		}
	}
}