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

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

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

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

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

32
33
// 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
34

35
36
37
var transportlogger *log.Logger

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

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

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

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

70
71
72
73
74
75
	client := &retryablehttp.Client{
		Logger:       transportlogger,
		RetryWaitMin: 100 * time.Millisecond,
		RetryWaitMax: 200 * time.Millisecond,
		RetryMax:     2,
		Backoff:      retryablehttp.DefaultBackoff,
76
		CheckRetry: func(ctx context.Context, resp *http.Response, err error) (bool, error) {
77
78
79
80
81
82
83
			// Don't retry on 5xx (which retryablehttp does by default)
			return err != nil || resp.StatusCode == 0, err
		},
		HTTPClient: &http.Client{
			Timeout:   time.Second * 3,
			Transport: &innerTransport,
		},
84
85
	}

Sietse Ringers's avatar
Sietse Ringers committed
86
87
88
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
89
		client:  client,
Sietse Ringers's avatar
Sietse Ringers committed
90
	}
91
92
}

93
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
94
95
96
97
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

98
99
100
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
101
102
	var req retryablehttp.Request
	req.Request, err = http.NewRequest(method, transport.Server+url, reader)
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
	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)
	}

119
	res, err := transport.client.Do(&req)
120
121
122
123
124
125
126
	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 {
127
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
128
129
130
131
132
133
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

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

151
	res, err := transport.request(url, method, reader, isstr)
152
	if err != nil {
153
		return err
154
	}
155
156
157
158
	if method == http.MethodDelete {
		return nil
	}

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

173
	Logger.Tracef("transport: response: %s", string(body))
174
175
176
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
177
		err = UnmarshalValidate(body, result)
178
		if err != nil {
Tomas's avatar
Tomas committed
179
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
180
		}
181
182
183
184
185
	}

	return nil
}

186
187
188
189
190
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}
	}
191
192

	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
193
		return nil, &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
194
	}
195
196
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
197
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
198
199
200
201
	}
	return b, nil
}

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

217
218
219
220
func (transport *HTTPTransport) GetFile(url string, dest string) error {
	return transport.GetSignedFile(url, dest, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
221
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
222
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
223
	return transport.jsonRequest(url, http.MethodPost, result, object)
224
225
}

Sietse Ringers's avatar
Sietse Ringers committed
226
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
227
func (transport *HTTPTransport) Get(url string, result interface{}) error {
228
	return transport.jsonRequest(url, http.MethodGet, result, nil)
229
230
}

Sietse Ringers's avatar
Sietse Ringers committed
231
// Delete performs a DELETE.
232
func (transport *HTTPTransport) Delete() {
233
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
234
}