1 | # -*- coding: utf-8 -*- |
---|
2 | # |
---|
3 | # Copyright (c) 2015 Virtual Cable S.L. |
---|
4 | # All rights reserved. |
---|
5 | # |
---|
6 | # Redistribution and use in source and binary forms, with or without modification, |
---|
7 | # are permitted provided that the following conditions are met: |
---|
8 | # |
---|
9 | # * Redistributions of source code must retain the above copyright notice, |
---|
10 | # this list of conditions and the following disclaimer. |
---|
11 | # * Redistributions in binary form must reproduce the above copyright notice, |
---|
12 | # this list of conditions and the following disclaimer in the documentation |
---|
13 | # and/or other materials provided with the distribution. |
---|
14 | # * Neither the name of Virtual Cable S.L. nor the names of its contributors |
---|
15 | # may be used to endorse or promote products derived from this software |
---|
16 | # without specific prior written permission. |
---|
17 | # |
---|
18 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
---|
19 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
---|
20 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
---|
21 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
---|
22 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
---|
23 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
---|
24 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
---|
25 | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
---|
26 | # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
---|
27 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
---|
28 | """ |
---|
29 | @author: Adolfo Gómez, dkmaster at dkmon dot com |
---|
30 | """ |
---|
31 | |
---|
32 | |
---|
33 | import json |
---|
34 | import ssl |
---|
35 | import threading |
---|
36 | from six.moves.socketserver import ThreadingMixIn # @UnresolvedImport |
---|
37 | from six.moves.BaseHTTPServer import BaseHTTPRequestHandler # @UnresolvedImport |
---|
38 | from six.moves.BaseHTTPServer import HTTPServer # @UnresolvedImport |
---|
39 | from six.moves.urllib.parse import unquote # @UnresolvedImport |
---|
40 | |
---|
41 | from .utils import exceptionToMessage |
---|
42 | from .certs import createSelfSignedCert |
---|
43 | from .log import logger |
---|
44 | |
---|
45 | |
---|
46 | class HTTPServerHandler(BaseHTTPRequestHandler): |
---|
47 | service = None |
---|
48 | protocol_version = 'HTTP/1.0' |
---|
49 | server_version = 'OpenGnsys Agent Server' |
---|
50 | sys_version = '' |
---|
51 | |
---|
52 | def sendJsonError(self, code, message): |
---|
53 | self.send_response(code) |
---|
54 | self.send_header('Content-type', 'application/json') |
---|
55 | self.end_headers() |
---|
56 | self.wfile.write(str.encode(json.dumps({'error': message}))) |
---|
57 | return |
---|
58 | |
---|
59 | def sendJsonResponse(self, data): |
---|
60 | try: self.send_response(200) |
---|
61 | except Exception as e: logger.warn (str(e)) |
---|
62 | data = json.dumps(data) |
---|
63 | self.send_header('Content-type', 'application/json') |
---|
64 | self.send_header('Content-Length', str(len(data))) |
---|
65 | self.end_headers() |
---|
66 | # Send the html message |
---|
67 | self.wfile.write(str.encode(data)) |
---|
68 | |
---|
69 | def parseUrl(self): |
---|
70 | """ |
---|
71 | Very simple path & params splitter |
---|
72 | """ |
---|
73 | path = self.path.split('?')[0][1:].split('/') |
---|
74 | |
---|
75 | try: |
---|
76 | params = dict((v[0], unquote(v[1])) for v in (v.split('=') for v in self.path.split('?')[1].split('&'))) |
---|
77 | except Exception: |
---|
78 | params = {} |
---|
79 | |
---|
80 | for v in self.service.modules: |
---|
81 | if v.name == path[0]: # Case Sensitive!!!! |
---|
82 | return v, path[1:], params |
---|
83 | |
---|
84 | return None, path, params |
---|
85 | |
---|
86 | def notifyMessage(self, module, path, get_params, post_params): |
---|
87 | """ |
---|
88 | Locates witch module will process the message based on path (first folder on url path) |
---|
89 | """ |
---|
90 | try: |
---|
91 | data = module.processServerMessage(path, get_params, post_params, self) |
---|
92 | self.sendJsonResponse(data) |
---|
93 | except Exception as e: |
---|
94 | logger.exception() |
---|
95 | self.sendJsonError(500, exceptionToMessage(e)) |
---|
96 | |
---|
97 | def do_GET(self): |
---|
98 | module, path, params = self.parseUrl() |
---|
99 | |
---|
100 | self.notifyMessage(module, path, params, None) |
---|
101 | |
---|
102 | def do_POST(self): |
---|
103 | module, path, get_params = self.parseUrl() |
---|
104 | post_params = None |
---|
105 | |
---|
106 | # Tries to get JSON content (UTF-8 encoded) |
---|
107 | try: |
---|
108 | length = int(self.headers.get('content-length')) |
---|
109 | content = self.rfile.read(length).decode('utf-8') |
---|
110 | logger.debug('length: {0}, content >>{1}<<'.format(length, content)) |
---|
111 | post_params = json.loads(content) |
---|
112 | except Exception as e: |
---|
113 | self.sendJsonError(500, exceptionToMessage(e)) |
---|
114 | |
---|
115 | self.notifyMessage(module, path, get_params, post_params) |
---|
116 | |
---|
117 | def log_error(self, fmt, *args): |
---|
118 | logger.error('HTTP ' + fmt % args) |
---|
119 | |
---|
120 | def log_message(self, fmt, *args): |
---|
121 | logger.debug('HTTP ' + fmt % args) |
---|
122 | |
---|
123 | |
---|
124 | class HTTPThreadingServer(ThreadingMixIn, HTTPServer): |
---|
125 | pass |
---|
126 | |
---|
127 | |
---|
128 | class HTTPServerThread(threading.Thread): |
---|
129 | def __init__(self, address, service): |
---|
130 | super(self.__class__, self).__init__() |
---|
131 | |
---|
132 | HTTPServerHandler.service = service # Keep tracking of service so we can intercact with it |
---|
133 | |
---|
134 | self.certFile = createSelfSignedCert() |
---|
135 | self.server = HTTPThreadingServer(address, HTTPServerHandler) |
---|
136 | context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
---|
137 | context.load_cert_chain(certfile=self.certFile) |
---|
138 | self.server.socket = context.wrap_socket(self.server.socket, server_side=True) |
---|
139 | |
---|
140 | logger.debug('Initialized HTTPS Server thread on {}'.format(address)) |
---|
141 | |
---|
142 | def getServerUrl(self): |
---|
143 | return 'https://{}:{}/'.format(self.server.server_address[0], self.server.server_address[1]) |
---|
144 | |
---|
145 | def stop(self): |
---|
146 | self.server.shutdown() |
---|
147 | |
---|
148 | def run(self): |
---|
149 | self.server.serve_forever() |
---|