/
http_client.py
254 lines (218 loc) · 8.79 KB
/
http_client.py
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function, unicode_literals
import six
import zlib
import base64
import json
import sys
import io
if six.PY2:
from urllib import urlencode
else:
from urllib.parse import urlencode
# Pycurl part
import pycurl
pycurl.global_init(pycurl.GLOBAL_ALL)
PYCURL_VERSION = pycurl.version_info()[1]
from shinken.bin import VERSION
from shinken.log import logger
class HTTPException(Exception):
pass
class FileReader(object):
def __init__(self, fp):
self.fp = fp
def read_callback(self, size):
return self.fp.read(size)
class HTTPClient(object):
def __init__(self, address='', port=0, use_ssl=False, timeout=3,
data_timeout=120, uri='', strong_ssl=False, proxy=''):
self.address = address
self.port = port
self.timeout = timeout
self.data_timeout = data_timeout
if not uri:
if use_ssl:
self.uri = "https://%s:%s/" % (self.address, self.port)
else:
self.uri = "http://%s:%s/" % (self.address, self.port)
else:
self.uri = uri
self.get_con = self.__create_con(proxy, strong_ssl)
self.post_con = self.__create_con(proxy, strong_ssl)
self.put_con = self.__create_con(proxy, strong_ssl)
def __create_con(self, proxy, strong_ssl):
con = pycurl.Curl()
con.setopt(con.VERBOSE, 0)
# Remove the Expect: 100-Continue default behavior of pycurl, because swsgiref do not
# manage it
headers = ['Expect:', 'Keep-Alive: 300', 'Connection: Keep-Alive']
user_agent = 'shinken:%s pycurl:%s' % (VERSION, PYCURL_VERSION)
# Manages bug described in https://github.com/pycurl/pycurl/issues/124
try:
con.setopt(pycurl.HTTPHEADER, headers)
con.setopt(pycurl.USERAGENT, user_agent)
except TypeError:
headers = [h.encode("utf-8") for h in headers]
user_agent = user_agent.encode("utf-8")
con.setopt(pycurl.HTTPHEADER, headers)
con.setopt(pycurl.USERAGENT, user_agent)
con.setopt(pycurl.FOLLOWLOCATION, 1)
con.setopt(pycurl.FAILONERROR, True)
con.setopt(pycurl.CONNECTTIMEOUT, self.timeout)
con.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_1)
if proxy:
# Manages bug described in https://github.com/pycurl/pycurl/issues/124
try:
con.setopt(pycurl.PROXY, proxy)
except TypeError:
proxy = proxy.encode("utf-8")
con.setopt(pycurl.PROXY, proxy)
# Also set the SSL options to do not look at the certificates too much
# unless the admin asked for it
if strong_ssl:
con.setopt(pycurl.SSL_VERIFYPEER, 1)
con.setopt(pycurl.SSL_VERIFYHOST, 2)
else:
con.setopt(pycurl.SSL_VERIFYPEER, 0)
con.setopt(pycurl.SSL_VERIFYHOST, 0)
return con
def set_proxy(self, proxy):
if proxy:
logger.debug('PROXY SETTING PROXY %s', proxy)
self.get_con.setopt(pycurl.PROXY, proxy)
self.post_con.setopt(pycurl.PROXY, proxy)
self.put_con.setopt(pycurl.PROXY, proxy)
# Try to get an URI path
def get(self, path, args={}, wait='short'):
c = self.get_con
c.setopt(c.POST, 0)
c.setopt(pycurl.HTTPGET, 1)
# For the TIMEOUT, it will depends if we are waiting for a long query or not
# long:data_timeout, like for huge broks receptions
# short:timeout, like for just "ok" connection
if wait == 'short':
c.setopt(c.TIMEOUT, self.timeout)
else:
c.setopt(c.TIMEOUT, self.data_timeout)
c.setopt(c.URL, self.uri + path + '?' + urlencode(args))
# Ok now manage the response
response = io.BytesIO()
c.setopt(pycurl.WRITEFUNCTION, response.write)
c.setopt(c.VERBOSE, 0)
try:
c.perform()
except pycurl.error as error:
errno, errstr = error.args
raise HTTPException('Connection error to %s : %s' % (self.uri, errstr))
r = c.getinfo(pycurl.HTTP_CODE)
# Do NOT close the connection, we want a keep alive
# c.close()
if r != 200:
err = response.getvalue().decode("utf-8")
logger.error("There was a critical error : %s", err)
raise HTTPException('Connection error to %s : %s' % (self.uri, r))
# Manage special return of pycurl
#ret = json.loads(.decode("utf-8").replace('\\/', '/'))
# print("GOT RAW RESULT", ret, type(ret))
return response.getvalue()
# Try to get an URI path
def post(self, path, args, wait='short'):
size = 0
for (k, v) in args.items():
args[k] = serialize(v)
size += len(args[k])
# Ok go for it!
c = self.post_con
c.setopt(pycurl.HTTPGET, 0)
c.setopt(c.POST, 1)
# For the TIMEOUT, it will depends if we are waiting for a long query or not
# long:data_timeout, like for huge broks receptions
# short:timeout, like for just "ok" connection
if wait == 'short':
c.setopt(c.TIMEOUT, self.timeout)
else:
c.setopt(c.TIMEOUT, self.data_timeout)
# if proxy:
# c.setopt(c.PROXY, proxy)
# Pycurl want a list of tuple as args
c.setopt(c.HTTPPOST, list(args.items()))
c.setopt(c.URL, self.uri + path)
# Ok now manage the response
response = io.BytesIO()
c.setopt(pycurl.WRITEFUNCTION, response.write)
c.setopt(c.VERBOSE, 0)
try:
c.perform()
except pycurl.error as error:
errno, errstr = error.args
raise HTTPException('Connection error to %s : %s' % (self.uri, errstr))
r = c.getinfo(pycurl.HTTP_CODE)
# Do NOT close the connection, we want a keep alive
# c.close()
if r != 200:
err = response.getvalue().decode("utf-8")
logger.error("There was a critical error : %s", err)
raise HTTPException('Connection error to %s : %s' % (self.uri, r))
# Manage special return of pycurl
# ret = json.loads(response.getvalue().replace('\\/', '/'))
return response.getvalue()
# Should return us pong string
return ret
# Try to get an URI path
def put(self, path, content, wait='short'):
c = self.put_con
filesize = len(content)
payload = io.BytesIO(content)
c.setopt(pycurl.INFILESIZE, filesize)
c.setopt(pycurl.PUT, 1)
c.setopt(pycurl.READFUNCTION, FileReader(payload).read_callback)
# For the TIMEOUT, it will depends if we are waiting for a long query or not
# long:data_timeout, like for huge broks receptions
# short:timeout, like for just "ok" connection
if wait == 'short':
c.setopt(c.TIMEOUT, self.timeout)
else:
c.setopt(c.TIMEOUT, self.data_timeout)
# if proxy:
# c.setopt(c.PROXY, proxy)
# Pycurl want a list of tuple as args
c.setopt(c.URL, self.uri + path)
c.setopt(c.VERBOSE, 0)
# Ok now manage the response
response = io.BytesIO()
c.setopt(pycurl.WRITEFUNCTION, response.write)
# c.setopt(c.VERBOSE, 1)
try:
c.perform()
except pycurl.error as error:
errno, errstr = error.args
raise HTTPException('Connection error to %s : %s' % (self.uri, errstr))
r = c.getinfo(pycurl.HTTP_CODE)
# Do NOT close the connection, we want a keep alive
# c.close()
if r != 200:
err = response.getvalue().decode("utf-8")
logger.error("There was a critical error : %s", err)
raise HTTPException('Connection error to %s : %s' % (self.uri, r))
return response.getvalue()