go-sendxmpp/connect.go

65 lines
1.8 KiB
Go
Raw Normal View History

2023-05-11 18:05:31 +00:00
// Copyright Martin Dosch.
2021-02-28 16:02:32 +00:00
// Use of this source code is governed by the BSD-2-clause
2022-05-02 15:13:50 +00:00
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"net"
"os"
"strings"
2024-01-10 15:21:39 +00:00
"github.com/xmppo/go-xmpp" // BSD-3-Clause
2021-09-29 16:18:58 +00:00
"salsa.debian.org/mdosch/xmppsrv" // BSD-2-Clause
)
func connect(options xmpp.Options, directTLS bool) (*xmpp.Client, error) {
proxy := os.Getenv("HTTP_PROXY")
// Look up SRV records if server is not specified manually.
if options.Host == "" {
server := options.User[strings.Index(options.User, "@")+1:]
// Don't do SRV look ups if proxy is set.
if proxy == "" {
// Look up xmpp-client SRV records.
srvMixed, err := xmppsrv.LookupClient(server)
if len(srvMixed) > 0 && err == nil {
for _, adr := range srvMixed {
if !directTLS && adr.Type != "xmpps-client" {
// Use StartTLS
options.NoTLS = true
options.StartTLS = true
} else if adr.Type == "xmpps-client" {
// Use direct TLS
options.NoTLS = false
options.StartTLS = false
}
options.Host = net.JoinHostPort(adr.Target, fmt.Sprint(adr.Port))
// Connect to server
client, err := options.NewClient()
if err == nil {
return client, nil
}
}
}
}
// Try port 5223 if directTLS is set and no xmpp-client SRV records are provided.
if directTLS {
options.NoTLS = false
options.StartTLS = false
options.Host = net.JoinHostPort(server, "5223")
} else {
// Try port 5222 if no xmpp-client SRV records are provided and directTLS is not set.
options.NoTLS = true
options.StartTLS = true
options.Host = net.JoinHostPort(server, "5222")
}
}
// Connect to server
client, err := options.NewClient()
if err == nil {
2023-06-06 19:36:28 +00:00
return client, nil
}
return client, fmt.Errorf("failed to connect to server: %w", err)
}