aboutsummaryrefslogtreecommitdiff
path: root/request.go
blob: 2834b3a134c86f724f91db884e5059b3b5baf218 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/******************************************************************************
*
*  Copyright 2018 Stefan Majewsky <majewsky@gmx.net>
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
******************************************************************************/

package schwift

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"

	"github.com/gophercloud/gophercloud"
)

var okCodes []int

func init() {
	//prepare input for gophercloud.RequestOpts.OkCodes such that gophercloud's
	//error handling is fused
	for code := 100; code < 600; code++ {
		//as an exception, 401s are handled by Gophercloud because we want to use its
		//internal token renewal logic
		if code != 401 {
			okCodes = append(okCodes, code)
		}
	}
}

//RequestOptions contains additional headers and values for a request.
type RequestOptions struct {
	Values url.Values
}

func cloneRequestOptions(orig *RequestOptions) *RequestOptions {
	result := RequestOptions{
		Values: make(url.Values),
	}
	if orig != nil {
		for k, v := range orig.Values {
			result.Values[k] = v
		}
	}
	return &result
}

//Request contains the parameters that can be set in a request to the Swift API.
type Request struct {
	Method        string //"GET", "HEAD", "PUT", "POST" or "DELETE"
	ContainerName string //empty for requests on accounts
	ObjectName    string //empty for requests on accounts/containers
	Headers       http.Header
	Options       *RequestOptions
	Body          io.Reader
	//ExpectStatusCodes can be left empty to disable this check, otherwise
	//schwift.UnexpectedStatusCodeError may be returned.
	ExpectStatusCodes []int
}

//URL returns the full URL for this request.
func (r Request) URL(client *gophercloud.ServiceClient, values url.Values) (string, error) {
	uri, err := url.Parse(client.Endpoint)
	if err != nil {
		return "", err
	}
	if !strings.HasSuffix(uri.Path, "/") {
		uri.Path += "/"
	}

	if r.ContainerName == "" {
		if r.ObjectName != "" {
			return "", ErrNoContainerName
		}
	} else {
		if strings.Contains(r.ContainerName, "/") {
			return "", ErrMalformedContainerName
		}
		uri.Path += r.ContainerName + "/" + r.ObjectName
	}

	uri.RawQuery = values.Encode()
	return uri.String(), nil
}

//Do executes this request on the given service client.
func (r Request) Do(client *gophercloud.ServiceClient) (*http.Response, error) {
	return r.do(client, false)
}

func (r Request) do(client *gophercloud.ServiceClient, afterReauth bool) (*http.Response, error) {
	provider := client.ProviderClient

	//build URL
	var values url.Values
	if r.Options != nil {
		values = r.Options.Values
	}
	uri, err := r.URL(client, values)
	if err != nil {
		return nil, err
	}

	//build request
	req, err := http.NewRequest(r.Method, uri, r.Body)
	if err != nil {
		return nil, err
	}

	for k, v := range r.Headers {
		req.Header[k] = v
	}
	req.Header.Set("User-Agent", provider.UserAgent.Join())
	for key, value := range provider.AuthenticatedHeaders() {
		req.Header.Set(key, value)
	}

	resp, err := provider.HTTPClient.Do(req)
	if err != nil {
		return nil, err
	}

	//return success if error code matches expectation
	if len(r.ExpectStatusCodes) == 0 {
		//check disabled -> return response unaltered
		return resp, nil
	}
	for _, code := range r.ExpectStatusCodes {
		if code == resp.StatusCode {
			return resp, nil
		}
	}

	//detect expired token
	if resp.StatusCode == http.StatusUnauthorized && !afterReauth {
		err := drainResponseBody(resp)
		if err != nil {
			return nil, err
		}
		err = provider.Reauthenticate(resp.Request.Header.Get("X-Auth-Token"))
		if err != nil {
			return nil, err
		}
		//restart request with new token
		return r.do(client, true)
	}

	//other unexpected status code -> generate UnexpectedStatusCodeError
	buf, err := collectResponseBody(resp)
	if err != nil {
		return nil, err
	}
	return nil, UnexpectedStatusCodeError{
		ExpectedStatusCodes: r.ExpectStatusCodes,
		ActualResponse:      resp,
		ResponseBody:        buf,
	}
}

func drainResponseBody(r *http.Response) error {
	_, err := io.Copy(ioutil.Discard, r.Body)
	if err != nil {
		return err
	}
	return r.Body.Close()
}

func collectResponseBody(r *http.Response) ([]byte, error) {
	buf, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}
	return buf, r.Body.Close()
}