| 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 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 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 |
|
| 42 |
Host: ssdpUDP4Addr, |
| 43 |
URL: &url.URL{Opaque: "*"}, |
| 44 |
Header: http.Header{ |
| 45 |
|
| 46 |
|
| 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 |
} |