aboutsummaryrefslogtreecommitdiffstats
path: root/Godeps/_workspace/src/github.com/fjl/goupnp/ssdp/registry.go
blob: 9e2611b7f6f6eda641b47fa3289d6530cad5ca55 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package ssdp

import (
    "fmt"
    "log"
    "net/http"
    "net/url"
    "regexp"
    "strconv"
    "sync"
    "time"

    "github.com/fjl/goupnp/httpu"
)

const (
    maxExpiryTimeSeconds = 24 * 60 * 60
)

var (
    maxAgeRx = regexp.MustCompile("max-age=([0-9]+)")
)

type Entry struct {
    // The address that the entry data was actually received from.
    RemoteAddr string
    // Unique Service Name. Identifies a unique instance of a device or service.
    USN string
    // Notfication Type. The type of device or service being announced.
    NT string
    // Server's self-identifying string.
    Server string
    Host   string
    // Location of the UPnP root device description.
    Location *url.URL

    // Despite BOOTID,CONFIGID being required fields, apparently they are not
    // always set by devices. Set to -1 if not present.

    BootID   int32
    ConfigID int32

    SearchPort uint16

    // When the last update was received for this entry identified by this USN.
    LastUpdate time.Time
    // When the last update's cached values are advised to expire.
    CacheExpiry time.Time
}

func newEntryFromRequest(r *http.Request) (*Entry, error) {
    now := time.Now()
    expiryDuration, err := parseCacheControlMaxAge(r.Header.Get("CACHE-CONTROL"))
    if err != nil {
        return nil, fmt.Errorf("ssdp: error parsing CACHE-CONTROL max age: %v", err)
    }

    loc, err := url.Parse(r.Header.Get("LOCATION"))
    if err != nil {
        return nil, fmt.Errorf("ssdp: error parsing entry Location URL: %v", err)
    }

    bootID, err := parseUpnpIntHeader(r.Header, "BOOTID.UPNP.ORG", -1)
    if err != nil {
        return nil, err
    }
    configID, err := parseUpnpIntHeader(r.Header, "CONFIGID.UPNP.ORG", -1)
    if err != nil {
        return nil, err
    }
    searchPort, err := parseUpnpIntHeader(r.Header, "SEARCHPORT.UPNP.ORG", ssdpSearchPort)
    if err != nil {
        return nil, err
    }

    if searchPort < 1 || searchPort > 65535 {
        return nil, fmt.Errorf("ssdp: search port %d is out of range", searchPort)
    }

    return &Entry{
        RemoteAddr:  r.RemoteAddr,
        USN:         r.Header.Get("USN"),
        NT:          r.Header.Get("NT"),
        Server:      r.Header.Get("SERVER"),
        Host:        r.Header.Get("HOST"),
        Location:    loc,
        BootID:      bootID,
        ConfigID:    configID,
        SearchPort:  uint16(searchPort),
        LastUpdate:  now,
        CacheExpiry: now.Add(expiryDuration),
    }, nil
}

func parseCacheControlMaxAge(cc string) (time.Duration, error) {
    matches := maxAgeRx.FindStringSubmatch(cc)
    if len(matches) != 2 {
        return 0, fmt.Errorf("did not find exactly one max-age in cache control header: %q", cc)
    }
    expirySeconds, err := strconv.ParseInt(matches[1], 10, 16)
    if err != nil {
        return 0, err
    }
    if expirySeconds < 1 || expirySeconds > maxExpiryTimeSeconds {
        return 0, fmt.Errorf("rejecting bad expiry time of %d seconds", expirySeconds)
    }
    return time.Duration(expirySeconds) * time.Second, nil
}

// parseUpnpIntHeader is intended to parse the
// {BOOT,CONFIGID,SEARCHPORT}.UPNP.ORG header fields. It returns the def if
// the head is empty or missing.
func parseUpnpIntHeader(headers http.Header, headerName string, def int32) (int32, error) {
    s := headers.Get(headerName)
    if s == "" {
        return def, nil
    }
    v, err := strconv.ParseInt(s, 10, 32)
    if err != nil {
        return 0, fmt.Errorf("ssdp: could not parse header %s: %v", headerName, err)
    }
    return int32(v), nil
}

var _ httpu.Handler = new(Registry)

// Registry maintains knowledge of discovered devices and services.
type Registry struct {
    lock  sync.Mutex
    byUSN map[string]*Entry
}

func NewRegistry() *Registry {
    return &Registry{
        byUSN: make(map[string]*Entry),
    }
}

// ServeMessage implements httpu.Handler, and uses SSDP NOTIFY requests to
// maintain the registry of devices and services.
func (reg *Registry) ServeMessage(r *http.Request) {
    if r.Method != methodNotify {
        return
    }

    nts := r.Header.Get("nts")

    var err error
    switch nts {
    case ntsAlive:
        err = reg.handleNTSAlive(r)
    case ntsUpdate:
        err = reg.handleNTSUpdate(r)
    case ntsByebye:
        err = reg.handleNTSByebye(r)
    default:
        err = fmt.Errorf("unknown NTS value: %q", nts)
    }
    log.Printf("In %s request from %s: %v", nts, r.RemoteAddr, err)
}

func (reg *Registry) handleNTSAlive(r *http.Request) error {
    entry, err := newEntryFromRequest(r)
    if err != nil {
        return err
    }

    reg.lock.Lock()
    defer reg.lock.Unlock()

    reg.byUSN[entry.USN] = entry

    return nil
}

func (reg *Registry) handleNTSUpdate(r *http.Request) error {
    entry, err := newEntryFromRequest(r)
    if err != nil {
        return err
    }
    nextBootID, err := parseUpnpIntHeader(r.Header, "NEXTBOOTID.UPNP.ORG", -1)
    if err != nil {
        return err
    }
    entry.BootID = nextBootID

    reg.lock.Lock()
    defer reg.lock.Unlock()

    reg.byUSN[entry.USN] = entry

    return nil
}

func (reg *Registry) handleNTSByebye(r *http.Request) error {
    reg.lock.Lock()
    defer reg.lock.Unlock()

    delete(reg.byUSN, r.Header.Get("USN"))

    return nil
}