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

configure-ptt-chedecorare-oglive-methodsejecutarscript-b64fix-cfg2objfixes-winlgromero-filebeatmainmodulesnew-browserno-ptt-paramogadmcliogadmclient-statusogagent-jobsogagent-macosogcore1oglogoglog2override-moduleping1ping2ping3ping4py3-winreport-progresstlsunification2unification3versionswindows-fixes
Last change on this file since 10fab78 was 10fab78, checked in by Natalia Serrano <natalia.serrano@…>, 10 months ago

refs #464 several fixes and improvements

  • fix OG icon in windows system tray
  • change a log.info into log.debug to avoid a crash (!)
  • migrate update.sh to python so it can be run from windows/macos too
    • manage windows/VERSION in this script too
    • remove call to pyrcc--it's not required!
  • remove stray windows scripts
  • add a forgotten setup.bat
  • Property mode set to 100644
File size: 5.6 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 json
34import ssl
35import threading
36from six.moves.socketserver import ThreadingMixIn  # @UnresolvedImport
37from six.moves.BaseHTTPServer import BaseHTTPRequestHandler  # @UnresolvedImport
38from six.moves.BaseHTTPServer import HTTPServer  # @UnresolvedImport
39from six.moves.urllib.parse import unquote  # @UnresolvedImport
40
41from .utils import exceptionToMessage
42from .certs import createSelfSignedCert
43from .log import logger
44
45
46class 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
124class HTTPThreadingServer(ThreadingMixIn, HTTPServer):
125    pass
126
127
128class 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()
Note: See TracBrowser for help on using the repository browser.