Debian Codegraph @

goupnp/ssdp/ssdp.go

raw symbols SCIP
1 package ssdp
2
3 import (
4 "context"
5 "errors"
6 "net/http"
7 "net/url"
8 "strconv"
9 "time"
10
11 "github.com/NebulousLabs/go-upnp/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 is deprecated; use SSDPRawSearchCtx instead
26 func SSDPRawSearch(httpu *httpu.HTTPUClient, searchTarget string, maxWaitSeconds int, numSends int) ([]*http.Response, error) {
27 return SSDPRawSearchCtx(context.Background(), httpu, searchTarget, maxWaitSeconds, numSends)
28 }
29
30 // SSDPRawSearch performs a fairly raw SSDP search request, and returns the
31 // unique response(s) that it receives. Each response has the requested
32 // searchTarget, a USN, and a valid location. maxWaitSeconds states how long to
33 // wait for responses in seconds, and must be a minimum of 1 (the
34 // implementation waits an additional 100ms for responses to arrive), 2 is a
35 // reasonable value for this. numSends is the number of requests to send - 3 is
36 // a reasonable value for this.
37 func SSDPRawSearchCtx(ctx context.Context, httpu *httpu.HTTPUClient, searchTarget string, maxWaitSeconds int, numSends int) ([]*http.Response, error) {
38 if maxWaitSeconds < 1 {
39 return nil, errors.New("ssdp: maxWaitSeconds must be >= 1")
40 }
41
42 seenUsns := make(map[string]bool)
43 var responses []*http.Response
44 req := (&http.Request{
45 Method: methodSearch,
46 // TODO: Support both IPv4 and IPv6.
47 Host: ssdpUDP4Addr,
48 URL: &url.URL{Opaque: "*"},
49 Header: http.Header{
50 // Putting headers in here avoids them being title-cased.
51 // (The UPnP discovery protocol uses case-sensitive headers)
52 "HOST": []string{ssdpUDP4Addr},
53 "MX": []string{strconv.FormatInt(int64(maxWaitSeconds), 10)},
54 "MAN": []string{ssdpDiscover},
55 "ST": []string{searchTarget},
56 },
57 }).WithContext(ctx)
58 allResponses, err := httpu.Do(req, time.Duration(maxWaitSeconds)*time.Second+100*time.Millisecond, numSends)
59 if err != nil {
60 return nil, err
61 }
62 for _, response := range allResponses {
63 if response.StatusCode != 200 {
64 continue
65 }
66 if st := response.Header.Get("ST"); st != searchTarget {
67 continue
68 }
69 location, err := response.Location()
70 if err != nil {
71 continue
72 }
73 usn := response.Header.Get("USN")
74 if usn == "" {
75 usn = location.String()
76 }
77 if _, alreadySeen := seenUsns[usn]; !alreadySeen {
78 seenUsns[usn] = true
79 responses = append(responses, response)
80 }
81 }
82
83 return responses, nil
84 }