Debian Codegraph @

goupnp/ssdp/registry.go

raw symbols SCIP
1 package ssdp
2
3 import (
4 "fmt"
5 "net/http"
6 "net/url"
7 "regexp"
8 "strconv"
9 "sync"
10 "time"
11
12 "github.com/NebulousLabs/go-upnp/goupnp/httpu"
13 )
14
15 const (
16 maxExpiryTimeSeconds = 24 * 60 * 60
17 )
18
19 var (
20 maxAgeRx = regexp.MustCompile("max-age=([0-9]+)")
21 )
22
23 const (
24 EventAlive = EventType(iota)
25 EventUpdate
26 EventByeBye
27 )
28
29 type EventType int8
30
31 func (et EventType) String() string {
32 switch et {
33 case EventAlive:
34 return "EventAlive"
35 case EventUpdate:
36 return "EventUpdate"
37 case EventByeBye:
38 return "EventByeBye"
39 default:
40 return fmt.Sprintf("EventUnknown(%d)", int8(et))
41 }
42 }
43
44 type Update struct {
45 // The USN of the service.
46 USN string
47 // What happened.
48 EventType EventType
49 // The entry, which is nil if the service was not known and
50 // EventType==EventByeBye. The contents of this must not be modified as it is
51 // shared with the registry and other listeners. Once created, the Registry
52 // does not modify the Entry value - any updates are replaced with a new
53 // Entry value.
54 Entry *Entry
55 }
56
57 type Entry struct {
58 // The address that the entry data was actually received from.
59 RemoteAddr string
60 // Unique Service Name. Identifies a unique instance of a device or service.
61 USN string
62 // Notfication Type. The type of device or service being announced.
63 NT string
64 // Server's self-identifying string.
65 Server string
66 Host string
67 // Location of the UPnP root device description.
68 Location url.URL
69
70 // Despite BOOTID,CONFIGID being required fields, apparently they are not
71 // always set by devices. Set to -1 if not present.
72
73 BootID int32
74 ConfigID int32
75
76 SearchPort uint16
77
78 // When the last update was received for this entry identified by this USN.
79 LastUpdate time.Time
80 // When the last update's cached values are advised to expire.
81 CacheExpiry time.Time
82 }
83
84 func newEntryFromRequest(r *http.Request) (*Entry, error) {
85 now := time.Now()
86 expiryDuration, err := parseCacheControlMaxAge(r.Header.Get("CACHE-CONTROL"))
87 if err != nil {
88 return nil, fmt.Errorf("ssdp: error parsing CACHE-CONTROL max age: %v", err)
89 }
90
91 loc, err := url.Parse(r.Header.Get("LOCATION"))
92 if err != nil {
93 return nil, fmt.Errorf("ssdp: error parsing entry Location URL: %v", err)
94 }
95
96 bootID, err := parseUpnpIntHeader(r.Header, "BOOTID.UPNP.ORG", -1)
97 if err != nil {
98 return nil, err
99 }
100 configID, err := parseUpnpIntHeader(r.Header, "CONFIGID.UPNP.ORG", -1)
101 if err != nil {
102 return nil, err
103 }
104 searchPort, err := parseUpnpIntHeader(r.Header, "SEARCHPORT.UPNP.ORG", ssdpSearchPort)
105 if err != nil {
106 return nil, err
107 }
108
109 if searchPort < 1 || searchPort > 65535 {
110 return nil, fmt.Errorf("ssdp: search port %d is out of range", searchPort)
111 }
112
113 return &Entry{
114 RemoteAddr: r.RemoteAddr,
115 USN: r.Header.Get("USN"),
116 NT: r.Header.Get("NT"),
117 Server: r.Header.Get("SERVER"),
118 Host: r.Header.Get("HOST"),
119 Location: *loc,
120 BootID: bootID,
121 ConfigID: configID,
122 SearchPort: uint16(searchPort),
123 LastUpdate: now,
124 CacheExpiry: now.Add(expiryDuration),
125 }, nil
126 }
127
128 func parseCacheControlMaxAge(cc string) (time.Duration, error) {
129 matches := maxAgeRx.FindStringSubmatch(cc)
130 if len(matches) != 2 {
131 return 0, fmt.Errorf("did not find exactly one max-age in cache control header: %q", cc)
132 }
133 expirySeconds, err := strconv.ParseInt(matches[1], 10, 16)
134 if err != nil {
135 return 0, err
136 }
137 if expirySeconds < 1 || expirySeconds > maxExpiryTimeSeconds {
138 return 0, fmt.Errorf("rejecting bad expiry time of %d seconds", expirySeconds)
139 }
140 return time.Duration(expirySeconds) * time.Second, nil
141 }
142
143 // parseUpnpIntHeader is intended to parse the
144 // {BOOT,CONFIGID,SEARCHPORT}.UPNP.ORG header fields. It returns the def if
145 // the head is empty or missing.
146 func parseUpnpIntHeader(headers http.Header, headerName string, def int32) (int32, error) {
147 s := headers.Get(headerName)
148 if s == "" {
149 return def, nil
150 }
151 v, err := strconv.ParseInt(s, 10, 32)
152 if err != nil {
153 return 0, fmt.Errorf("ssdp: could not parse header %s: %v", headerName, err)
154 }
155 return int32(v), nil
156 }
157
158 var _ httpu.Handler = new(Registry)
159
160 // Registry maintains knowledge of discovered devices and services.
161 //
162 // NOTE: the interface for this is experimental and may change, or go away
163 // entirely.
164 type Registry struct {
165 lock sync.Mutex
166 byUSN map[string]*Entry
167
168 listenersLock sync.RWMutex
169 listeners map[chan<- Update]struct{}
170 }
171
172 func NewRegistry() *Registry {
173 return &Registry{
174 byUSN: make(map[string]*Entry),
175 listeners: make(map[chan<- Update]struct{}),
176 }
177 }
178
179 // NewServerAndRegistry is a convenience function to create a registry, and an
180 // httpu server to pass it messages. Call ListenAndServe on the server for
181 // messages to be processed.
182 func NewServerAndRegistry() (*httpu.Server, *Registry) {
183 reg := NewRegistry()
184 srv := &httpu.Server{
185 Addr: ssdpUDP4Addr,
186 Multicast: true,
187 Handler: reg,
188 }
189 return srv, reg
190 }
191
192 func (reg *Registry) AddListener(c chan<- Update) {
193 reg.listenersLock.Lock()
194 defer reg.listenersLock.Unlock()
195 reg.listeners[c] = struct{}{}
196 }
197
198 func (reg *Registry) RemoveListener(c chan<- Update) {
199 reg.listenersLock.Lock()
200 defer reg.listenersLock.Unlock()
201 delete(reg.listeners, c)
202 }
203
204 func (reg *Registry) sendUpdate(u Update) {
205 reg.listenersLock.RLock()
206 defer reg.listenersLock.RUnlock()
207 for c := range reg.listeners {
208 c <- u
209 }
210 }
211
212 // GetService returns known service (or device) entries for the given service
213 // URN.
214 func (reg *Registry) GetService(serviceURN string) []*Entry {
215 // Currently assumes that the map is small, so we do a linear search rather
216 // than indexed to avoid maintaining two maps.
217 var results []*Entry
218 reg.lock.Lock()
219 defer reg.lock.Unlock()
220 for _, entry := range reg.byUSN {
221 if entry.NT == serviceURN {
222 results = append(results, entry)
223 }
224 }
225 return results
226 }
227
228 // ServeMessage implements httpu.Handler, and uses SSDP NOTIFY requests to
229 // maintain the registry of devices and services.
230 func (reg *Registry) ServeMessage(r *http.Request) {
231 if r.Method != methodNotify {
232 return
233 }
234
235 nts := r.Header.Get("nts")
236
237 switch nts {
238 case ntsAlive:
239 reg.handleNTSAlive(r)
240 case ntsUpdate:
241 reg.handleNTSUpdate(r)
242 case ntsByebye:
243 reg.handleNTSByebye(r)
244 }
245 }
246
247 func (reg *Registry) handleNTSAlive(r *http.Request) error {
248 entry, err := newEntryFromRequest(r)
249 if err != nil {
250 return err
251 }
252
253 reg.lock.Lock()
254 reg.byUSN[entry.USN] = entry
255 reg.lock.Unlock()
256
257 reg.sendUpdate(Update{
258 USN: entry.USN,
259 EventType: EventAlive,
260 Entry: entry,
261 })
262
263 return nil
264 }
265
266 func (reg *Registry) handleNTSUpdate(r *http.Request) error {
267 entry, err := newEntryFromRequest(r)
268 if err != nil {
269 return err
270 }
271 nextBootID, err := parseUpnpIntHeader(r.Header, "NEXTBOOTID.UPNP.ORG", -1)
272 if err != nil {
273 return err
274 }
275 entry.BootID = nextBootID
276
277 reg.lock.Lock()
278 reg.byUSN[entry.USN] = entry
279 reg.lock.Unlock()
280
281 reg.sendUpdate(Update{
282 USN: entry.USN,
283 EventType: EventUpdate,
284 Entry: entry,
285 })
286
287 return nil
288 }
289
290 func (reg *Registry) handleNTSByebye(r *http.Request) error {
291 usn := r.Header.Get("USN")
292
293 reg.lock.Lock()
294 entry := reg.byUSN[usn]
295 delete(reg.byUSN, usn)
296 reg.lock.Unlock()
297
298 reg.sendUpdate(Update{
299 USN: usn,
300 EventType: EventByeBye,
301 Entry: entry,
302 })
303
304 return nil
305 }