transport.go 5.99 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
	"log"
11
	"net"
12
	"net/http"
13
	"os"
14
	"path/filepath"
15
16
	"strings"
	"time"
17

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

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
const verbose = false
Sietse Ringers's avatar
Sietse Ringers committed
33

34
35
36
37
38
39
40
41
var transportlogger *log.Logger

func init() {
	if verbose {
		transportlogger = log.New(os.Stdout, "transport: ", 0)
	}
}

Sietse Ringers's avatar
Sietse Ringers committed
42
// NewHTTPTransport returns a new HTTPTransport.
43
44
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
45
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
46
47
		url += "/"
	}
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

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

63
64
65
66
	client := retryablehttp.NewClient()
	client.RetryMax = 3
	client.RetryWaitMin = 100 * time.Millisecond
	client.RetryWaitMax = 500 * time.Millisecond
67
	client.Logger = transportlogger
68
69
70
71
72
	client.HTTPClient = &http.Client{
		Timeout:   time.Second * 5,
		Transport: &innerTransport,
	}

Sietse Ringers's avatar
Sietse Ringers committed
73
74
75
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
76
		client:  client,
Sietse Ringers's avatar
Sietse Ringers committed
77
	}
78
79
}

80
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
81
82
83
84
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

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

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

121
	var isstr bool
122
123
	var reader io.Reader
	if object != nil {
124
125
126
127
128
129
		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
130
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
131
			}
Sietse Ringers's avatar
Sietse Ringers committed
132
			if verbose {
133
				fmt.Printf("%s %s: %s\n", method, url, string(marshaled))
Sietse Ringers's avatar
Sietse Ringers committed
134
			}
135
			reader = bytes.NewBuffer(marshaled)
136
		}
137
138
139
140
	} else {
		if verbose {
			fmt.Printf("%s %s\n", method, url)
		}
141
142
	}

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

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

Sietse Ringers's avatar
Sietse Ringers committed
167
168
169
	if verbose {
		fmt.Printf("RESPONSE: %s\n", string(body))
	}
170
171
172
173
174
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
Tomas's avatar
Tomas committed
175
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
176
		}
177
178
179
180
181
	}

	return nil
}

182
183
184
185
186
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}
	}
187
188

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

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

213
214
215
216
func (transport *HTTPTransport) GetFile(url string, dest string) error {
	return transport.GetSignedFile(url, dest, nil)
}

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

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

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