-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
99 lines (87 loc) · 3.05 KB
/
main.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
# -*- coding: UTF-8 -*-
import thread
import socket
import argparse
import json
import logging
from httphandler import *
from base64 import b64encode as encode
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr = logging.FileHandler('www/restrito/server.log')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
help = """
HttpServer
Usage:
main.py Defaults to run on localhost:8181 with a read block size of 32 bytes
main.py (-c | --config-file) <FILE>, must be an existing json file
Option:
-c , --config-file
"""
config = {
'port': 8181,
'read_length': 32,
'allow_serve_directories': False,
'security':
{
'realm': 'realm',
'basic_auth': 'pusheen:neehsup',
'private_directories':
[
'restrito'
]
}
}
def parse_config_file(file):
if file is None:
return None
try:
fl = open(file)
js = json.loads(fl.read())
fl.close()
return js
except IOError as e:
print "Can't open file", file
print e
return None
def get_args():
parser = argparse.ArgumentParser(
description="A Simple HTTP server, if none where specified will run on 8181 and read block length will be 32, the directory 'restrito' has access with 'pusheen:neehsup'")
parser.add_argument('-c', '--config-file', required=False, type=str,
help='Config file, must be an existing json file. An example file with default configurations is provided in config.json.sample')
arg = parser.parse_args()
return parse_config_file(arg.config_file)
if __name__ == '__main__':
config_args = get_args()
if config_args is not None:
config = config_args
config['security']['basic_auth']= encode(config['security']['basic_auth'])
logger.info('Starting server at %s' % config['port'])
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
# Aceita qualquer requeste de qualquer endereço, que venha na porta
orig = ('0.0.0.0', int(config['port']))
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcp.bind(orig)
# Começa a ouvir
tcp.listen(100)
try:
while True:
# Conexão aceita
con, client = tcp.accept()
logger.debug("Concetado com cliente %s" % client[0])
# Criando obj para parsear o request
request = httphandler(con, client, int(config['read_length']), config['security'], config['allow_serve_directories'])
# Start em uma nova thread e procesa a request
thread.start_new_thread(request.processarRequest, ())
except KeyboardInterrupt as e:
print "Servidor finalizado com sucesso"
except Exception as e:
print "Servidor encontrou um problema", e
finally:
tcp.listen(0)
tcp.close()