Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
AlpacaMax
GitHub Repository: AlpacaMax/Shadow-Browser
Path: blob/master/api/main.py
249 views
1
from flask import Flask
2
import docker
3
from flask import request
4
from threading import Timer
5
import random
6
import os
7
8
app = Flask(__name__)
9
10
MIN_PORT = 5950 # Min port for vnc services
11
MAX_PORT = 6000 # Max port for vnc services (Not included)
12
TOTAL = MAX_PORT - MIN_PORT
13
14
ports_in_use = []
15
16
client = docker.from_env()
17
18
HOSTNAME = os.environ.get("HOSTNAME")
19
print("HOSTNAME:", HOSTNAME)
20
21
22
@app.route("/")
23
def hello():
24
"""
25
Hello-world test
26
"""
27
txt = client.containers.run('alpine', 'echo hello world, alpine')
28
return txt.decode('ascii')
29
30
31
def get_port():
32
"""
33
get an available port no in use
34
return -1 if no port available
35
"""
36
for port in range(MIN_PORT, MAX_PORT):
37
if not (port in ports_in_use):
38
ports_in_use.append(port)
39
return port
40
return -1
41
42
43
def release_port(port):
44
"""
45
release a port from the pool
46
return 0 if successful
47
return -1 if not successful
48
"""
49
if port in ports_in_use:
50
ports_in_use.remove(port)
51
else:
52
raise Exception('Port not in use!')
53
54
55
def kill_container(container, port):
56
print(container.id + " killed!")
57
container.kill()
58
release_port(port)
59
60
61
def start_chrome_container(port, duration, password):
62
"""
63
start a container on port with duration and password
64
duration in second
65
"""
66
container = client.containers.run('siomiz/chrome', ports={'5900/tcp': ('0.0.0.0', port)},
67
detach=True, auto_remove=True,
68
environment=['VNC_PASSWORD=' + str(password)])
69
Timer(duration, kill_container, (container, port, )).start()
70
71
72
@app.route("/run_chrome", methods=['GET'])
73
def run_chrome():
74
"""
75
example: http://localhost/run_chrome?duration=5
76
duration: the duration of a container in minutes
77
duration = -1 for unlimited time
78
return: the port of the service
79
"""
80
duration = request.args.get('duration')
81
port = get_port()
82
password = random.randint(0, 99999999)
83
start_chrome_container(port, int(duration), password)
84
out = HOSTNAME + "#" + str(port) + "#" + str(password)
85
return out
86
87
88
@app.route("/hostname")
89
def hostname():
90
"""
91
check if the hostname is correct
92
:return: the host name of the server
93
"""
94
return HOSTNAME
95
96
@app.route("/browsers_info")
97
def get_info():
98
inuse = len(ports_in_use)
99
available = TOTAL - inuse
100
per_inuse = int(float(inuse) / TOTAL * 100)
101
per_available = int(float(available) / TOTAL * 100)
102
info = str(available) + "#" + str(inuse) + "#" + str(per_available) + "#" + str(per_inuse)
103
return info
104
105
if __name__ == "__main__":
106
# Only for debugging while developing
107
app.run(host='0.0.0.0', debug=True, port=80)
108
109