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

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

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

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

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

31
32
// Logger is used for logging. If not set, init() will initialize it to logrus.StandardLogger().
var Logger *logrus.Logger
Sietse Ringers's avatar
Sietse Ringers committed
33

34
35
36
var transportlogger *log.Logger

func init() {
37
38
	if Logger == nil {
		Logger = logrus.StandardLogger()
39
40
41
	}
}

Sietse Ringers's avatar
Sietse Ringers committed
42
// NewHTTPTransport returns a new HTTPTransport.
43
func NewHTTPTransport(serverURL string) *HTTPTransport {
44
45
	if Logger.IsLevelEnabled(logrus.TraceLevel) {
		transportlogger = log.New(Logger.WriterLevel(logrus.TraceLevel), "transport: ", 0)
46
47
	} else {
		transportlogger = log.New(ioutil.Discard, "", 0)
48
49
	}

50
	url := serverURL
51
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
52
53
		url += "/"
	}
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

	// 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
	}

69
70
71
72
	client := retryablehttp.NewClient()
	client.RetryMax = 3
	client.RetryWaitMin = 100 * time.Millisecond
	client.RetryWaitMax = 500 * time.Millisecond
73
	client.Logger = transportlogger
74
75
76
77
78
	client.HTTPClient = &http.Client{
		Timeout:   time.Second * 5,
		Transport: &innerTransport,
	}

Sietse Ringers's avatar
Sietse Ringers committed
79
80
81
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
82
		client:  client,
Sietse Ringers's avatar
Sietse Ringers committed
83
	}
84
85
}

86
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
87
88
89
90
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

91
92
93
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
94
95
	var req retryablehttp.Request
	req.Request, err = http.NewRequest(method, transport.Server+url, reader)
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
	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)
	}

112
	res, err := transport.client.Do(&req)
113
114
115
116
117
118
119
	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 {
120
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
121
122
123
124
125
126
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

127
	var isstr bool
128
129
	var reader io.Reader
	if object != nil {
130
131
		var objstr string
		if objstr, isstr = object.(string); isstr {
132
			Logger.Trace("transport: body: ", objstr)
133
134
135
136
			reader = bytes.NewBuffer([]byte(objstr))
		} else {
			marshaled, err := json.Marshal(object)
			if err != nil {
Tomas's avatar
Tomas committed
137
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
138
			}
139
			Logger.Trace("transport: body: ", string(marshaled))
140
			reader = bytes.NewBuffer(marshaled)
141
142
143
		}
	}

144
	res, err := transport.request(url, method, reader, isstr)
145
	if err != nil {
146
		return err
147
	}
148
149
150
151
	if method == http.MethodDelete {
		return nil
	}

152
153
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
154
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
155
156
	}
	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
157
		apierr := &RemoteError{}
Sietse Ringers's avatar
Sietse Ringers committed
158
159
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
Tomas's avatar
Tomas committed
160
			return &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
161
		}
162
		Logger.Tracef("transport: error: %+v", apierr)
Tomas's avatar
Tomas committed
163
		return &SessionError{ErrorType: ErrorApi, RemoteStatus: res.StatusCode, RemoteError: apierr}
164
165
	}

166
	Logger.Tracef("transport: response: %s", string(body))
167
168
169
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
170
		err = UnmarshalValidate(body, result)
171
		if err != nil {
Tomas's avatar
Tomas committed
172
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
173
		}
174
175
176
177
178
	}

	return nil
}

179
180
181
182
183
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}
	}
184
185

	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
186
		return nil, &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
187
	}
188
189
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
190
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
191
192
193
194
	}
	return b, nil
}

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

210
211
212
213
func (transport *HTTPTransport) GetFile(url string, dest string) error {
	return transport.GetSignedFile(url, dest, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
214
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
215
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
216
	return transport.jsonRequest(url, http.MethodPost, result, object)
217
218
}

Sietse Ringers's avatar
Sietse Ringers committed
219
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
220
func (transport *HTTPTransport) Get(url string, result interface{}) error {
221
	return transport.jsonRequest(url, http.MethodGet, result, nil)
222
223
}

Sietse Ringers's avatar
Sietse Ringers committed
224
// Delete performs a DELETE.
225
func (transport *HTTPTransport) Delete() {
226
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
227
}