-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
executable file
·205 lines (181 loc) · 5.9 KB
/
app.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
#!/usr/bin/env python
import os, socket, json, logging, datetime, argparse
from bottle import route, request, response, error, hook, default_app
from logentries import LogentriesHandler
from dicttoxml import dicttoxml
from IPy import IP
import pydenticon
def get_ipaddress():
"""Return the IP address of the visitor to the calling function."""
try:
if request.headers.get('Cf-Connecting-Ip') == None \
and request.headers.get('X-Forwarded-For') == None:
raise TypeError
elif request.headers.get('Cf-Connecting-Ip') != None:
return str(IP(request.headers.get('Cf-Connecting-Ip')))
else:
return str(IP(request.headers.get('X-Forwarded-For')))
except TypeError:
return str(IP(request.get('REMOTE_ADDR')))
except ValueError:
return "Unable to determine IP address, or IP address provided was invalid"
def get_reverse_host():
"""Return the reverse hostname of the IP address to the calling function."""
try:
return socket.gethostbyaddr(get_ipaddress())[0]
except:
return "Unable to resolve IP address to reverse hostname"
def get_request_headers():
"""Return an array of headers used to make the request to the calling function."""
return request.headers.keys()
def set_content_type(fn):
def _return_type(*args, **kwargs):
if request.headers.get('Accept') == "application/json":
response.headers['Content-Type'] = 'application/json'
return True
if request.path.endswith('.json'):
response.headers['Content-Type'] = 'application/json'
return True
if request.headers.get('Accept') == "application/xml":
response.headers['Content-Type'] = 'application/xml'
return True
if request.path.endswith('.xml'):
response.headers['Content-Type'] = 'application/xml'
return True
response.headers['Content-Type'] = 'text/plain'
if request.method != 'OPTIONS':
return fn(*args, **kwargs)
return _return_type
def enable_cors(fn):
def _enable_cors(*args, **kwargs):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
if request.method != 'OPTIONS':
return fn(*args, **kwargs)
return _enable_cors
@route('/version')
@enable_cors
@set_content_type
def return_version():
try:
dirname, filename = os.path.split(os.path.abspath(__file__))
del filename
f = open(os.getenv('VERSION_PATH', '{}/.git/refs/heads/master'.format(dirname)), 'r')
content = f.read()
response.content_type = 'text/plain'
return content
except:
return "Unable to open version file."
@route('/icon')
@route('/icon/<height:int>')
@route('/icon/<height:int>/<width:int>')
def return_icon(height=100, width=100):
response.content_type = 'image/png'
address = IP(get_ipaddress())
values = []
if address.version() == 6:
address = str(address).split(":")
for ochet in address:
if ochet == '':
values.append("0")
elif int(ochet) >= 255:
values.append("255")
else:
values.append(ochet)
else:
address = str(address).split(".")
for ochet in address:
values.append(ochet)
colors = []
colors.append("rgb(" + values[0] \
+ "," + values[1] \
+ "," + values[2] + ")")
generator = pydenticon.Generator(8, 8, foreground=colors)
identicon = generator.generate(get_ipaddress(), height, width)
return identicon
@route('/headers')
@route('/headers.json')
@route('/headers.xml')
@enable_cors
@set_content_type
def return_headers():
content = {
"results": {}
}
for key in get_request_headers():
if "User-Agent" in key or ',' not in request.headers.get(key):
content["results"][key] = request.headers.get(key)
else:
content["results"][key] = request.headers.get(key).replace(" ", "").split(',')
if response.content_type == 'application/json':
return json.dumps(content)
elif response.content_type == 'application/xml':
return '<?xml version="1.0"?>{}'.format(dicttoxml(content, attr_type=False, root=False).decode('utf-8'))
else:
results = ["%s = %s \r\n" % (key, str(request.headers.get(key))) for key in get_request_headers()]
content = "".join(results)
return content
@route('/headers/<key>')
@enable_cors
def return_header(key):
response.content_type = 'text/plain'
return request.headers.get(key, "Not found")
@route('/reverse')
@route('/reverse.json')
@route('/reverse.xml')
@enable_cors
@set_content_type
def return_reverse():
content = {
"results": {
'reverse': get_reverse_host()
}
}
if response.content_type == 'application/json':
return json.dumps(content)
elif response.content_type == 'application/xml':
return '<?xml version="1.0"?>{}'.format(dicttoxml(content, attr_type=False, root=False).decode('utf-8'))
else:
return get_reverse_host()
@route('/')
@route('/ip')
@route('/ip.json')
@route('/ip.xml')
@enable_cors
@set_content_type
def return_ip():
content = {
"results": {
'ip': get_ipaddress()
}
}
if response.content_type == 'application/json':
return json.dumps(content)
elif response.content_type == 'application/xml':
return '<?xml version="1.0"?>{}'.format(dicttoxml(content, attr_type=False, root=False).decode('utf-8'))
else:
return get_ipaddress()
@route('/favicon.ico')
@error(404)
def error_404():
response.status = 404
return 'Not Found'
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Server settings
parser.add_argument("-i", "--host", default=os.getenv('IP', '127.0.0.1'), help="server ip")
parser.add_argument("-p", "--port", default=os.getenv('PORT', 5000), help="server port")
# Verbose mode
parser.add_argument("--verbose", "-v", help="increase output verbosity", action="store_true")
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
try:
app = default_app()
app.run(host=args.host, port=args.port, server='tornado')
except:
log.error("Unable to start server on {}:{}".format(args.host, args.port))