-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.go
95 lines (82 loc) · 2.39 KB
/
connection.go
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
package main
import (
"encoding/base64"
"errors"
"github.com/headzoo/surf"
"github.com/headzoo/surf/browser"
"net/url"
"os"
"path/filepath"
"strings"
)
func download(params Params) (string, error) {
/* 1. Prepare the local file */
// Create a name for the local filename so we exit now instead after
// the download of a big file
var filename string
if params.File == "" {
uri, err := url.Parse(params.Url)
if err != nil {
return "", errors.New("URL can not be parsed")
}
parts := strings.Split(uri.Path, "/")
filename = filepath.FromSlash(params.Dir + "/" + parts[len(parts)-1])
} else {
filename = params.File
}
// Create the local file
file, err := os.Create(filename)
if err != nil {
return "", errors.New("Can not create local file")
}
/* 2. Prepare the request */
bow := surf.NewBrowser()
bow.SetUserAgent("shibdl/" + defaults.Version)
/* 3. Open the url with the file to be downloaded */
err = bow.Open(params.Url)
if err != nil {
return "", errors.New("Connection failed")
}
/* 4. Add credentials for basic authentication */
// ref https://wiki.shibboleth.net/confluence/display/IDP30/PasswordAuthnConfiguration#PasswordAuthnConfiguration-UserInterface
// "The first user interface layer of the flow is actually HTTP Basic authentication;
// if a header with credentials is supplied, the credentials are tested immediately with no prompting."
bow.AddRequestHeader("Authorization", "Basic "+basicAuth(params.User, params.Password))
/* 5. Keep submitting login forms */
err = sendForms(bow, defaults.MaxForms)
if err != nil {
return "", err
}
/* 6. Clean-up secrets */
bow.DelRequestHeader("Authorization")
/* 7. Download the file */
_, err = bow.Download(file)
if err != nil {
os.Remove(filename)
return "", errors.New("Can not download the file")
}
return filename, nil
}
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func sendForms(browser *browser.Browser, maxForms int) error {
formsCounter := 0
for {
formsCounter += 1
if formsCounter >= maxForms {
return errors.New("Failed to login (maximal login forms reached)")
break
}
if len(browser.Forms()) >= 1 {
form := browser.Forms()[1]
if form != nil && form.Submit() != nil {
return errors.New("Failed to send the Shibboleth login form")
}
} else {
break
}
}
return nil
}