forked from laobubu/ssland
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.py
executable file
·360 lines (303 loc) · 10.1 KB
/
web.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# WebServer Module.
# Use `web.run(host='127.0.0.1', port=8080)` to start
#
import re
import config, user
import bottle
import json, sys, os
import utils
import ssmgr
import traffic
import datetime
import pyqrcode, io, base64
from bottle import route, get, post, run, template, redirect, static_file, response, request
from functools import wraps
WEB_ROOT = config.WEB_ROOT
bottle.TEMPLATE_PATH.insert(0, WEB_ROOT)
# bottle.debug(True)
# FIXME: Use another graceful way to pass current_user to processors
current_user = user.User()
is_admin = False
# decorator that used for login_only pages
def require_login(func):
def func_wrapper(*args, **kwargs):
global current_user, is_admin
uid_str = request.get_cookie('ssl_uid')
password = request.get_cookie('ssl_pw')
logined = uid_str and password
if logined:
current_user = user.get_by_id(int(uid_str))
logined = current_user and current_user.salted_password == password
is_admin = logined and current_user.id == config.USER_ADMIN
if not logined:
response.set_cookie('ssl_uid', '', expires=0)
response.set_cookie('ssl_pw', '', expires=0)
return redirect('/login')
return func(*args, **kwargs)
return func_wrapper
# decorator that used for user json APIs. Decorated function shall return a dict.
def json_api(func):
def func_wrapper(*args, **kwargs):
rs = func(*args, **kwargs)
try:
ds = json.dumps(rs)
response.content_type = 'application/json; charset=utf-8'
return ds
except:
return rs
return func_wrapper
# decorator for admin APIs
def admin_api(uri):
def admin_api_out(func):
@wraps(func)
@post(uri)
@require_login
@json_api
def func_wrapper(*args, **kwargs):
if not is_admin: return {"error": "not_admin"}
return func(*args, **kwargs)
return admin_api_out
# get salted password from request.forms
def get_salted_password():
password = request.forms.get('password')
if not (request.forms.get('md5ed') == '1' and re.match(r'^[a-f\d]{32}$', password)):
password = user.salt_password(password)
return password
# home panel Generator
get_home_content = lambda msg='': template(
'home',
config=config,
user=current_user,
is_admin=is_admin,
message=msg,
ssconf=ssmgr.conf_cache
)
# Website for normal User
@route('/')
@require_login
def server_index():
ssmgr.read_conf()
return get_home_content()
@route('/qr.svg')
@require_login
def server_qr():
ssmgr.read_conf()
qr = pyqrcode.create('ss://' + base64.b64encode('%s:%s@%s:%d'%(
ssmgr.conf_cache['method'],
current_user.sskey,
ssmgr.conf_cache['server'],
current_user.get_port()
)))
out = io.BytesIO()
qr.svg(out, scale=5)
response.content_type = 'image/svg+xml'
return out.getvalue()
@post('/passwd')
@require_login
def set_passwd():
u = current_user
u.salted_password = get_salted_password()
u.write()
return get_home_content("Password has changed.")
@post('/sskey')
@require_login
def set_sskey():
u = current_user
u.sskey = request.forms.get('sskey')
u.write()
import cron;
cd = cron.start()
if cd <= 0.5:
msg = "Your Shadowsocks key is changed!"
else:
msg = "The Shadowsocks key will be changed in %.2f sec" % cd
return get_home_content(msg)
# Website for Administrator
@route('/admin')
@require_login
def server_admin():
if not is_admin: return redirect('/')
return static_file('admin.html', root=WEB_ROOT)
@admin_api('/admin/cli')
def admin_cli():
argv = request.forms.get('cmd').split(' ')
out, rtn = utils.get_stdout([sys.executable, './cli.py'] + argv)
return {
"retval": rtn,
"output": out
}
@admin_api('/admin/restart')
def admin_restart():
import cron
cd = cron.start()
return { "time": cd }
@admin_api('/admin/basic')
def admin_basic():
return { "user_salt": config.USER_SALT }
@admin_api('/admin/tx/query')
def admin_tx_query():
tfrom, tto, tsum = [request.forms.get(n) or None for n in ('from', 'to', 'group')]
# Make a UID->Username table
un = { u.id: u.username for u in user.get_all() }
# Make result
tresult = {}
for uid, pkg, tx, time in traffic.query(min_time=tfrom, max_time=tto, sum=int(tsum)):
if not time in tresult: tresult[time] = []
tresult[time].append({ "title": un[uid], "amount": tx })
tdays = tresult.keys()
tdays.sort()
return [ {"title": tday, "data": tresult[tday]} for tday in tdays ]
@admin_api('/admin/user/add')
def admin_user_add():
u = user.User()
u.username, u.salted_password, u.sskey = [request.forms.get(n) for n in ('username', 'password', 'sskey')]
u.create()
u.write()
return { "id": u.id }
@admin_api('/admin/user/del')
def admin_user_del():
username = request.forms.get('username')
user.delete_users(username)
return { "status": "ok" }
@admin_api('/admin/user/list')
def admin_user_list():
list = []
for u in user.get_all():
ui = u.__dict__
ui['port'] = u.get_port()
list.append(ui)
return { "list": list }
@admin_api('/admin/user/passwd')
def admin_user_passwd():
username, password = [request.forms.get(n) for n in ('username', 'password')]
u = user.get_by_username(username)
u.salted_password = password
u.write()
return { "status": "ok" }
@admin_api('/admin/user/sskey')
def admin_user_sskey():
username, sskey = [request.forms.get(n) for n in ('username', 'value')]
u = user.get_by_username(username)
u.sskey = sskey
u.write()
return { "status": "ok" }
@admin_api('/admin/user/port')
def admin_user_port():
username, port = [request.forms.get(n) for n in ('username', 'value')]
u = user.get_by_username(username)
u.set_port(port)
u.write()
return { "status": "ok" }
@admin_api('/admin/user/limit')
def admin_user_limit():
username, limit = [request.forms.get(n) for n in ('username', 'limit')]
limit = json.loads(limit)
u = user.get_by_username(username)
u.set_meta("limit", limit)
u.write()
return { "status": "ok" }
@admin_api('/admin/user/suspend')
def admin_user_suspend():
username, suspend, reason = [request.forms.get(n) for n in ('username', 'suspend', 'reason')]
u = user.get_by_username(username)
u.suspended = suspend == "1"
if reason:
datestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
u.set_meta("limiter_log", "%s: %s"%(datestr, reason))
u.write()
return { "username": username, "suspended": u.suspended }
# Login and Logout
@get('/logout')
def logout():
response.set_cookie('ssl_uid', '', expires=0)
response.set_cookie('ssl_pw', '', expires=0)
return redirect('/login')
@get('/login')
def login():
return template('login', salt=config.USER_SALT)
@post('/login')
def do_login():
username = request.forms.get('username')
password = get_salted_password()
current_user = user.get_by_username(username)
logined = current_user and current_user.salted_password == password
if logined:
response.set_cookie('ssl_uid', str(current_user.id))
response.set_cookie('ssl_pw', password)
return redirect('/')
return template('login',
username=username,
message='User not found.' if not current_user else 'Password is incorrect.',
salt=config.USER_SALT
)
@route('/static/<filename>')
def server_static(filename):
return static_file(filename, root=WEB_ROOT+'/static')
if __name__ == "__main__":
import argparse, os, sys, time, signal
parser = argparse.ArgumentParser(description='SSLand Web Server')
parser.add_argument('-d', '--daemon', action='store', required=False, help="Control web server daemon")
flags = parser.parse_args(sys.argv[1:])
DAEMON_PID_FILE = config.TMP_ROOT + "/ssland.web.pid"
if flags.daemon in ('stop', 'restart'):
try:
with open(DAEMON_PID_FILE, 'r') as f:
pid = int(f.read())
os.kill(pid, signal.SIGTERM)
print("Stopped PID %d" % pid)
os.remove(DAEMON_PID_FILE)
except:
pass
if flags.daemon == 'stop': sys.exit(0)
if flags.daemon in ('start', 'restart'):
def freopen(f, mode, stream):
oldf = open(f, mode)
oldfd = oldf.fileno()
newfd = stream.fileno()
os.close(newfd)
os.dup2(oldfd, newfd)
def handle_exit(signum, _):
if signum == signal.SIGTERM:
sys.exit(0)
sys.exit(1)
signal.signal(signal.SIGINT, handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
already_running=False
try:
with open(DAEMON_PID_FILE, 'r') as f:
pid = int(f.read())
os.kill(pid, 0)
print("Already running daemon with PID %d" % pid)
already_running=True
except:
pass
if already_running:
sys.exit(0)
else:
# Thread not found. Create
pid = os.fork()
assert pid != -1
if pid > 0:
# parent waits for its child
time.sleep(5)
sys.exit(0)
# child signals its parent to exit
ppid = os.getppid()
pid = os.getpid()
with open(DAEMON_PID_FILE, 'w') as f:
f.write(str(pid))
os.setsid()
signal.signal(signal.SIGHUP, signal.SIG_IGN)
print("Daemon running, PID %d" % pid)
os.kill(ppid, signal.SIGTERM)
sys.stdin.close()
try:
log_file = "/var/log/ssland.web.log"
freopen(log_file, 'a', sys.stdout)
freopen(log_file, 'a', sys.stderr)
except:
pass
run(host=config.WEB_HOST, port=config.WEB_PORT)