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

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

15
	"github.com/privacybydesign/irmago/internal/disable_sigpipe"
16
	"github.com/privacybydesign/irmago/internal/fs"
17
18
)

Sietse Ringers's avatar
Sietse Ringers committed
19
// HTTPTransport sends and receives JSON messages to a HTTP server.
20
type HTTPTransport struct {
Sietse Ringers's avatar
Sietse Ringers committed
21
22
23
	Server  string
	client  *http.Client
	headers map[string]string
24
25
}

26
const verbose = false
Sietse Ringers's avatar
Sietse Ringers committed
27

Sietse Ringers's avatar
Sietse Ringers committed
28
// NewHTTPTransport returns a new HTTPTransport.
29
30
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
31
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
32
33
		url += "/"
	}
34
35

	transport := &HTTPTransport{
Sietse Ringers's avatar
Sietse Ringers committed
36
37
		Server:  url,
		headers: map[string]string{},
38
		client: &http.Client{
Sietse Ringers's avatar
Sietse Ringers committed
39
			Timeout: time.Second * 15,
40
41
		},
	}
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

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

	transport.client.Transport = &innerTransport

	return transport
60
61
}

62
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
63
64
65
66
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

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
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
	req, err := http.NewRequest(method, transport.Server+url, reader)
	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)
	}

	res, err := transport.client.Do(req)
	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 {
95
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
96
97
98
99
100
101
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

102
	var isstr bool
103
104
	var reader io.Reader
	if object != nil {
105
106
107
108
109
110
		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
111
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
112
			}
Sietse Ringers's avatar
Sietse Ringers committed
113
			if verbose {
114
				fmt.Printf("%s %s: %s\n", method, url, string(marshaled))
Sietse Ringers's avatar
Sietse Ringers committed
115
			}
116
			reader = bytes.NewBuffer(marshaled)
117
		}
118
119
120
121
	} else {
		if verbose {
			fmt.Printf("%s %s\n", method, url)
		}
122
123
	}

124
	res, err := transport.request(url, method, reader, isstr)
125
	if err != nil {
126
		return err
127
	}
128
129
130
131
	if method == http.MethodDelete {
		return nil
	}

132
133
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
134
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode, StatusMessage: res.Status}
135
136
137
	}
	if res.StatusCode != 200 {
		apierr := &ApiError{}
Sietse Ringers's avatar
Sietse Ringers committed
138
139
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
140
			return &SessionError{ErrorType: ErrorServerResponse, Status: res.StatusCode, StatusMessage: res.Status}
141
		}
Sietse Ringers's avatar
Sietse Ringers committed
142
143
144
		if verbose {
			fmt.Printf("ERROR: %+v\n", apierr)
		}
145
		return &SessionError{ErrorType: ErrorApi, Status: res.StatusCode, ApiError: apierr, StatusMessage: res.Status}
146
147
	}

Sietse Ringers's avatar
Sietse Ringers committed
148
149
150
	if verbose {
		fmt.Printf("RESPONSE: %s\n", string(body))
	}
151
152
153
154
155
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
156
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode, StatusMessage: res.Status}
157
		}
158
159
160
161
162
	}

	return nil
}

163
164
165
166
167
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}
	}
168
169
170
171

	if res.StatusCode != 200 {
		return nil, &SessionError{ErrorType: ErrorServerResponse, Status: res.StatusCode}
	}
172
173
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
174
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode, StatusMessage: res.Status}
175
176
177
178
179
180
181
182
183
	}
	return b, nil
}

func (transport *HTTPTransport) GetFile(url string, dest string) error {
	b, err := transport.GetBytes(url)
	if err != nil {
		return err
	}
184
	if err = fs.EnsureDirectoryExists(filepath.Dir(dest)); err != nil {
185
186
		return err
	}
187
	return fs.SaveFile(dest, b)
188
189
}

Sietse Ringers's avatar
Sietse Ringers committed
190
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
191
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
192
	return transport.jsonRequest(url, http.MethodPost, result, object)
193
194
}

Sietse Ringers's avatar
Sietse Ringers committed
195
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
196
func (transport *HTTPTransport) Get(url string, result interface{}) error {
197
	return transport.jsonRequest(url, http.MethodGet, result, nil)
198
199
}

Sietse Ringers's avatar
Sietse Ringers committed
200
// Delete performs a DELETE.
201
func (transport *HTTPTransport) Delete() {
202
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
203
}