~samwhited/xmpp

ref: d3ceddb51fa198df1449016fda7923afe83bb0f3 xmpp/dial1_6.go -rw-r--r-- 1.7 KiB
d3ceddb5Sam Whited Add some new options to Config 5 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

// +build !go1.7

package xmpp

import (
	"net"
	"strconv"
	"time"

	"golang.org/x/net/context"
)

func (d *Dialer) dial(
	ctx context.Context, network string, config *Config) (*Conn, error) {
	if ctx == nil {
		panic("xmpp.Dial: nil context")
	}

	// Backwards compatibility with old net.Dialer cancelation methods.
	deadline := d.deadline(ctx, time.Now())
	if !deadline.IsZero() {
		if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
			subCtx, cancel := context.WithDeadline(ctx, deadline)
			defer cancel()
			ctx = subCtx
		}
	}
	if oldCancel := d.Cancel; oldCancel != nil {
		subCtx, cancel := context.WithCancel(ctx)
		defer cancel()
		go func() {
			select {
			case <-oldCancel:
				cancel()
			case <-subCtx.Done():
			}
		}()
		ctx = subCtx
	}

	if d.NoLookup {
		p, err := lookupPort(network, config.connType())
		if err != nil {
			return nil, err
		}
		conn, err := d.Dialer.Dial(network, net.JoinHostPort(
			config.Location.Domainpart(),
			strconv.FormatUint(uint64(p), 10),
		))
		if err != nil {
			return nil, err
		}
		return NewConn(ctx, config, conn)
	}

	addrs, err := lookupService(config.connType(), network, config.Location)
	if err != nil {
		return nil, err
	}

	// Try dialing all of the SRV records we know about, breaking as soon as the
	// connection is established.
	for _, addr := range addrs {
		if conn, e := d.Dialer.Dial(network, net.JoinHostPort(
			addr.Target, strconv.FormatUint(uint64(addr.Port), 10),
		),
		); e != nil {
			err = e
			continue
		} else {
			return NewConn(ctx, config, conn)
		}
	}
	return nil, err
}