summaryrefslogtreecommitdiffhomepage
path: root/src/conn.go
blob: b2caffb98e489bb539c10f19f9f739465655082b (plain)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main

import (
	"errors"
	"net"
)

type UDPBind interface {
	SetMark(value uint32) error
	ReceiveIPv6(buff []byte, end *Endpoint) (int, error)
	ReceiveIPv4(buff []byte, end *Endpoint) (int, error)
	Send(buff []byte, end *Endpoint) error
	Close() error
}

func parseEndpoint(s string) (*net.UDPAddr, error) {

	// ensure that the host is an IP address

	host, _, err := net.SplitHostPort(s)
	if err != nil {
		return nil, err
	}
	if ip := net.ParseIP(host); ip == nil {
		return nil, errors.New("Failed to parse IP address: " + host)
	}

	// parse address and port

	addr, err := net.ResolveUDPAddr("udp", s)
	if err != nil {
		return nil, err
	}
	return addr, err
}

func UpdateUDPListener(device *Device) error {
	device.mutex.Lock()
	defer device.mutex.Unlock()

	netc := &device.net
	netc.mutex.Lock()
	defer netc.mutex.Unlock()

	// close existing sockets

	if netc.bind != nil {
		println("close bind")
		if err := netc.bind.Close(); err != nil {
			return err
		}
		netc.bind = nil
		println("closed")
	}

	// open new sockets

	if device.tun.isUp.Get() {

		println("creat")

		// bind to new port

		var err error
		netc.bind, netc.port, err = CreateUDPBind(netc.port)
		if err != nil {
			return err
		}

		// set mark

		err = netc.bind.SetMark(netc.fwmark)
		if err != nil {
			return err
		}

		println("okay")

		// clear cached source addresses

		for _, peer := range device.peers {
			peer.mutex.Lock()
			peer.endpoint.value.ClearSrc()
			peer.mutex.Unlock()
		}
	}

	return nil
}

func CloseUDPListener(device *Device) error {
	netc := &device.net
	netc.mutex.Lock()
	defer netc.mutex.Unlock()
	return netc.bind.Close()
}