go-sendxmpp/connect.go
2021-02-28 17:02:32 +01:00

61 lines
1.7 KiB
Go

// Copyright 2018 - 2021 Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.package main
import (
"fmt"
"net"
"strings"
"github.com/mattn/go-xmpp" // BSD-3-Clause
)
func connect(options xmpp.Options, directTLS bool) (*xmpp.Client, error) {
// Lookup SRV records if server is not specified manually
if options.Host == "" {
server := options.User[strings.LastIndex(options.User, "@")+1:]
// Lookup xmpp-client SRV records if direct TLS is not required
if !directTLS {
if _, addrs, err := net.LookupSRV("xmpp-client", "tcp", server); err == nil {
if len(addrs) > 0 {
for _, adr := range addrs {
options.Host = fmt.Sprintf("%s:%d", adr.Target, adr.Port)
// Connect to server
client, err := options.NewClient()
if err == nil {
return client, err
}
}
}
}
// Try port 5222 if no xmpp-client SRV records are provided.
options.Host = server + ":5222"
// Connect to server
client, err := options.NewClient()
if err == nil {
return client, err
}
// Unset STartTLS as we try direct TLS now
options.NoTLS = false
options.StartTLS = false
}
// Lookup xmpps-client SRV records
// TODO: Fallback to 5223 and 443 if no xmpps-client SRV records exist
if _, addrs, err := net.LookupSRV("xmpps-client", "tcp", server); err == nil {
if len(addrs) > 0 {
for _, adr := range addrs {
options.Host = fmt.Sprintf("%s:%d", adr.Target, adr.Port)
// Connect to server
client, err := options.NewClient()
if err == nil {
return client, err
}
}
}
}
}
client, err := options.NewClient()
return client, err
}