-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsgi_api.py
executable file
·193 lines (143 loc) · 4.92 KB
/
wsgi_api.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Georges Toth'
__email__ = '[email protected]'
__copyright__ = 'Copyright 2013, Georges Toth'
__license__ = 'GPL v3+'
#
# REST server API for IP2AS data
#
import cherrypy
import os
import syslog
import sys
try:
import ConfigParser as configparser
except ImportError:
import configparser
import json
from ip2as.ip2as import IP2AS
ip2as_ = None
def is_authorized():
if not cherrypy.request.headers.get('key', '') in cherrypy.config['api_keys']:
raise cherrypy.HTTPError(403, 'Forbidden')
def audit():
params = {}
if hasattr(cherrypy.request, 'json') and cherrypy.request.json:
for k in cherrypy.request.json:
params[k] = cherrypy.request.json[k]
log('{0} {1} {2} {3}'.format(cherrypy.request.headers.get('remote-addr', 'NONE'), cherrypy.request.headers.get('key', ''),
cherrypy.request.request_line, str(params)))
cherrypy.tools.is_authorized = cherrypy.Tool('before_handler', is_authorized, priority=49)
cherrypy.tools.audit = cherrypy.Tool('before_handler', audit, priority=50)
def log(msg, priority=syslog.LOG_INFO):
'''
Central logging method
:param msg: message
:param priority: message priority
:type msg: str
:type priority: syslog.LOG_*
'''
syslog.syslog(priority, msg)
class IP2ASTool(cherrypy.Tool):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(IP2ASTool, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def __init__(self):
global ip2as_
cherrypy.Tool.__init__(self, 'on_start_resource',
self.bind_session,
priority=20)
self.ip2as = ip2as_
def bind_session(self):
cherrypy.request.ip2as = self.ip2as
class Manage(object):
def __init__(self):
pass
@cherrypy.expose
@cherrypy.tools.audit()
@cherrypy.tools.is_authorized()
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def get_asn(self, asn):
try:
asn_ = cherrypy.request.ip2as.getasn(asn)
except KeyError:
raise cherrypy.HTTPError(404, 'Nothing found')
cherrypy.response.status = 200
return json.dumps(asn_)
@cherrypy.expose
@cherrypy.tools.audit()
@cherrypy.tools.is_authorized()
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def get_ip(self, ip):
try:
ip_ = cherrypy.request.ip2as.getip(ip)
except KeyError:
raise cherrypy.HTTPError(404, 'Nothing found')
cherrypy.response.status = 200
return json.dumps(ip_)
def error_page_403(status, message, traceback, version):
return 'Error {0} - {1}'.format(status, message)
cherrypy.config.update({'error_page.403': error_page_403})
def application(environ, start_response):
global ip2as_
syslog.openlog('ip2as_wsgi_server', logoption=syslog.LOG_PID)
myprefix = os.path.dirname(os.path.abspath(__file__))
wsgi_config = myprefix + '/wsgi_api.ini'
if not os.path.exists(wsgi_config):
wsgi_config = '/etc/ip2as_wsgi_api.ini'
if not os.path.exists(wsgi_config):
log('Fatal error: config file not found!', priority=syslog.LOG_ERR)
sys.exit(1)
config = configparser.ConfigParser()
config.read(wsgi_config)
ip2as_dat = config.get('ip2as', 'ip2as_dat').strip('\'')
try:
import msgpack
ip2as_bin_dat = config.get('ip2as', 'ip2as_bin_dat').strip('\'')
except ImportError, configparser.NoOptionError:
ip2as_bin_dat = ''
if ip2as_ is None:
if not ip2as_bin_dat == '':
ip2as_ = IP2AS(ip2as_bin_dat, use_msgpack=True)
else:
ip2as_ = IP2AS(ip2as_dat)
cherrypy.tools.ip2as = IP2ASTool()
cherrypy.config['tools.encode.on'] = True
cherrypy.config['tools.encode.encoding'] = 'utf-8'
cherrypy.config.update(config=wsgi_config)
cherrypy.tree.mount(Manage(), '/', config=wsgi_config)
return cherrypy.tree(environ, start_response)
if __name__ == '__main__':
syslog.openlog('ip2as_wsgi_server', logoption=syslog.LOG_PID)
myprefix = os.path.dirname(os.path.abspath(__file__))
wsgi_config = myprefix + '/wsgi_api.ini'
if not os.path.exists(wsgi_config):
wsgi_config = '/etc/ip2as_wsgi_api.ini'
if not os.path.exists(wsgi_config):
log('Fatal error: config file not found!', priority=syslog.LOG_ERR)
sys.exit(1)
config = configparser.ConfigParser()
config.read(wsgi_config)
ip2as_dat = config.get('ip2as', 'ip2as_dat').strip('\'')
try:
import msgpack
ip2as_bin_dat = config.get('ip2as', 'ip2as_bin_dat').strip('\'')
except ImportError, configparser.NoOptionError:
ip2as_bin_dat = ''
if ip2as_ is None:
if not ip2as_bin_dat == '':
ip2as_ = IP2AS(ip2as_bin_dat, use_msgpack=True)
else:
ip2as_ = IP2AS(ip2as_dat)
cherrypy.tools.ip2as = IP2ASTool()
cherrypy.config['tools.encode.on'] = True
cherrypy.config['tools.encode.encoding'] = 'utf-8'
cherrypy.config.update(config=wsgi_config)
log('starting')
cherrypy.quickstart(Manage(), '/', config=wsgi_config)