Debian Codegraph @

ssdp/ssdp.go

raw symbols SCIP
1 package ssdp
2
3 import (
4 "errors"
5 "log"
6 "net/http"
7 "net/url"
8 "strconv"
9 "time"
10
11 "github.com/huin/goupnp/httpu"
12 )
13
14 const (
15 ssdpDiscover = `"ssdp:discover"`
16 ntsAlive = `ssdp:alive`
17 ntsByebye = `ssdp:byebye`
18 ntsUpdate = `ssdp:update`
19 ssdpUDP4Addr = "239.255.255.250:1900"
20 ssdpSearchPort = 1900
21 methodSearch = "M-SEARCH"
22 methodNotify = "NOTIFY"
23 )
24
25 // SSDPRawSearch performs a fairly raw SSDP search request, and returns the
26 // unique response(s) that it receives. Each response has the requested
27 // searchTarget, a USN, and a valid location. maxWaitSeconds states how long to
28 // wait for responses in seconds, and must be a minimum of 1 (the
29 // implementation waits an additional 100ms for responses to arrive), 2 is a
30 // reasonable value for this. numSends is the number of requests to send - 3 is
31 // a reasonable value for this.
32 func SSDPRawSearch(httpu *httpu.HTTPUClient, searchTarget string, maxWaitSeconds int, numSends int) ([]*http.Response, error) {
33 if maxWaitSeconds < 1 {
34 return nil, errors.New("ssdp: maxWaitSeconds must be >= 1")
35 }
36
37 seenUsns := make(map[string]bool)
38 var responses []*http.Response
39 req := http.Request{
40 Method: methodSearch,
41 // TODO: Support both IPv4 and IPv6.
42 Host: ssdpUDP4Addr,
43 URL: &url.URL{Opaque: "*"},
44 Header: http.Header{
45 // Putting headers in here avoids them being title-cased.
46 // (The UPnP discovery protocol uses case-sensitive headers)
47 "HOST": []string{ssdpUDP4Addr},
48 "MX": []string{strconv.FormatInt(int64(maxWaitSeconds), 10)},
49 "MAN": []string{ssdpDiscover},
50 "ST": []string{searchTarget},
51 },
52 }
53 allResponses, err := httpu.Do(&req, time.Duration(maxWaitSeconds)*time.Second+100*time.Millisecond, numSends)
54 if err != nil {
55 return nil, err
56 }
57 for _, response := range allResponses {
58 if response.StatusCode != 200 {
59 log.Printf("ssdp: got response status code %q in search response", response.Status)
60 continue
61 }
62 if st := response.Header.Get("ST"); st != searchTarget {
63 continue
64 }
65 location, err := response.Location()
66 if err != nil {
67 log.Printf("ssdp: no usable location in search response (discarding): %v", err)
68 continue
69 }
70 usn := response.Header.Get("USN")
71 if usn == "" {
72 log.Printf("ssdp: empty/missing USN in search response (using location instead): %v", err)
73 usn = location.String()
74 }
75 if _, alreadySeen := seenUsns[usn]; !alreadySeen {
76 seenUsns[usn] = true
77 responses = append(responses, response)
78 }
79 }
80
81 return responses, nil
82 }