summaryrefslogtreecommitdiffstats
path: root/response.go
blob: 4c3f7536aab595cdf4b463f94ad45546dc641916 (plain)
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package cnp

import (
	"bytes"
	"io"
	"strings"
	"time"
)

// Response represents a CNP response message.
type Response struct {
	Message
}

// NewResponse creates a new Response from a response intent and optional body
// data.
func NewResponse(intent string, body []byte) (resp *Response, err error) {
	var r io.Reader
	if body != nil {
		r = bytes.NewReader(body)
	}
	resp = &Response{*NewMessage("", r)}
	err = resp.SetResponseIntent(intent)
	return
}

var responseIntents = map[string]bool{
	IntentOK:          true,
	IntentNotModified: true,
	IntentRedirect:    true,
	IntentError:       true,
}

// ParseResponse parses a response message.
func ParseResponse(r io.Reader) (*Response, error) {
	msg, err := ParseMessage(r)
	if msg == nil {
		return nil, err
	}
	return &Response{*msg}, err
}

// ResponseIntent retrieves the response intent.
// If the intent is unknown, the "error" intent is returned.
func (r *Response) ResponseIntent() string {
	s := r.Intent()
	if !responseIntents[s] {
		return IntentError
	}
	return s
}

// SetResponseIntent sets the response intent.
// If the provided intent is not a known response intent, an error is returned
// and the intent is set to "error".
func (r *Response) SetResponseIntent(intent string) error {
	if !responseIntents[intent] {
		r.SetIntent(IntentError)
		return ErrorInvalid{"invalid response: unknown response intent"}
	}
	r.SetIntent(intent)
	return nil
}

// Name retrieves the name response parameter.
//
// If the name response parameter is not a valid filename, an empty string is
// returned.
func (r *Response) Name() string {
	name, err := getFilename(&r.Message, "name")
	if err != nil {
		return ""
	}
	return name
}

// SetName sets the name response parameter.
//
// Returns an error if the name includes characters not valid in a filename
// (slash, null byte).
func (r *Response) SetName(name string) error {
	return setFilename(&r.Message, "name", name)
}

// Type retrieves the type response parameter.
//
// If the type response parameter is invalid or empty, the default value
// "application/octet-stream" is returned.
func (r *Response) Type() string {
	typ, _ := getType(&r.Message, "type")
	return typ
}

// SetType sets the type response parameter.
//
// Returns an error if typ is not a valid format for a MIME type.
func (r *Response) SetType(typ string) error {
	return setType(&r.Message, "type", typ)
}

// Time retrieves the time response parameter.
//
// If the parameter isn't a valid RFC3339 timestamp, a zero time.Time is
// returned.
func (r *Response) Time() time.Time {
	t, err := getTime(&r.Message, "time")
	if err != nil {
		return time.Time{}
	}
	return t
}

// SetTime sets the time response parameter.
//
// If t is the zero time value, the time parameter is unset.
func (r *Response) SetTime(t time.Time) {
	setTime(&r.Message, "time", t)
}

// Modified retrieves the modified Response parameter.
//
// If the parameter isn't a valid RFC3339 timestamp, a zero time.Time is
// returned.
func (r *Response) Modified() time.Time {
	t, err := getTime(&r.Message, "modified")
	if err != nil {
		return time.Time{}
	}
	return t
}

// SetModified sets the modified response parameter.
//
// If t is the zero time value, the modified parameter is unset. Otherwise, if
// the time response parameter is empty, it's set to the current time.
func (r *Response) SetModified(t time.Time) {
	setTime(&r.Message, "modified", t)
	if !t.IsZero() && r.Time().IsZero() {
		r.SetTime(time.Now())
	}
}

// Location retrieves the host and path from the location response
// parameter.
//
// If the location parameter is empty, it returns empty host and path. If the
// location parameter is invalid, an error is returned.
func (r *Response) Location() (host, path string, err error) {
	l := r.Param("location")
	if l == "" {
		return "", "", nil
	}
	if err := validateRequestIntent(l); err != nil {
		return "", "", err
	}
	ss := strings.SplitN(l, "/", 2)
	return ss[0], "/" + ss[1], nil
}

// SetLocation sets the location response parameter to host and path.
//
// Returns an error if the host or path are invalid.
func (r *Response) SetLocation(host, path string) error {
	err := ErrorInvalid{"invalid response: invalid location parameter"}
	if strings.ContainsRune(host, '/') {
		return err
	}
	l := host + path
	if err := validateRequestIntent(l); err != nil {
		return err
	}
	r.SetParam("location", l)
	return nil
}

var responseErrorReasons = map[string]bool{
	ReasonSyntax:       true,
	ReasonVersion:      true,
	ReasonInvalid:      true,
	ReasonNotSupported: true,
	ReasonTooLarge:     true,
	ReasonNotFound:     true,
	ReasonDenied:       true,
	ReasonRejected:     true,
	ReasonServerError:  true,
	"":                 true,
}

// Reason retrieves the reason response parameter.
//
// If the reason is nonempty and unknown, "server_error" is returned.
func (r *Response) Reason() string {
	reason := r.Param("reason")
	if _, ok := responseErrorReasons[reason]; ok {
		return reason
	}
	return ReasonServerError
}

// SetReason sets the reason response parameter.
//
// If the reason is nonempty and unknown, it sets "server_error" instead.
func (r *Response) SetReason(reason string) error {
	if _, ok := responseErrorReasons[reason]; !ok {
		r.SetParam("reason", ReasonServerError)
		return ErrorInvalid{"invalid response: unknown error reason"}
	}
	r.SetParam("reason", reason)
	return nil
}

// Select retrieves the select response parameter.
//
// If the parameter isn't a valid selector, empty strings are returned.
func (r *Response) Select() (selector, query string) {
	selector, query, _ = getSelect(&r.Message, "select")
	return
}

// SetSelect sets the select response parameter.
//
// If the selector name is empty, the select parameter is unset.
func (r *Response) SetSelect(selector, query string) error {
	return setSelect(&r.Message, "select", selector, query)
}

// Length gets the length response parameter (or -1 if it's not set or invalid).
func (r *Response) Length() int64 {
	n, err := getInt(&r.Message, "length", -1)
	if err != nil {
		return -1
	}
	return n
}

// SetLength sets the length response parameter to n.
//
// If negative, the parameter is unset.
func (r *Response) SetLength(n int64) {
	if n < 0 {
		r.SetParam("length", "")
	} else {
		setInt(&r.Message, "length", n)
	}
}

// Validate validates the response intent and header parameter value format
// (length, name, type, time, modified, location, reason, select)
func (r *Response) Validate() error {
	if !responseIntents[r.Intent()] {
		return ErrorInvalid{"invalid response: unknown response intent"}
	}
	if err := r.Message.Validate(); err != nil {
		return err
	}
	if _, err := getFilename(&r.Message, "name"); err != nil {
		return err
	}
	if _, err := getType(&r.Message, "type"); err != nil {
		return err
	}
	if _, err := getTime(&r.Message, "time"); err != nil {
		return err
	}
	if _, err := getTime(&r.Message, "modified"); err != nil {
		return err
	}
	if h, p, err := r.Location(); err != nil {
		return err
	} else if r.ResponseIntent() == IntentRedirect && h == "" && p == "" {
		return ErrorInvalid{"invalid response: redirect response needs location parameter"}
	}
	if !responseErrorReasons[r.Param("reason")] {
		return ErrorInvalid{"invalid response: unknown error reason"}
	}
	if _, _, err := getSelect(&r.Message, "select"); err != nil {
		return err
	}
	return nil
}

// Write writes the response to w.
func (r *Response) Write(w io.Writer) error {
	if _, ok := r.Header.Parameters["length"]; !ok {
		r.TryComputeLength()
	}
	return r.Message.Write(w)
}