Esempio n. 1
0
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}
Esempio n. 2
0
def stat():
    '''
    Get the stat data and storage into database.
    Add IPTABLES rules if necessary.
    '''
    cs, ec = get_stdout(IPTABLES + ('-nxvL', 'SSLAND')) # get current stat
    if ec == 3: return False   # No privilege
    if ec == 1: # chain not found
        # create the chain
        get_stdout(IPTABLES + ('-N','SSLAND'))
        get_stdout(IPTABLES + ('-I','OUTPUT','1','-j','SSLAND'))
    get_stdout(IPTABLES + ('-Z','SSLAND')) # empty IPTABLES stat
    
    t  = {}  # dict PORT=>(pkgs, bytes)
    for i in re.findall(r"^\s*(\d+)\s+(\d+).+dpt:(\d+)", cs, re.M):
        # i = Pkgs   Traffic(byte)   port
        t[int(i[2])] = ( int(i[0]) , int(i[1]) )
        
    query = []
    users = user.get_all()
    for u in users:
        if u.suspended: continue
        port = config.user_port(u.id)
        if port in t:
            ti = t[port]
            query.append((u.id, ti[0], ti[1]))
        else:
            get_stdout(IPTABLES + ('-A','SSLAND','-p','tcp','--dport',str(port)))
            
    cursor = database.conn.cursor()
    cursor.executemany('INSERT INTO traffic(user,packages,traffic) VALUES (?, ?, ?)', query)
    cursor.close()
    database.conn.commit()
Esempio n. 3
0
def server_index():
    return template(
        'home', 
        config=config, 
        user=current_user,
        users=(user.get_all() if current_user.id == config.USER_ADMIN else {})
    )
Esempio n. 4
0
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 }
Esempio n. 5
0
def stat():
    '''
    Get the stat data and storage into database.
    '''
    update_iptables()
    cs, ec = get_stdout(IPTABLES + ('-nxvL', CHAIN_NAME)) # get current stat
    if ec == 3: return False   # No privilege
    get_stdout(IPTABLES + ('-Z',CHAIN_NAME)) # empty IPTABLES stat
    
    t  = {}  # dict PORT=>(pkgs, bytes)
    for i in re.findall(r"^\s*(\d+)\s+(\d+).+[sd]pt:(\d+)", cs, re.M):
        # i = Pkgs   Traffic(byte)   port
        port = int(i[2])
        if not port in t: t[port] = [0, 0]
        t[port][0] += int(i[0])
        t[port][1] += int(i[1])
        
    query = []
    users = user.get_all(only_active=True)
    for u in users:
        port = u.get_port()
        if port in t:
            ti = t[port]
            if ti[0] and ti[1]: query.append((u.id, ti[0], ti[1]))      # skip empty record
            
    cursor = database.conn.cursor()
    cursor.executemany('INSERT INTO traffic(user,packages,traffic) VALUES (?, ?, ?)', query)
    cursor.close()
    database.conn.commit()
Esempio n. 6
0
def update_conf():
    '''
    Update Shadowsocks Config file.
    '''
    try:
        j = json.load(open(config.SS_CONF, 'r'))
    except:
        # Cannot read config file. Use default
        print(
            "Cannot read Shadowsocks config file. File not exist or SSLand has no permission.",
            file=sys.stderr)
        j = {
            "server": "0.0.0.0",
            "port_password": {
                "6789": "aba"
            },
            "timeout": 300,
            "method": "aes-256-cfb"
        }
    pp = {}
    for u in user.get_all():
        if u.suspended: continue
        port = str(config.user_port(u.id))
        key = u.sskey
        if len(key) > 0: pp[port] = key
    j['port_password'] = pp
    json.dump(j, open(config.SS_CONF, 'w'))
    return j
Esempio n. 7
0
def run(scope, action, argv):
    if scope == 'user':
        if   action == 'list':
            print("id\tusername\tsuspended\tport\tsskey")
            for u in user.get_all():
                print('\t'.join(( str(item) for item in 
                    (u.id, u.username, 'True' if u.suspended else 'False', config.user_port(u.id), u.sskey)
                )))
        elif action == 'add':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'Shadowsocks Key: ')
            u = user.User()
            u.username = username
            u.set_password(password)
            u.sskey = sskey
            u.create()
            u.write()
        elif action == 'del':
            user.delete_users(*argv)
        elif action in ['suspend', 'unsuspend']:
            user.batch_update(*argv, suspended=(1 if action == 'suspend' else 0))
        elif action == 'passwd':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'sskey':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'Shadowsocks Key: ')
            u = user.get_by_username(username)
            u.sskey = sskey
            u.write()
        else:
            print_help()
    elif scope == 'sys':
        if   action == 'update':
            import ssmgr
            ssmgr.update_and_restart()
            
            try:
                import os
                with open(config.TMP_ROOT + "/ssland.web.pid", 'r') as f:
                    pid = int(f.read())
                    os.kill(pid, 0)
                    from utils import get_stdout
                    get_stdout(["./web.py", "-d", "restart"])
            except:
                pass
        else:
            print_help()
    else:
        print_help()
Esempio n. 8
0
def update_conf():
    '''
    Read Shadowsocks Config file, fill with users' port and sskey, and save it.
    '''
    read_conf(True)
    pp = {}
    for u in user.get_all(only_active=True):
        if not len(u.sskey): continue
        port = str(u.get_port())
        pp[port] = u.sskey
    conf_cache['port_password'] = pp
    write_conf()
Esempio n. 9
0
def update_conf():
    '''
    Read Shadowsocks Config file, fill with users' port and sskey, and save it.
    '''
    read_conf(True)
    pp = {}
    for u in user.get_all(only_active=True):
        if not len(u.sskey): continue
        port = str(u.get_port())
        pp[port] = u.sskey
    conf_cache['port_password'] = pp
    write_conf()
Esempio n. 10
0
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 ]
Esempio n. 11
0
def cli():
    if (current_user.id != config.USER_ADMIN):
        return redirect('/')

    argv = request.forms.get('cmd').split(' ')
    import cli
    cli.run(argv[0], argv[1], argv[2:])

    return template('home',
                    config=config,
                    user=current_user,
                    message="EXECUTED",
                    users=user.get_all())
Esempio n. 12
0
def updateServer():
    if (current_user.id != config.USER_ADMIN):
        return redirect('/')

    import cron
    cd = cron.start()
    msg = "The Shadowsocks will be updated in %.2f sec" % cd

    return template('home',
                    config=config,
                    user=current_user,
                    message=msg,
                    users=user.get_all())
Esempio n. 13
0
def update_all():
    '''
    Suspend users who exceed the limitation.
    '''
    results = {}
    datestr = datetime.datetime.now().strftime(DATE_FORMAT)
    for u in user.get_all(only_active=True):
        reason = check_user(u)
        if reason:
            u.suspended = True
            u.set_meta("limiter_log", "%s: %s"%(datestr, reason))
            u.write(commit=False)
            results[u.username] = reason
    database.conn.commit()
    return results
Esempio n. 14
0
def updateServer():
    if (current_user.id != config.USER_ADMIN):
        return redirect('/')
    
    import cron;
    cd = cron.start()
    msg = "The Shadowsocks will be updated in %.2f sec" % cd
    
    return template(
        'home', 
        config=config, 
        user=current_user,
        message=msg, 
        users=user.get_all()
    )
Esempio n. 15
0
def cli():
    if (current_user.id != config.USER_ADMIN):
        return redirect('/')
    
    argv = request.forms.get('cmd').split(' ')
    import cli
    cli.run(argv[0], argv[1], argv[2:])
    
    return template(
        'home', 
        config=config, 
        user=current_user,
        message="EXECUTED",
        users=user.get_all()
    )
Esempio n. 16
0
def suspend(suspend, username):
    if (current_user.id != config.USER_ADMIN):
        return redirect('/')

    u = user.get_by_username(username)
    u.suspended = suspend != "0"
    u.write()

    msg = 'User %s status changed. Please click [Update SSConfig].' % username
    return template(
        'home',
        config=config,
        user=current_user,
        message=msg,
        users=(user.get_all() if current_user.id == config.USER_ADMIN else {}))
Esempio n. 17
0
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]
Esempio n. 18
0
def suspend(suspend, username):
    if (current_user.id != config.USER_ADMIN):
        return redirect('/')
    
    u = user.get_by_username(username)
    u.suspended = suspend != "0"
    u.write()
    
    msg = 'User %s status changed. Please click [Update SSConfig].' % username
    return template(
        'home', 
        config=config, 
        user=current_user,
        message=msg, 
        users=(user.get_all() if current_user.id == config.USER_ADMIN else {})
    )
Esempio n. 19
0
def update_conf():
    '''
    Update Shadowsocks Config file.
    '''
    try:
        j = json.load(open(config.SS_CONF, 'r'))
    except:
        # Cannot read config file. Use default
        print("Cannot read Shadowsocks config file. File not exist or SSLand has no permission.", file=sys.stderr)
        j = {"server": "0.0.0.0", "port_password": {"6789": "aba"}, "timeout": 300, "method": "aes-256-cfb"}
    pp = {}
    for u in user.get_all():
        if u.suspended: continue
        port = str(config.user_port(u.id))
        key  = u.sskey
        if len(key) > 0: pp[port] = key
    j['port_password'] = pp
    json.dump(j, open(config.SS_CONF, 'w'))
    return j
Esempio n. 20
0
def update_iptables():
    '''
    Add IPTABLES rules if necessary.
    '''
    cs, ec = get_stdout(IPTABLES + ('-nxvL', CHAIN_NAME)) # get current stat
    if ec == 3: return False   # No privilege
    if ec == 1: # chain not found
        # create the chain
        get_stdout(IPTABLES + ('-N',CHAIN_NAME))
        get_stdout(IPTABLES + ('-I','INPUT','1','-j',CHAIN_NAME))
        get_stdout(IPTABLES + ('-I','OUTPUT','1','-j',CHAIN_NAME))
    
    sport = set(int(r) for r in re.findall(r"\bspt:(\d+)", cs, re.M))
    dport = set(int(r) for r in re.findall(r"\bdpt:(\d+)", cs, re.M))
    
    users = user.get_all(only_active=True)
    for u in users:
        port = u.get_port()
        if not port in sport:   get_stdout(IPTABLES + ('-A',CHAIN_NAME,'-p','tcp','--sport',str(port)))
        if not port in dport:   get_stdout(IPTABLES + ('-A',CHAIN_NAME,'-p','tcp','--dport',str(port)))
Esempio n. 21
0
def sskey():
    sskey = request.forms.get('sskey')
    
    u = current_user
    if (u.id == config.USER_ADMIN): u = user.get_by_username(request.forms.get('username'))
    
    u.sskey = 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 template(
        'home', 
        config=config, 
        user=current_user,
        message=msg, 
        users=(user.get_all() if current_user.id == config.USER_ADMIN else {})
    )
Esempio n. 22
0
def sskey():
    sskey = request.forms.get('sskey')

    u = current_user
    if (u.id == config.USER_ADMIN):
        u = user.get_by_username(request.forms.get('username'))

    u.sskey = 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 template(
        'home',
        config=config,
        user=current_user,
        message=msg,
        users=(user.get_all() if current_user.id == config.USER_ADMIN else {}))
Esempio n. 23
0
def run(scope, action, argv):
    if scope == 'user':
        if action == 'list':
            print("id\tusername\tsuspended\tport\tsskey")
            for u in user.get_all():
                print('\t'.join(
                    (str(item) for item in (u.id, u.username,
                                            'True' if u.suspended else 'False',
                                            u.get_port(), u.sskey))))
        elif action == 'add':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'Shadowsocks Key: ')
            u = user.User()
            u.username = username
            u.set_password(password)
            u.sskey = sskey
            u.create()
            u.write()
        elif action == 'del':
            user.delete_users(*argv)
        elif action in ['suspend', 'unsuspend']:
            user.batch_update(*argv,
                              suspended=(1 if action == 'suspend' else 0))
        elif action == 'passwd':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'sskey':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'Shadowsocks Key: ')
            u = user.get_by_username(username)
            u.sskey = sskey
            u.write()
        else:
            print_help()
    elif scope == 'sys':
        if action == 'update':
            ssmgr.update_and_restart()
            get_stdout(["./web.py", "-d", "restart"])
        elif action == 'init':
            # RUN THIS WHEN SYSTEM BOOTS ONLY !
            traffic.update_iptables()
            get_stdout(["./web.py", "-d", "restart"])
            ssmgr.update_and_restart()
        else:
            print_help()
    elif scope == 'tx' or scope == 'traffic':
        if action == 'query':
            un = {}
            uid = -1
            for u in user.get_all():
                un[u.id] = u.username
                if len(argv) > 0 and u.username == argv[0]:
                    uid = u.id
            for r in traffic.query(uid=uid, sum=traffic.QS_DAY):
                print("%s\t%s\t%s" % (un[r[0]], r[3], sizeof_fmt(r[2])))
        elif action == 'update':
            traffic.stat()
        else:
            print_help()
    else:
        print_help()
Esempio n. 24
0
def run(scope, action, argv):
    if scope == 'user':
        if   action == 'list':
            print("id\tusername\tsuspended\tport\tsskey")
            for u in user.get_all():
                print('\t'.join(( str(item) for item in 
                    (u.id, u.username, 'True' if u.suspended else 'False', u.get_port(), u.sskey)
                )))
        elif action == 'add':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'Shadowsocks Key: ')
            u = user.User()
            u.username = username
            u.set_password(password)
            u.sskey = sskey
            u.create()
            u.write()
        elif action == 'del':
            user.delete_users(*argv)
        elif action in ['suspend', 'unsuspend']:
            user.batch_update(*argv, suspended=(1 if action == 'suspend' else 0))
        elif action == 'passwd':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'sskey':
            username = argv[0] if len(argv) > 0 else raw_input('Username: '******'Shadowsocks Key: ')
            u = user.get_by_username(username)
            u.sskey = sskey
            u.write()
        else:
            print_help()
    elif scope == 'sys':
        if   action == 'update':
            ssmgr.update_and_restart()
            get_stdout(["./web.py", "-d", "restart"])
        elif action == 'init':
            # RUN THIS WHEN SYSTEM BOOTS ONLY !
            traffic.update_iptables()
            get_stdout(["./web.py", "-d", "restart"])
            ssmgr.update_and_restart()
        else:
            print_help()
    elif scope == 'tx' or scope == 'traffic':
        if   action == 'query':
            un = {}
            uid = -1
            for u in user.get_all():
                un[u.id] = u.username
                if len(argv) > 0 and u.username == argv[0] :
                    uid = u.id
            for r in traffic.query(uid=uid,sum=traffic.QS_DAY):
                print("%s\t%s\t%s"%(un[r[0]], r[3], sizeof_fmt(r[2])))
        elif action == 'update':
            traffic.stat()
        else:
            print_help()
    else:
        print_help()
Esempio n. 25
0
def get_all_user():
    users = get_all()
    return {"success": True, "data": users}
Esempio n. 26
0
def get_all_users(str, sid):
    users = user.get_all()
    sio.emit('all-users', users)
Esempio n. 27
0
def server_index():
    return template(
        'home',
        config=config,
        user=current_user,
        users=(user.get_all() if current_user.id == config.USER_ADMIN else {}))