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.
|
2021-02-28 12:57:06 +00:00
|
|
|
|
2021-02-28 16:03:52 +00:00
|
|
|
package main
|
|
|
|
|
2021-02-28 12:57:06 +00:00
|
|
|
import (
|
2023-06-07 20:28:01 +00:00
|
|
|
"errors"
|
2021-02-28 12:57:06 +00:00
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"strings"
|
|
|
|
|
2021-09-29 16:18:58 +00:00
|
|
|
"github.com/mattn/go-xmpp" // BSD-3-Clause
|
|
|
|
"salsa.debian.org/mdosch/xmppsrv" // BSD-2-Clause
|
2021-02-28 12:57:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func connect(options xmpp.Options, directTLS bool) (*xmpp.Client, error) {
|
2021-03-02 13:54:49 +00:00
|
|
|
// Look up SRV records if server is not specified manually.
|
2021-02-28 12:57:06 +00:00
|
|
|
if options.Host == "" {
|
2021-03-03 21:10:45 +00:00
|
|
|
server := options.User[strings.Index(options.User, "@")+1:]
|
2021-03-02 13:54:49 +00:00
|
|
|
// Look up xmpp-client SRV records.
|
2021-09-29 16:18:58 +00:00
|
|
|
srvMixed, err := xmppsrv.LookupClient(server)
|
|
|
|
if len(srvMixed) > 0 && err == nil {
|
2021-03-02 13:54:49 +00:00
|
|
|
for _, adr := range srvMixed {
|
2021-09-29 16:18:58 +00:00
|
|
|
if !directTLS && adr.Type != "xmpps-client" {
|
2021-03-02 13:54:49 +00:00
|
|
|
// Use StartTLS
|
|
|
|
options.NoTLS = true
|
|
|
|
options.StartTLS = true
|
2021-09-29 16:18:58 +00:00
|
|
|
} else if adr.Type == "xmpps-client" {
|
2021-03-02 13:54:49 +00:00
|
|
|
// Use direct TLS
|
|
|
|
options.NoTLS = false
|
|
|
|
options.StartTLS = false
|
2023-06-06 17:13:43 +00:00
|
|
|
}
|
|
|
|
options.Host = net.JoinHostPort(adr.Target, fmt.Sprint(adr.Port))
|
|
|
|
// Connect to server
|
|
|
|
client, err := options.NewClient()
|
2023-06-07 20:28:01 +00:00
|
|
|
if errors.Unwrap(err) == nil {
|
2023-06-06 17:13:43 +00:00
|
|
|
return client, nil
|
2021-02-28 12:57:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-06-04 09:47:56 +00:00
|
|
|
// 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")
|
|
|
|
}
|
2021-02-28 12:57:06 +00:00
|
|
|
}
|
2021-03-02 13:54:49 +00:00
|
|
|
// Connect to server
|
2021-02-28 12:57:06 +00:00
|
|
|
client, err := options.NewClient()
|
2023-06-07 20:28:01 +00:00
|
|
|
if errors.Unwrap(err) == nil {
|
2023-06-06 19:36:28 +00:00
|
|
|
return client, nil
|
|
|
|
}
|
|
|
|
return client, fmt.Errorf("failed to connect to server: %w", err)
|
2021-02-28 12:57:06 +00:00
|
|
|
}
|