-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdiscovery.go
257 lines (218 loc) · 7.35 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package onvif
import (
"errors"
"github.com/clbanning/mxj"
"github.com/golang/glog"
"github.com/google/uuid"
"net"
"regexp"
"strings"
"time"
)
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 StartDiscoveryOn(interfaceName string, duration time.Duration) ([]Device, error) {
itf, err := net.InterfaceByName(interfaceName) //here your interface
if err != nil {
return []Device{}, err
}
item, _ := itf.Addrs()
var ip net.IP
for _, addr := range item {
switch v := addr.(type) {
case *net.IPNet:
if !v.IP.IsLoopback() {
if v.IP.To4() != nil { //Verify if IP is IPV4
ip = v.IP
}
}
}
}
if ip == nil {
return []Device{}, err
}
// Discover device on interface's network
devices, err := discoverDevices(ip.String(), duration)
return devices, nil
}
// StartDiscovery send a WS-Discovery message and wait for all matching device to respond
func StartDiscovery(interfaceName string, duration time.Duration) ([]Device, error) {
// Get list of interface address
if interfaceName != "" {
return StartDiscoveryOn(interfaceName, duration)
}
addrs, err := net.InterfaceAddrs()
if err != nil {
return []Device{}, err
}
// Fetch IPv4 address
var 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
var 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.New().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>`
request := `<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope
xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</a:Action>
<a:MessageID>` + requestID + `</a:MessageID>
<a:ReplyTo><a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>
<a:To s:mustUnderstand="1">urn:schemas-xmlsoap-org:ws:2005:04:discovery</a:To>
</s:Header>
<s:Body>
<Probe xmlns="http://schemas.xmlsoap.org/ws/2005/04/discovery">
<d:Types xmlns:d="http://schemas.xmlsoap.org/ws/2005/04/discovery" xmlns:dp0="http://www.onvif.org/ver10/network/wsdl">dp0:NetworkVideoTransmitter</d:Types>
</Probe>
</s:Body>
</s: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 := make([]Device, 0)
// 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
}
}
//fmt.Println(string(buffer))
// 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) {
glog.Infof("Discover response: %s", string(buffer))
// Inital result
result := Device{}
// Parse XML to map
mapXML, err := mxj.NewMapXml(buffer)
if err != nil {
glog.Warningf("Parse response error %v", err)
return result, err
}
// Check if this response is for our request
responseMessageID, err := mapXML.ValueForPath("Envelope.Header.RelatesTo")
if err != nil {
glog.Warningf("Parse message id error %v", err)
return result, err
}
if responseMessageMap, ok := responseMessageID.(map[string]interface{}); ok {
responseMessage := responseMessageMap["#text"].(string)
if responseMessage != messageID {
glog.Info(responseMessage)
glog.Info(messageID)
return result, errWrongDiscoveryResponse
}
} else {
if responseMessageID != messageID {
glog.Info(responseMessageID)
glog.Info(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)
glog.Infof("Discover device id: %s", deviceID)
// 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, " ")
glog.Infof("Discover address: %s", xAddrs)
if len(listXAddr) == 0 {
glog.Warning("Discover address len 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
}