summaryrefslogtreecommitdiffhomepage
path: root/src/conn.go
blob: 7b35829f83a0889b6689c9abef4fb892295980cd (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
package main

import (
	"net"
)

func updateUDPConn(device *Device) error {
	netc := &device.net
	netc.mutex.Lock()
	defer netc.mutex.Unlock()

	// close existing connection

	if netc.conn != nil {
		netc.conn.Close()
		netc.conn = nil
	}

	// open new connection

	if device.tun.isUp.Get() {

		// listen on new address

		conn, err := net.ListenUDP("udp", netc.addr)
		if err != nil {
			return err
		}

		// set fwmark

		err = setMark(netc.conn, netc.fwmark)
		if err != nil {
			return err
		}

		// retrieve port (may have been chosen by kernel)

		addr := conn.LocalAddr()
		netc.conn = conn
		netc.addr, _ = net.ResolveUDPAddr(
			addr.Network(),
			addr.String(),
		)

		// notify goroutines

		signalSend(device.signal.newUDPConn)
	}

	return nil
}

func closeUDPConn(device *Device) {
	netc := &device.net
	netc.mutex.Lock()
	if netc.conn != nil {
		netc.conn.Close()
	}
	netc.mutex.Unlock()
	signalSend(device.signal.newUDPConn)
}