import BaseHTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import threading
import datetime
import os

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        starting_dir = os.getcwd()
        os.chdir('scripts')

        filename = self.path.split('/')[1]
        if os.path.exists(filename):
            self.send_response(200)
            self.end_headers()
            with open(filename, 'r') as script:
                self.wfile.write(script.read())
        else:
            self.send_response(404)
            self.end_headers()

        os.chdir(starting_dir)

    def do_POST(self):
        self.send_response(200)
        self.end_headers()
        sent_bytes = int(self.headers.getheader('content-length'))
        results = self.rfile.read(sent_bytes)
        with open('/tmp/post-data', 'w') as f:
            f.write(results)
        with open('pentestly.log', 'a') as f:
            f.write('[{} - {}]\n'.format(self.__dict__['client_address'][0], datetime.datetime.now().ctime()))
            f.write(results + '\n')

class PentestlyServer(threading.Thread):
    def __init__(self, port=80):

        self.success = False
        try:
            threading.Thread.__init__(self)
            self.httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', port), Handler)
            self.success = True

        except Exception as e:
            import traceback;traceback.print_exc()
            print("[!] Could not set up PentestlyServer: {}".format(str(e)))

    def run(self):
        try:
            self.httpd.serve_forever()
        except:
            pass

    def shutdown(self):
        self.httpd.shutdown()
        self.httpd.socket.close()
        self.httpd.server_close()
        self._Thread__stop()

        # ensure all threads are dead
        for thread in threading.enumerate():
            if thread.isAlive():
                try: 
                    thread._Thread__stop()
                except:
                    pass
