transport.go 5.84 KB
Newer Older
1
package irma
2
3
4

import (
	"bytes"
5
	"crypto/sha256"
6
	"encoding/json"
7
	"fmt"
8
9
	"io"
	"io/ioutil"
10
	"net"
11
	"net/http"
12
	"path/filepath"
13
14
	"strings"
	"time"
15

16
	"github.com/go-errors/errors"
17
18
	"github.com/hashicorp/go-retryablehttp"

19
	"github.com/privacybydesign/irmago/internal/disable_sigpipe"
20
	"github.com/privacybydesign/irmago/internal/fs"
21
22
)

Sietse Ringers's avatar
Sietse Ringers committed
23
// HTTPTransport sends and receives JSON messages to a HTTP server.
24
type HTTPTransport struct {
Sietse Ringers's avatar
Sietse Ringers committed
25
	Server  string
26
	client  *retryablehttp.Client
Sietse Ringers's avatar
Sietse Ringers committed
27
	headers map[string]string
28
29
}

30
const verbose = false
Sietse Ringers's avatar
Sietse Ringers committed
31

Sietse Ringers's avatar
Sietse Ringers committed
32
// NewHTTPTransport returns a new HTTPTransport.
33
34
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
35
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
36
37
		url += "/"
	}
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

	// Create a transport that dials with a SIGPIPE handler (which is only active on iOS)
	var innerTransport http.Transport

	innerTransport.Dial = func(network, addr string) (c net.Conn, err error) {
		c, err = net.Dial(network, addr)
		if err != nil {
			return c, err
		}
		if err = disable_sigpipe.DisableSigPipe(c); err != nil {
			return c, err
		}
		return c, nil
	}

53
54
55
56
57
58
59
60
61
62
	client := retryablehttp.NewClient()
	client.RetryMax = 3
	client.RetryWaitMin = 100 * time.Millisecond
	client.RetryWaitMax = 500 * time.Millisecond
	client.Logger = nil
	client.HTTPClient = &http.Client{
		Timeout:   time.Second * 5,
		Transport: &innerTransport,
	}

Sietse Ringers's avatar
Sietse Ringers committed
63
64
65
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
66
		client:  client,
Sietse Ringers's avatar
Sietse Ringers committed
67
	}
68
69
}

70
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
71
72
73
74
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

75
76
77
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
78
79
	var req retryablehttp.Request
	req.Request, err = http.NewRequest(method, transport.Server+url, reader)
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}

	req.Header.Set("User-Agent", "irmago")
	if reader != nil {
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
	}
	for name, val := range transport.headers {
		req.Header.Set(name, val)
	}

96
	res, err := transport.client.Do(&req)
97
98
99
100
101
102
103
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}
	return res, nil
}

func (transport *HTTPTransport) jsonRequest(url string, method string, result interface{}, object interface{}) error {
104
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
105
106
107
108
109
110
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

111
	var isstr bool
112
113
	var reader io.Reader
	if object != nil {
114
115
116
117
118
119
		var objstr string
		if objstr, isstr = object.(string); isstr {
			reader = bytes.NewBuffer([]byte(objstr))
		} else {
			marshaled, err := json.Marshal(object)
			if err != nil {
Tomas's avatar
Tomas committed
120
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
121
			}
Sietse Ringers's avatar
Sietse Ringers committed
122
			if verbose {
123
				fmt.Printf("%s %s: %s\n", method, url, string(marshaled))
Sietse Ringers's avatar
Sietse Ringers committed
124
			}
125
			reader = bytes.NewBuffer(marshaled)
126
		}
127
128
129
130
	} else {
		if verbose {
			fmt.Printf("%s %s\n", method, url)
		}
131
132
	}

133
	res, err := transport.request(url, method, reader, isstr)
134
	if err != nil {
135
		return err
136
	}
137
138
139
140
	if method == http.MethodDelete {
		return nil
	}

141
142
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
143
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
144
145
	}
	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
146
		apierr := &RemoteError{}
Sietse Ringers's avatar
Sietse Ringers committed
147
148
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
Tomas's avatar
Tomas committed
149
			return &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
150
		}
Sietse Ringers's avatar
Sietse Ringers committed
151
152
153
		if verbose {
			fmt.Printf("ERROR: %+v\n", apierr)
		}
Tomas's avatar
Tomas committed
154
		return &SessionError{ErrorType: ErrorApi, RemoteStatus: res.StatusCode, RemoteError: apierr}
155
156
	}

Sietse Ringers's avatar
Sietse Ringers committed
157
158
159
	if verbose {
		fmt.Printf("RESPONSE: %s\n", string(body))
	}
160
161
162
163
164
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
Tomas's avatar
Tomas committed
165
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
166
		}
167
168
169
170
171
	}

	return nil
}

172
173
174
175
176
func (transport *HTTPTransport) GetBytes(url string) ([]byte, error) {
	res, err := transport.request(url, http.MethodGet, nil, false)
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}
177
178

	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
179
		return nil, &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
180
	}
181
182
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
183
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
184
185
186
187
	}
	return b, nil
}

188
func (transport *HTTPTransport) GetSignedFile(url string, dest string, hash ConfigurationFileHash) error {
189
190
191
192
	b, err := transport.GetBytes(url)
	if err != nil {
		return err
	}
193
194
195
196
	sha := sha256.Sum256(b)
	if hash != nil && !bytes.Equal(hash, sha[:]) {
		return errors.Errorf("Signature over new file %s is not valid", dest)
	}
197
	if err = fs.EnsureDirectoryExists(filepath.Dir(dest)); err != nil {
198
199
		return err
	}
200
	return fs.SaveFile(dest, b)
201
202
}

203
204
205
206
func (transport *HTTPTransport) GetFile(url string, dest string) error {
	return transport.GetSignedFile(url, dest, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
207
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
208
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
209
	return transport.jsonRequest(url, http.MethodPost, result, object)
210
211
}

Sietse Ringers's avatar
Sietse Ringers committed
212
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
213
func (transport *HTTPTransport) Get(url string, result interface{}) error {
214
	return transport.jsonRequest(url, http.MethodGet, result, nil)
215
216
}

Sietse Ringers's avatar
Sietse Ringers committed
217
// Delete performs a DELETE.
218
func (transport *HTTPTransport) Delete() {
219
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
220
}