-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandlerStore.go
More file actions
424 lines (377 loc) · 11.1 KB
/
handlerStore.go
File metadata and controls
424 lines (377 loc) · 11.1 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* ****************************************************************************
* Copyright 2020 51 Degrees Mobile Experts Limited (51degrees.com)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
* ***************************************************************************/
package swift
import (
"encoding/base64"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
// HandlerStore takes a Services pointer and returns a HTTP handler used to
// respond to a storage operation. Should not be assigned to an end point as
// the table name is the first segment of the URL path, and the encrypted
// operation data the second segment. The second optional parameter is used to
// handle responses that do not contain a valid operation request due to data
// corruption.
func HandlerStore(
s *Services,
e func(w http.ResponseWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Extract the operation parameters from the request.
o, err := newOperationFromRequest(s, w, r)
if err != nil {
if e == nil {
storeMalformed(s, w, r)
} else {
e(w, r)
}
return
}
// If the previous node is set then update last accessed time and
// confirm it is alive by virtue of being the previous node.
if o.PrevNode() != nil {
o.prevNodePtr.accessed = time.Now().UTC()
o.prevNodePtr.alive = true
// Update the operation's previous node with this node for the
// next node in the chain.
o.prevNode = o.thisNode.domain
}
// If there are still more nodes to try and the operation is not out of
// time then select the next node.
if o.nodesVisited < o.nodeCount && o.IsTimeStampValid() {
// If this is the penultimate operation in the storage operation
// then go back to the home node that will be the first one in those
// visited to ensure it has the most current copy of the data.
if o.nodesVisited == o.nodeCount-1 {
o.nextNode = o.HomeNode()
}
// If no node is set then find a random storage node that is not the
// home node or the current node. Try 10 times before giving up and
// just using the node found.
if o.nextNode == nil {
c := 10
for o.nextNode == nil && c > 0 {
o.nextNode = o.network.getRandomNode(func(i *node) bool {
return i.role == roleStorage &&
i != o.thisNode &&
i.domain != o.HomeNode().domain &&
i.starts.Before(time.Now().UTC())
})
c--
}
}
// If there is still no node them use the home node.
if o.nextNode == nil {
o.nextNode = o.HomeNode()
}
// If there is still no node then generate an error.
if o.nextNode == nil {
returnServerError(s, w, fmt.Errorf("No next node available"))
return
}
}
if o.nextNode != nil {
// If this is the first node (the home node), the home alone can be
// used if it contains a current version of the values, there are
// values in cookies for all the keys of the operation, and those
// values have not expired meaning the rest of the network does not
// need to be consulted to complete the operation.
if o.nodesVisited == 1 && o.UseHomeNode() && o.getCookiesValid() {
o.storeComplete(s, w, r)
} else if o.done() {
o.storeDone(s, w, r)
} else {
o.storeContinue(s, w, r)
}
} else {
o.storeDone(s, w, r)
}
}
}
// The operation is invalid return a malformed request.
func storeMalformed(s *Services, w http.ResponseWriter, r *http.Request) {
var o operation
o.request = r
o.HTML.BackgroundColor = s.config.BackgroundColor
o.HTML.MessageColor = s.config.MessageColor
sendHTMLTemplate(s, w, malformedTemplate, &o)
}
// If this is the home node and the last operation of a multi node operation
// then validate that cookies are available. If not then a warning will need to
// be shown for non JavaScript operations. Otherwise complete the operation.
func (o *operation) storeDone(
s *Services,
w http.ResponseWriter,
r *http.Request) {
if o.nodeCount > 1 &&
o.done() &&
o.JavaScript() == false &&
o.getAnyCookiesPresent() == false {
o.storeWarning(s, w, r)
} else {
o.storeComplete(s, w, r)
}
}
// storeWarning provides a browser specific warning requesting the user changes
// their settings to support SWIFT.
func (o *operation) storeWarning(
s *Services,
w http.ResponseWriter,
r *http.Request) {
var err error
// The next node after the cookies have been set is the home node. The
// counter and the time stamp will also need to be reset to zero.
o.nextNode = o.HomeNode()
o.nodesVisited = 0
o.timeStamp = time.Now().UTC()
// Get the next URL for the node.
o.nextURL, err = o.getNextURL()
if err != nil {
returnServerError(s, w, err)
return
}
// Send the HTML warning.
sendHTMLTemplate(s, w, warningTemplate, o)
}
// If the post on complete flag is set then use the JavaScript post on complete
// template. If not then use the blank template for the return.
func (o *operation) storeComplete(
s *Services,
w http.ResponseWriter,
r *http.Request) {
if o.PostMessageOnComplete() {
if o.DisplayUserInterface() {
o.storePostMessage(s, w, r, postMessageTemplate)
} else {
o.storePostMessage(s, w, r, postMessageBlankTemplate)
}
} else {
if o.DisplayUserInterface() {
if o.nodesVisited <= 1 {
o.storeReturn(s, w, r, blankTemplate)
} else {
o.storeReturn(s, w, r, progressTemplate)
}
} else {
o.storeReturn(s, w, r, blankTemplate)
}
}
}
func (o *operation) storePostMessage(
s *Services,
w http.ResponseWriter,
r *http.Request,
t *template.Template) {
sendHTMLTemplate(s, w, t, o)
}
func (o *operation) storeReturn(
s *Services,
w http.ResponseWriter,
r *http.Request,
t *template.Template) {
var err error
nu := o.returnURL
// Get the results to append to the end of the return URL.
x, err := o.Results()
if err != nil && s.config.Debug == true {
log.Println(err.Error())
}
nu += x
// Sets cookies for any non empty resolved pairs.
o.setCookies(s, w, r)
// Turn the next URL string into a url.URL value.
o.nextURL, err = url.Parse(nu)
if err != nil {
returnServerError(s, w, err)
return
}
if o.JavaScript() {
o.storeReturnJavaScript(s, w, r)
} else {
o.storeReturnHTML(s, w, r, t)
}
}
func (o *operation) storeReturnHTML(
s *Services,
w http.ResponseWriter,
r *http.Request,
t *template.Template) {
sendHTMLTemplate(s, w, t, o)
}
func (o *operation) storeReturnJavaScript(
s *Services,
w http.ResponseWriter,
r *http.Request) {
sendJSTemplate(s, w, javaScriptReturnTemplate, o)
}
func (o *operation) storeContinue(
s *Services,
w http.ResponseWriter,
r *http.Request) {
var err error
// Get the next URL for the node.
o.nextURL, err = o.getNextURL()
if err != nil {
returnServerError(s, w, err)
return
}
// Sets cookies for any non empty resolved pairs.
o.setCookies(s, w, r)
// Set the preload header to trigger a DNS lookup on the next domain before
// the request to that domain occurs via the navigation change. Only do this
// if the next node is not the home node which will have already been
// visited.
if o.nextNode != o.HomeNode() {
w.Header().Set(
"Link",
fmt.Sprintf("<%s://%s>; rel=preconnect;",
o.nextURL.Scheme,
o.nextURL.Host))
}
if o.JavaScript() {
o.storeContinueJavaScript(s, w, r)
} else {
o.storeContinueHTML(s, w, r)
}
}
func (o *operation) storeContinueHTML(s *Services,
w http.ResponseWriter,
r *http.Request) {
var t *template.Template
if o.DisplayUserInterface() {
t = progressTemplate
} else {
t = blankTemplate
}
sendHTMLTemplate(s, w, t, o)
}
func (o *operation) storeContinueJavaScript(s *Services,
w http.ResponseWriter,
r *http.Request) {
sendJSTemplate(s, w, javaScriptProgressTemplate, o)
}
// setCookies for all the resolved pairs that are not empty. If no cookies are
// written as part of the storage operation because the values are empty then
// set a special cookie used to verify that the browser does support cookies if
// no cookies were included in the request.
func (o *operation) setCookies(
s *Services,
w http.ResponseWriter,
r *http.Request) error {
f := false
for _, p := range o.resolved {
if p.isEmpty() == false {
err := o.setValueInCookie(w, r, p)
if err != nil {
return err
}
f = true
}
}
if f == false && o.getAnyCookiesPresent() == false {
return o.setBrowserWarningCookie(s, w, r)
}
return nil
}
// setBrowserWarningCookie set a cookie to verify cookies are supported. Use a
// single key "t" with no value. We only need to know it's present in the future
// and do not need any values. Expires after a minute.
func (o *operation) setBrowserWarningCookie(
s *Services,
w http.ResponseWriter,
r *http.Request) error {
cookie := http.Cookie{
Name: "t",
Domain: o.getCookieDomain(),
Value: "",
Path: "/",
SameSite: http.SameSiteLaxMode,
Secure: o.services.config.Scheme == "https",
HttpOnly: true,
Expires: time.Now().UTC().Add(time.Minute)}
http.SetCookie(w, &cookie)
return nil
}
func (o *operation) getResults() (string, error) {
// Build the results array of key value pairs.
var r Results
for _, p := range o.resolved {
r.pairs = append(r.pairs, &p.Pair)
}
// Add the expiry time for the results.
r.expires = time.Now().UTC().Add(
o.services.config.StorageOperationTimeoutDuration())
// Add other state information from the storage operation.
r.state = o.state
// Add HTML user interface parameters from the storage operation.
r.HTML = o.HTML
// Encode them as a byte array for encryption.
out, err := encodeResults(&r)
if err != nil {
return "", err
}
// Encrypt the result with the access node.
var u url.URL
u.Scheme = o.services.config.Scheme
u.Host = o.accessNode
u.Path = "/swift/api/v1/encrypt"
q := url.Values{}
q.Set("plain", base64.StdEncoding.EncodeToString(out))
res, err := http.PostForm(u.String(), q)
if err != nil {
return "", err
}
if res.StatusCode != http.StatusOK {
return "", newResponseError(u.String(), res)
}
in, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(in), nil
}
func (o *operation) getNextURL() (*url.URL, error) {
if o.nextNode == nil {
return nil, fmt.Errorf("Next node must be set")
}
p, err := o.asURLParameter()
if err != nil {
return nil, err
}
var u url.URL
u.Scheme = o.services.config.Scheme
u.Host = o.nextNode.domain
u.Path = o.nextNode.scramble(o.table) + "/" + p
if err != nil {
return nil, err
}
return &u, nil
}
func (o *operation) asURLParameter() (string, error) {
b, err := o.asByteArray()
if err != nil {
return "", err
}
e, err := o.nextNode.encode(b)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(e), err
}