-
Notifications
You must be signed in to change notification settings - Fork 56
/
discovery.go
182 lines (152 loc) · 4.98 KB
/
discovery.go
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package onvif
import (
"errors"
"net"
"regexp"
"strings"
"time"
"github.com/clbanning/mxj"
"github.com/satori/go.uuid"
)
var errWrongDiscoveryResponse = errors.New("Response is not related to discovery request")
// StartDiscovery send a WS-Discovery message and wait for all matching device to respond
func StartDiscovery(duration time.Duration) ([]Device, error) {
// Get list of interface address
addrs, err := net.InterfaceAddrs()
if err != nil {
return []Device{}, err
}
// Fetch IPv4 address
ipAddrs := []string{}
for _, addr := range addrs {
ipAddr, ok := addr.(*net.IPNet)
if ok && !ipAddr.IP.IsLoopback() && ipAddr.IP.To4() != nil {
ipAddrs = append(ipAddrs, ipAddr.IP.String())
}
}
// Create initial discovery results
discoveryResults := []Device{}
// Discover device on each interface's network
for _, ipAddr := range ipAddrs {
devices, err := discoverDevices(ipAddr, duration)
if err != nil {
return []Device{}, err
}
discoveryResults = append(discoveryResults, devices...)
}
return discoveryResults, nil
}
func discoverDevices(ipAddr string, duration time.Duration) ([]Device, error) {
// Create WS-Discovery request
requestID := "uuid:" + uuid.NewV4().String()
request := `
<?xml version="1.0" encoding="UTF-8"?>
<e:Envelope
xmlns:e="http://www.w3.org/2003/05/soap-envelope"
xmlns:w="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery"
xmlns:dn="http://www.onvif.org/ver10/network/wsdl">
<e:Header>
<w:MessageID>` + requestID + `</w:MessageID>
<w:To e:mustUnderstand="true">urn:schemas-xmlsoap-org:ws:2005:04:discovery</w:To>
<w:Action a:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe
</w:Action>
</e:Header>
<e:Body>
<d:Probe>
<d:Types>dn:NetworkVideoTransmitter</d:Types>
</d:Probe>
</e:Body>
</e:Envelope>`
// Clean WS-Discovery message
request = regexp.MustCompile(`\>\s+\<`).ReplaceAllString(request, "><")
request = regexp.MustCompile(`\s+`).ReplaceAllString(request, " ")
// Create UDP address for local and multicast address
localAddress, err := net.ResolveUDPAddr("udp4", ipAddr+":0")
if err != nil {
return []Device{}, err
}
multicastAddress, err := net.ResolveUDPAddr("udp4", "239.255.255.250:3702")
if err != nil {
return []Device{}, err
}
// Create UDP connection to listen for respond from matching device
conn, err := net.ListenUDP("udp", localAddress)
if err != nil {
return []Device{}, err
}
defer conn.Close()
// Set connection's timeout
err = conn.SetDeadline(time.Now().Add(duration))
if err != nil {
return []Device{}, err
}
// Send WS-Discovery request to multicast address
_, err = conn.WriteToUDP([]byte(request), multicastAddress)
if err != nil {
return []Device{}, err
}
// Create initial discovery results
discoveryResults := []Device{}
// Keep reading UDP message until timeout
for {
// Create buffer and receive UDP response
buffer := make([]byte, 10*1024)
_, _, err = conn.ReadFromUDP(buffer)
// Check if connection timeout
if err != nil {
if udpErr, ok := err.(net.Error); ok && udpErr.Timeout() {
break
} else {
return discoveryResults, err
}
}
// Read and parse WS-Discovery response
device, err := readDiscoveryResponse(requestID, buffer)
if err != nil && err != errWrongDiscoveryResponse {
return discoveryResults, err
}
// Push device to results
discoveryResults = append(discoveryResults, device)
}
return discoveryResults, nil
}
// readDiscoveryResponse reads and parses WS-Discovery response
func readDiscoveryResponse(messageID string, buffer []byte) (Device, error) {
// Inital result
result := Device{}
// Parse XML to map
mapXML, err := mxj.NewMapXml(buffer)
if err != nil {
return result, err
}
// Check if this response is for our request
responseMessageID, _ := mapXML.ValueForPathString("Envelope.Header.RelatesTo")
if responseMessageID != messageID {
return result, errWrongDiscoveryResponse
}
// Get device's ID and clean it
deviceID, _ := mapXML.ValueForPathString("Envelope.Body.ProbeMatches.ProbeMatch.EndpointReference.Address")
deviceID = strings.Replace(deviceID, "urn:uuid:", "", 1)
// Get device's name
deviceName := ""
scopes, _ := mapXML.ValueForPathString("Envelope.Body.ProbeMatches.ProbeMatch.Scopes")
for _, scope := range strings.Split(scopes, " ") {
if strings.HasPrefix(scope, "onvif://www.onvif.org/name/") {
deviceName = strings.Replace(scope, "onvif://www.onvif.org/name/", "", 1)
deviceName = strings.Replace(deviceName, "_", " ", -1)
break
}
}
// Get device's xAddrs
xAddrs, _ := mapXML.ValueForPathString("Envelope.Body.ProbeMatches.ProbeMatch.XAddrs")
listXAddr := strings.Split(xAddrs, " ")
if len(listXAddr) == 0 {
return result, errors.New("Device does not have any xAddr")
}
// Finalize result
result.ID = deviceID
result.Name = deviceName
result.XAddr = listXAddr[0]
return result, nil
}