source: ogAgent-Git/src/opengnsys/httpserver.py @ c39b253

maintls 4.0.0
Last change on this file since c39b253 was 9af7469, checked in by Natalia Serrano <natalia.serrano@…>, 4 weeks ago

refs #1784 ignore module name in URLs

  • Property mode set to 100644
File size: 7.2 KB
Line 
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
33import os
34import json
35import ssl
36import threading
37from six.moves.socketserver import ThreadingMixIn  # @UnresolvedImport
38from six.moves.BaseHTTPServer import BaseHTTPRequestHandler  # @UnresolvedImport
39from six.moves.BaseHTTPServer import HTTPServer  # @UnresolvedImport
40from six.moves.urllib.parse import unquote  # @UnresolvedImport
41
42from .utils import exceptionToMessage
43from .certs import createSelfSignedCert
44from .log import logger
45
46
47class HTTPServerHandler(BaseHTTPRequestHandler):
48    service = None
49    protocol_version = 'HTTP/1.0'
50    server_version = 'OpenGnsys Agent Server'
51    sys_version = ''
52   
53    def sendJsonError(self, code, message):
54        self.send_response(code)
55        self.send_header('Content-type', 'application/json')
56        self.end_headers()
57        self.wfile.write(str.encode(json.dumps({'error': message})))
58        return
59
60    def sendJsonResponse(self, data):
61        try: self.send_response(200)
62        except Exception as e: logger.warn ('exception: "{}"'.format(str(e)))
63        data = json.dumps(data)
64        self.send_header('Content-type', 'application/json')
65        self.send_header('Content-Length', str(len(data)))
66        self.end_headers()
67        # Send the html message
68        self.wfile.write(str.encode(data))
69
70    def parseUrl(self):
71        """
72        Very simple path & params splitter
73        """
74        path = self.path.split('?')[0][1:].split('/')
75       
76        try:
77            params = dict((v[0], unquote(v[1])) for v in (v.split('=') for v in self.path.split('?')[1].split('&')))
78        except Exception:
79            params = {}
80
81        ## quick override because universities do not actually want the module to be extracted out of the URL
82        module = 'ogAdmClient' if os.path.exists ('/scripts/oginit') else 'opengnsys'
83
84        for v in self.service.modules:
85            if v.name == module:  # Case Sensitive!!!!
86                return v, path[1:], params
87           
88        return None, path, params
89   
90    def notifyMessage(self, module, path, get_params, post_params):
91        """
92        Locates witch module will process the message based on path (first folder on url path)
93        """
94        try:
95            if module is None:
96                raise Exception ({ '_httpcode': 404, '_msg': f'Module {path[0]} not found' })
97            data = module.processServerMessage(path, get_params, post_params, self)
98            self.sendJsonResponse(data)
99        except Exception as e:
100            logger.exception()
101            n_args = len (e.args)
102            if 0 == n_args:
103                logger.debug ('Empty exception raised from message processor for "{}"'.format(path[0]))
104                self.sendJsonError(500, exceptionToMessage(e))
105            else:
106                arg0 = e.args[0]
107                if type (arg0) is str:
108                    logger.debug ('Message processor for "{}" returned exception string "{}"'.format(path[0], str(e)))
109                    self.sendJsonError (500, exceptionToMessage(e))
110                elif type (arg0) is dict:
111                    if '_httpcode' in arg0:
112                        logger.debug ('Message processor for "{}" returned HTTP code "{}" with exception string "{}"'.format(path[0], str(arg0['_httpcode']), str(arg0['_msg'])))
113                        self.sendJsonError (arg0['_httpcode'], arg0['_msg'])
114                    else:
115                        logger.debug ('Message processor for "{}" returned exception dict "{}" with no HTTP code'.format(path[0], str(e)))
116                        self.sendJsonError (500, exceptionToMessage(e))
117                else:
118                    logger.debug ('Message processor for "{}" returned non-string and non-dict exception "{}", type "{}"'.format(path[0], str(e), type(e)))
119                    self.sendJsonError (500, exceptionToMessage(e))
120            ## not reached
121           
122    def do_GET(self):
123        module, path, params = self.parseUrl()
124       
125        self.notifyMessage(module, path, params, None)
126       
127    def do_POST(self):
128        module, path, get_params = self.parseUrl()
129        post_params = None
130
131        # Tries to get JSON content (UTF-8 encoded)
132        try:
133            length = int(self.headers.get('content-length'))
134            content = self.rfile.read(length).decode('utf-8')
135            logger.debug('length: {0}, content >>{1}<<'.format(length, content))
136            post_params = json.loads(content)
137        except Exception as e:
138            self.sendJsonError(500, exceptionToMessage(e))
139           
140        self.notifyMessage(module, path, get_params, post_params)
141
142    def log_error(self, fmt, *args):
143        logger.error('HTTP ' + fmt % args)
144       
145    def log_message(self, fmt, *args):
146        logger.debug('HTTP ' + fmt % args)
147       
148
149class HTTPThreadingServer(ThreadingMixIn, HTTPServer):
150    pass
151
152
153class HTTPServerThread(threading.Thread):
154    def __init__(self, address, service):
155        super(self.__class__, self).__init__()
156
157        HTTPServerHandler.service = service  # Keep tracking of service so we can intercact with it
158
159        self.certFile = createSelfSignedCert()
160        self.server = HTTPThreadingServer(address, HTTPServerHandler)
161        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
162        context.load_cert_chain(certfile=self.certFile)
163        self.server.socket = context.wrap_socket(self.server.socket, server_side=True)
164       
165        logger.debug('Initialized HTTPS Server thread on {}'.format(address))
166
167    def getServerUrl(self):
168        return 'https://{}:{}/'.format(self.server.server_address[0], self.server.server_address[1])
169
170    def stop(self):
171        self.server.shutdown()
172
173    def run(self):
174        self.server.serve_forever()
Note: See TracBrowser for help on using the repository browser.