Debian Codegraph @

ssdp/registry.go

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