# -*- coding: utf-8 -*-

import os
import signal
import subprocess
from flask import Flask, jsonify, request, abort
from functools import wraps
import time
import requests
import shutil
import zlib
import json
import tempfile
import psutil
from werkzeug.serving import WSGIRequestHandler
import base64
import hashlib
import re

WSGIRequestHandler.protocol_version = "HTTP/1.1"
app = Flask(__name__)
app.config.from_envvar('HTTPGUARD_SETTINGS', silent=False)


def requires_auth(f):
   @wraps(f)
   def decorated(*args, **kwargs):
        remote_addr = request.remote_addr
        master_ipaddr = app.config['MASTER_IPADDR']
        if remote_addr != master_ipaddr and remote_addr != "127.0.0.1":
            abort(403)

        return f(*args, **kwargs)

   return decorated

def check_nginx_conf():
    nginx_bin_location = os.path.join(app.config['NGINX_LOCATION'],"sbin/nginx")
    try:
        subprocess.check_output([nginx_bin_location, "-t"],stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        return False, e.output

    return True, None

def reload_nginx():
    pid = get_nginx_pid()
    if pid == None or pid == "":
        return False, u"找不到pid,无法重载"

    try:
        subprocess.check_output(["kill","-HUP", pid],stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        return False, e.output

    return True, None

def get_nginx_pid():
    nginx_pid_file = os.path.join(app.config['NGINX_LOCATION'],"logs/nginx.pid")
    try:
        with open(nginx_pid_file, "r") as fp:
            nginx_pid = fp.read().replace("\n","")
            return nginx_pid

    except IOError:
        return None    

def is_nginx_running():
    nginx_pid = get_nginx_pid()
    if nginx_pid == None:
        return False

    return os.path.exists(os.path.join('/proc', nginx_pid))

def stop_nginx():
    if not is_nginx_running():
        return True

    nginx_pid = get_nginx_pid()
    os.kill(int(nginx_pid),signal.SIGQUIT)
    for x in xrange(1,10):
        if not os.path.exists(os.path.join('/proc', nginx_pid)):
            return True

        time.sleep(1)

    return False

def start_nginx():
    if is_nginx_running():
        return True

    nginx_bin_location = os.path.join(app.config['NGINX_LOCATION'],"sbin/nginx")
    try:
        subprocess.check_output([nginx_bin_location],stderr=subprocess.STDOUT)
        return True

    except subprocess.CalledProcessError as e:
        return False, e.output      

@app.route('/v1/reload-nginx', methods=['POST'])
@requires_auth
def reload_nginx_handler():
    ret, err = check_nginx_conf()
    if not ret:
        return jsonify(state="failed",msg=err)

    ret, err = reload_nginx()
    if not ret:
        return jsonify(state="failed",msg=err)

    return jsonify(state="success",msg=None)


@app.route('/v1/is-nginx-running', methods=['GET'])
@requires_auth
def is_nginx_running_handler():
    if is_nginx_running():
        return jsonify(state="success",msg=None)

    return jsonify(state="failed",msg=None)


def get_machine_code():
    try:
        route_fp = open("/proc/net/route","r")
    except IOError:
        return None, "can not open route file"

    default_dev = None
    route_ip = None
    for line in route_fp:
        line_split = line.split()        
        iface = line_split[0]
        dest = line_split[1]
        gateway = line_split[2]   
        if dest == "00000000":
            default_dev = iface
            route_ip = gateway
            break

    if default_dev is None:
        return None, "get default_dev failed" 

    if route_ip is None:
        return None, "get route_ip failed" 

    addr_file = "/sys/class/net/"+default_dev+"/address"

    try:
        with open(addr_file,"r") as fp:
            mac_addr = fp.read()

    except IOError:
        return None, "can not open addr_file."

    str = mac_addr + route_ip
    hl = hashlib.md5()
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest(),None

@app.route('/v1/guard-status', methods=['GET'])
@requires_auth
def guard_status_handler():
    nginx_running = False

    if is_nginx_running():
        nginx_running = True

    machine_code, err = get_machine_code()
    if machine_code is None:
        return jsonify(state="failed",msg=err)

    return jsonify(state="success",msg={"nginx_running":nginx_running, "machine_code":machine_code})


@app.route('/v1/restart-nginx', methods=['POST'])
@requires_auth
def restart_nginx_handler():
    if not stop_nginx():
        return jsonify(state="failed",msg="stop nginx failed")

    if not start_nginx():
        return jsonify(state="failed",msg="start nginx failed")

    return jsonify(state="success",msg=None)  


@app.route('/v1/save-nginx-conf', methods=['POST'])
@requires_auth
def save_nginx_conf_handler():
    body = request.get_data()
    nginx_conf_bak_file = "/tmp/nginx.conf.bak"
    nginx_conf_file = os.path.join(app.config['NGINX_LOCATION'],"conf/nginx.conf")
    # 备份文件
    shutil.copyfile(nginx_conf_file, nginx_conf_bak_file)

    with open(nginx_conf_file,"w") as fp:
        fp.write(body)

    # 检查配置文件
    ret, err = check_nginx_conf()
    if not ret:
        # 还原配置
        shutil.copyfile(nginx_conf_bak_file, nginx_conf_file)
        return jsonify(state="failed",msg=err)

    # 重载nginx
    ret, err = reload_nginx()
    if not ret:
        return jsonify(state="failed",msg=err)

    return jsonify(state="success",msg=None)


@app.route('/v1/save-nginx-vhost', methods=['POST'])
@requires_auth
def save_nginx_vhost_handler():
    nginx_vhost_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost")
    certs_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost/certs")
    error_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost/error_page")

    if not os.path.isdir(nginx_vhost_dir):
        os.makedirs(nginx_vhost_dir)
    
    if not os.path.isdir(certs_dir):
        os.makedirs(certs_dir)

    if not os.path.isdir(error_dir):
        os.makedirs(error_dir)
        
    # 备份vhost
    tempdir = tempfile.mktemp()
    if os.path.isdir(tempdir):
        shutil.rmtree(tempdir)

    shutil.copytree(nginx_vhost_dir, tempdir) 
    try:
        body = request.get_data()
        body = zlib.decompress(body)
        body = json.loads(body)
        master_ip = app.config["MASTER_IPADDR"]
        for site in body:                         
            vhost_conf = base64.b64decode(site["vhost"])
            vhost_conf = vhost_conf.replace("master-ip",master_ip)
            site_id = site['site_id']
            error404 = base64.b64decode(site['error404'])
            error50x = base64.b64decode(site['error50x'])
            crt = base64.b64decode(site['crt'])
            key = base64.b64decode(site['key'])
            ngx_cache_dir = base64.b64decode(site['ngx_cache_dir'])

            # 检查cache_dir目录是否存在
            if not os.path.isdir(ngx_cache_dir):
                os.makedirs(ngx_cache_dir)
                subprocess.check_output(["chown","nobody",ngx_cache_dir ],stderr=subprocess.STDOUT)
            
            print(vhost_conf)
            # 保存vhost
            vhost_path = os.path.join(nginx_vhost_dir,site_id + ".conf")
            with open(vhost_path, "w") as fp:
                fp.write(vhost_conf)

            # 保存错误页面
            error404_path = os.path.join(error_dir,site_id + ".404.html")
            with open(error404_path,"w") as fp:
                fp.write(error404)

            error50x_path = os.path.join(error_dir,site_id + ".50x.html")
            with open(error50x_path,"w") as fp:
                fp.write(error50x)

            # 保存证书
            crt_path = os.path.join(certs_dir,site_id + ".crt")
            with open(crt_path,"w") as fp:
                fp.write(crt)

            key_path = os.path.join(certs_dir,site_id + ".key")
            with open(key_path,"w") as fp:
                fp.write(key)


        ret, err = check_nginx_conf()
        if not ret:
            # 恢复备份
            shutil.rmtree(nginx_vhost_dir)
            shutil.copytree(tempdir, nginx_vhost_dir)
            return jsonify(state="failed",msg=err)

        ret, err = reload_nginx()
        if not ret:
            return jsonify(state="failed",msg=err)

        return jsonify(state="success",msg=None)

    except:
        # 恢复备份
        shutil.rmtree(nginx_vhost_dir)
        shutil.copytree(tempdir, nginx_vhost_dir)
        raise

    finally:
        shutil.rmtree(tempdir)

@app.route('/v1/del-all-vhost', methods=['POST'])
@requires_auth
def del_all_vhost_handler():
    nginx_vhost_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost")
    try:
        shutil.rmtree(nginx_vhost_dir)
    except:
        pass
            
    return jsonify(state="success",msg=None)

@app.route('/v1/del-nginx-vhost', methods=['POST'])
@requires_auth
def del_nginx_vhost_handler():
    nginx_vhost_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost")
    certs_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost/certs")
    error_dir = os.path.join(app.config['NGINX_LOCATION'],"conf/vhost/error_page")

    # 备份vhost
    tempdir = tempfile.mktemp()
    if os.path.isdir(tempdir):
        shutil.rmtree(tempdir)

    shutil.copytree(nginx_vhost_dir, tempdir) 
    try:
        body = request.get_data()
        body = zlib.decompress(body)
        body = json.loads(body)
        for site in body:                         
            site_id = site['site_id']
            ngx_cache_dir = site['ngx_cache_dir']
            try:
                # 删除vhost
                vhost_path = os.path.join(nginx_vhost_dir,site_id + ".conf")
                if os.path.exists(vhost_path):
                    os.remove(vhost_path)

                # 删除错误页面
                error404_path = os.path.join(error_dir,site_id + ".404.html")
                if os.path.exists(error404_path):
                    os.remove(error404_path)

                error50x_path = os.path.join(error_dir,site_id + ".50x.html")
                if os.path.exists(error50x_path):
                    os.remove(error50x_path)

                # 删除证书
                crt_path = os.path.join(certs_dir,site_id + ".crt")
                if os.path.exists(crt_path):
                    os.remove(crt_path)

                key_path = os.path.join(certs_dir,site_id + ".key")
                if os.path.exists(key_path):
                    os.remove(key_path)

                # 删除缓存目录
                cache_path = os.path.join(ngx_cache_dir,site_id)
                if os.path.exists(cache_path):
                    shutil.rmtree(cache_path)
            except:
                pass

        ret, err = check_nginx_conf()
        if not ret:
            # 恢复备份
            shutil.rmtree(nginx_vhost_dir)
            shutil.copytree(tempdir, nginx_vhost_dir)
            return jsonify(state="failed",msg=err)

        ret, err = reload_nginx()
        if not ret:
            return jsonify(state="failed",msg=err)

        return jsonify(state="success",msg=None)

    except:
        # 恢复备份
        shutil.rmtree(nginx_vhost_dir)
        shutil.copytree(tempdir, nginx_vhost_dir)
        raise

    finally:
        shutil.rmtree(tempdir)

@app.route('/v1/save-config-json', methods=['POST'])
@requires_auth
def save_config_json_handler():
    config_json_file = os.path.join(app.config['HTTPGUARD_LOCATION'],"conf/config.json")
    body = request.get_data()
    json_body = json.loads(body)

    if os.path.exists(config_json_file):
        with open(config_json_file, "r") as fp:
            config_data = fp.read()

        auth_code = json.loads(config_data)["auth_code"]

        json_body["auth_code"] = auth_code

    os.umask(000)
    with open(config_json_file, "w") as fp:
        fp.write(json.dumps(json_body))

    try:
        r = requests.post("http://127.0.0.1/guard/reload-config", timeout=3)
        return jsonify(state="success",msg=None)

    except requests.exceptions.Timeout:
        return jsonify(state="failed",msg="Connection Timeout")

@app.route('/v1/nginx-status', methods=['GET'])
@requires_auth
def nginx_status_handler():
    try:
        res = requests.get("http://127.0.0.1/guard/nginx-status",timeout=3)
    except requests.exceptions.ConnectionError:
        return jsonify(state="failed",msg="ConnectionError")
    except requests.exceptions.HTTPError:
        return jsonify(state="failed",msg="HTTPError:" + str(res.status_code))
    except requests.exceptions.Timeout:
        return jsonify(state="failed",msg="Connection Timeout")

    return res.content

@app.route('/v1/load-status', methods=['GET'])
@requires_auth
def load_status_handler():
    return jsonify(state="success",msg={"cpu":cpu(None)[0],"load":sysload(None)[0]})

@app.route('/v1/net-status', methods=['GET'])
@requires_auth
def net_status_handler():
    netif = request.args.get('netif')
    return jsonify(state="success",msg={"sent":net_sent(netif)[0],"recv":net_recv(netif)[0]})

def cpu(val):
    try:
        with open("/tmp/cpu.log","r") as fp:
            return float(fp.read()), None
    except IOError:
        print "/tmp/cpu.log not found"
        return None, "/tmp/cpu.log not found"

def sysload(val):
    return os.getloadavg()[0], None

def memory(val):
    return psutil.virtual_memory()[2], None

def disk(partition):
    try:
        return psutil.disk_usage(partition)[3], None
    except OSError:
        return None, partition + " not found"

def inode(partition):
    try:
        inode_stat = os.statvfs("/")
        f_favail = inode_stat.f_favail
        f_files = inode_stat.f_files
        f_fusage = f_files - f_favail
        percent = '{:.1f}'.format(f_fusage*1.0 / f_files*100)
        return percent, None
    except OSError:
        return None, partition + " not found"

def host_traffic(host):
    url = "http://127.0.0.1/guard/host-traffic?host={host}".format(host=host)
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    msg = content["msg"]
    state = content["state"]
    if state == "success":
        return msg, None

    return None, msg 

def host_req(val):
    url = "http://127.0.0.1/guard/host-req"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    msg = content["msg"]
    state = content["state"]
    if state == "success":
        return msg, None

    return None, msg

def nginx_cpu(val):
    url = "http://127.0.0.1/guard/nginx-status"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    return content["msg"]["cpu"], None

def nginx_conn_active(val):
    url = "http://127.0.0.1/guard/nginx-status"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    try:
        return content["msg"]["connection"]["connections_active"], None    
    except TypeError as e:
        return 0, None

def nginx_conn_reading(val):
    url = "http://127.0.0.1/guard/nginx-status"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    try:
        return content["msg"]["connection"]["connections_reading"], None    
    except TypeError as e:
        return 0, None

def nginx_conn_writing(val):
    url = "http://127.0.0.1/guard/nginx-status"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    try:
        return content["msg"]["connection"]["connections_writing"], None    
    except TypeError as e:
        return 0, None 

def nginx_conn_waiting(val):
    url = "http://127.0.0.1/guard/nginx-status"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    try:
        return content["msg"]["connection"]["connections_waiting"], None    
    except TypeError as e:
        return 0, None    

def net_recv(nic):
    try:
        with open("/tmp/"+nic+".recv.log","r") as fp:
            return float(fp.read()), None
    except IOError:
        print "/tmp/"+nic+".recv.log not found"
        return None, "/tmp/"+nic+".recv.log not found"


def net_sent(nic):
    try:
        with open("/tmp/"+nic+".sent.log","r") as fp:
            return float(fp.read()), None
    except IOError:
        print "/tmp/"+nic+".sent.log not found"
        return None, "/tmp/"+nic+".sent.log"

def tcp_conn(val):
    count = 0
    for conn in psutil.net_connections():
        if conn.status == "ESTABLISHED":
            count = count + 1

    return count, None

def disk_discovery(val):
    mounts = []
    for i in psutil.disk_partitions():
        mounts.append(i.mountpoint)

    return mounts, None

def net_if_discovery(val):
    net_if = []
    for i in psutil.net_if_addrs():
        if i == "lo":
            continue
            
        net_if.append(i)

    return net_if, None

def auto_cc_state(val):
    url = "http://127.0.0.1/guard/domain-auto-cc-state"
    r = requests.get(url)
    content = r.content
    content = json.loads(content)
    return content["msg"], None



@app.route('/v1/monitor', methods=['GET'])
@requires_auth
def monitor_handler():
    item = request.args.get('item')
    val = request.args.get('val')

    if not item:
        return jsonify(state="failed",msg="arg item not found")

    data, err = globals()[item](val)
    if err:
        return jsonify(state="failed",msg=err)

    return jsonify(state="success",msg=data)

@app.route('/v1/nginx-ver', methods=['GET'])
@requires_auth
def nginx_ver_handler():
    nginx_conf_file = os.path.join(app.config['NGINX_LOCATION'],"conf/nginx.conf")
    try:
        with open(nginx_conf_file, "r") as fp:
            for line in fp:
                if not (line.find("#version=") == -1):
                    version=line[9:-1]
                    break
            else:
                version = -1
    except IOError:
        version = -1

    return jsonify(state="success",msg=version)

@app.route('/v1/config-ver', methods=['GET'])
@requires_auth
def config_ver_handler():
    config_json_file = os.path.join(app.config['HTTPGUARD_LOCATION'],"conf/config.json")
    try:
        with open(config_json_file, "r") as fp:
            data = fp.read()

        data = json.loads(data)
        try:
            version = data["data_ver"]
        except KeyError:
            version = -1

    except IOError:
        version = -1

    return jsonify(state="success",msg=version)

@app.route('/v1/clean_site_whitelist', methods=['POST'])
@requires_auth
def clean_site_whitelist_handler():
    body = request.get_data()
    try:
        body = json.loads(body)
        site_id = body["site_id"]
    except ValueError:
        return jsonify(state="failed",msg="not a valid json.")
    except KeyError:
        return jsonify(state="failed",msg="key site_id not found.")

    data = json.dumps({'site_id': site_id})
    try:
        r = requests.post("http://127.0.0.1/guard/clean-site-whitelist", data=data, timeout=10)
        return jsonify(state="success",msg=None)

    except requests.exceptions.Timeout:
        return jsonify(state="failed",msg="Connection Timeout")


@app.route('/v1/clean_site_blacklist', methods=['POST'])
@requires_auth
def clean_site_blacklist_handler():
    body = request.get_data()
    try:
        body = json.loads(body)
        site_id = body["site_id"]
    except ValueError:
        return jsonify(state="failed",msg="not a valid json.")
    except KeyError:
        return jsonify(state="failed",msg="key site_id not found.")

    data = json.dumps({'site_id': site_id})
    try:
        r = requests.post("http://127.0.0.1/guard/clean-site-blacklist", data=data, timeout=10)
        body = r.content

    except requests.exceptions.Timeout:
        return jsonify(state="failed",msg="Connection Timeout")


    body = json.loads(body)
    ip_del = []
    for ip in body["msg"].split(","):
        if ip == "":
            continue

        ip_del.append("del httpguard {ip}".format(ip=ip))

    ip_del_data = "\n".join(ip_del)

    if ip_del_data != "":
        with open("/tmp/ip_del_"+str(site_id),"w") as fp:
            fp.write(ip_del_data)
        subprocess.check_output(["/sbin/ipset", "-!" , "restore" ,"-f", "/tmp/ip_del_"+str(site_id)],stderr=subprocess.STDOUT)

    return jsonify(state="success",msg=None)

@app.route('/v1/get-host-list', methods=['GET'])
@requires_auth
def get_host_list_handler():
    host_list = []
    for filename in os.listdir(os.path.join(app.config['NGINX_LOCATION'],"conf/vhost")):
        if filename.endswith(".conf"):
            with open(os.path.join(app.config['NGINX_LOCATION'],"conf/vhost",filename)) as fp:
                for line in fp:
                    m = re.match(r".*server_name(.*);",line)
                    if m:
                        host_list = host_list + m.group(1).split()

    return jsonify(state="success",msg=host_list)

@app.route('/v1/mark-upgrade', methods=['POST'])
@requires_auth
def mark_upgrade_handler():
    with open("/tmp/mark-agent-upgrade","w") as fp:
        fp.write("")

    return jsonify(state="success",msg=None)

@app.route('/v1/agent-version', methods=['GET'])
@requires_auth
def agent_version_handler():
    return jsonify(state="success",msg=app.config["VERSION_NUM"])


@app.route('/v1/clean_site_cache', methods=['POST'])
@requires_auth
def clean_site_cache_handler():
    body = request.get_data()
    try:
        body = json.loads(body)
        site_id = body["site_id"]
        ngx_cache_dir = body["ngx_cache_dir"]

    except ValueError:
        return jsonify(state="failed",msg="not a valid json.")
    except KeyError:
        return jsonify(state="failed",msg="site_id not found.")

    # 删除缓存目录
    cache_path = os.path.join(ngx_cache_dir,site_id)
    if os.path.exists(cache_path):
        shutil.rmtree(cache_path)

    return jsonify(state="success",msg=None)

@app.route('/v1/clear_site_certain_cache', methods=['POST'])
@requires_auth
def clear_site_certain_cache_handler():
    body = request.get_data()
    try:
        body = json.loads(body)
        site_id = body["site_id"]
        url = body["url"]
        ngx_cache_dir = body["ngx_cache_dir"]

    except ValueError:
        return jsonify(state="failed",msg="not a valid json.")
    except KeyError, e:
        raise
        return jsonify(state="failed",msg=e[0])

    # 删除缓存
    for path in url.split("\n"):
        if path.strip() == "":
            continue

        path = ".*" + path
        subprocess.check_output(["/opt/httpguard/httpguard/util/purge_cache.sh", path, ngx_cache_dir],stderr=subprocess.STDOUT)
        print "/opt/httpguard/httpguard/util/purge_cache.sh " +  path + " " + ngx_cache_dir

    return jsonify(state="success",msg=None)
    

@app.route('/v1/save-key-config', methods=['POST'])
@requires_auth
def save_config():
    content = request.get_json(silent=True,force=True)
    config_file = "/opt/httpguard/httpguard/conf/config.json"

    with open(config_file,"r") as fp:
        config = fp.read()

    config = json.loads(config)

    for k in content:
        config[k] = content[k]

    config_data = json.dumps(config)
    with open(config_file,"w") as fp:
        fp.write(config_data)

    try:
        r = requests.post("http://127.0.0.1/guard/reload-config", timeout=3)
        return jsonify(state="success",msg=None)

    except requests.exceptions.Timeout:
        return jsonify(state="failed",msg="reload-config Connection Timeout")

    return jsonify(state="success",msg=None)

@app.route('/v1/block-ip', methods=['POST'])
@requires_auth
def block_ip():
    with open("/opt/httpguard/httpguard/conf/config.json") as fp:
        config = fp.read()

    config = json.loads(config)
    timeout = config["temp_blacklist_block_time"]

    body = request.get_data()
    ipset_list = []
    for ip in body.split():
        ipset_list.append("add httpguard {ip} timeout {timeout}".format(ip=ip,timeout=timeout))

    data = "\n".join(ipset_list)
    if data != "":
        with open("/tmp/black_ip_list","w") as fp:
            fp.write(data)
        subprocess.check_output(["/sbin/ipset", "-!" , "restore" ,"-f", "/tmp/black_ip_list"],stderr=subprocess.STDOUT)

    return jsonify(state="success",msg=None)

@app.route('/', methods=['GET'])
def index():
    return "it works."
    
if __name__ == '__main__':
    app.run()
