<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page
        import="org.apache.commons.lang.StringUtils,weaver.general.BaseBean,weaver.general.Util,weaver.hrm.HrmUserVarify,weaver.hrm.User,java.io.BufferedReader,java.io.File,java.io.FileInputStream" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Vector" %>
<%@ page import="java.util.regex.Matcher" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="java.text.SimpleDateFormat" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>

<%
    response.setHeader("cache-control", "no-cache");
    response.setHeader("pragma", "no-cache");
    response.setHeader("expires", "Mon 1 Jan 1990 00:00:00 GMT");

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>WEBSHELL检查</title>

    <LINK href="/css/Weaver_wev8.css" type=text/css rel=STYLESHEET>
</head>
<%!
    public List getFiles(String filepath, long ts) {
        List files = new Vector();
        //System.out.println(TimeUtil.getCurrentTimeString()+":开始得到项目 "+project+" 文件列表...");
        listFiles(files, filepath, ts);
        //System.out.println(TimeUtil.getCurrentTimeString()+":项目 "+project+" 文件列表获取完成..."+files.size());
        return files;
    }

    public void listFiles(List files, String dirName, long ts) {
        try {
            File dirFile = new File(dirName);
            if (!dirFile.exists() || (!dirFile.isDirectory())) {
            } else {
                File[] tmpfiles = dirFile.listFiles();
                for (int i = 0; i < tmpfiles.length; i++) {
                    File f = tmpfiles[i];
                    if (f.isFile()) {
                        if (!f.getName().endsWith(".log") && !f.getName().endsWith(".zip") && !f.getName().toLowerCase().endsWith(".jpg")
                                && !f.getName().toLowerCase().endsWith(".jpeg") && !f.getName().toLowerCase().endsWith(".js")
                                && !f.getName().toLowerCase().endsWith(".css") && !f.getName().toLowerCase().endsWith(".png")) {

                            Date d = new Date(f.lastModified());
                            if (d.getTime() > ts) {
                                files.add(f.getAbsolutePath());
                            }
                        }
                    } else if (f.isDirectory()) {
                        if (!f.getPath().trim().endsWith("filesystem")) {
                            if (f.getPath().contains("WEB-INF")) {
                                if (f.getPath().trim().endsWith("WEB-INF") || f.getPath().trim().contains("WEB-INF" + File.separator + "work")) {
                                    listFiles(files, f.getAbsolutePath(), ts);
                                }
                            } else {
                                listFiles(files, f.getAbsolutePath(), ts);
                            }
                        }

                    }
                }
            }
        } catch (Exception e) {
        }
    }

    public String checkCode(String code, int line) {
        if (code == null) return null;
        Pattern p = null;
        Matcher m = null;
        p = Pattern.compile("getruntime|processbuilder|https://github.com/sensepost/reGeorg|SocketChannel|defineClass", Pattern.CASE_INSENSITIVE);
        m = p.matcher(code);
        if (m.find()) {
            return "0";
        }
        return null;
    }

    public List checkFiles(List files) {
        String readline = "";
        List resultList = new Vector();
        int i = 0;
        BaseBean bb = new weaver.general.BaseBean();
        for (int j = 0; j < files.size(); j++) {
            String file = "" + files.get(i);
            i++;
            //xss.writeLog(file,true);
            if (i % 50 == 0) {
                try {
                    bb.writeLog("已完成：" + (i * 1.0 / files.size() * 100) + "%...");
                } catch (Exception e) {
                }
                //System.out.println("已完成："+(i*1.0/files.size()*100)+"%...");
            }
            File f = new File(file);
            if (!f.exists()) continue;
            if ((f.getName().indexOf("debug.jsp") != -1 && file.indexOf("debug") != -1)
                    || (f.getName().indexOf("debugm.jsp") != -1 && file.indexOf("debug") != -1)
                    || (f.getName().indexOf("monitorXOperation.jsp") != -1 && file.indexOf("join") != -1)
                    || (f.getName().indexOf("checkdone.jsp") != -1 && file.indexOf("security") != -1 && file.indexOf("monitor") != -1)
                    || f.getName().indexOf("checkFile.jsp") != -1
                    || f.getName().indexOf("ecologyClusterConfigCheck.jsp") != -1
            ) continue;
            BufferedReader is = null;
            boolean isComment = false;
            try {
                is = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GBK"));
                int lineno = 0;
                //System.out.println("正在检查第"+i+"个文件，总共"+files.size()+"个文件...");
                long spaceCount = 0;
                long totalCount = 0;
                boolean inKeyword = false;
                while ((readline = is.readLine()) != null) {
                    //readline = readline.trim() ;
                    lineno++;
                    if (readline != null) {
                        //if(readline.indexOf("//")!=-1)continue;
                        //totalCount+=readline.length();
						/*for(int c=0;c<readline.length();c++){
							if(readline.charAt(c)==32){
								spaceCount++;
							}else if(readline.charAt(c)==9){
								spaceCount+=4;
							}
						}*/
                        String res = checkCode(readline, lineno);
                        if (res == null) {//正常
                        } else if (res.equals("0")) {//非例外
                            //resultList.add(f.getPath());
                            inKeyword = true;
                            break;
                        }
                    }
                }
                if (inKeyword) {
                    resultList.add(f.getPath());
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
        return resultList;
    }


%>
<body>
<div style="margin:0 auto;width:800px;margin-top:50px;">
    <%
        if (request.getParameter("heart") != null && "1".equals(request.getParameter("heart"))) {
            User user = HrmUserVarify.getUser(request, response);
            if (user == null || !"sysadmin".equals(user.getLoginid())) {
                out.println("false");
            } else {
                out.println("true");
            }
            return;
        }

        User user = HrmUserVarify.getUser(request, response);

        if (user == null || !"sysadmin".equals(user.getLoginid())) {
            out.println("请登陆");
            return;
        }

        long ts = -1;
        if(request.getParameter("ts") != null){
            ts = Long.parseLong(request.getParameter("ts"));
        } else if(request.getParameter("dt") != null){
            String dt = Util.null2String(request.getParameter("dt"));
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            try {
                ts = sdf1.parse(dt).getTime();
            }catch (Exception e){

            }
        }

        //List exceptionFiles = checkFiles(getFiles(request.getRealPath("/")));
        List exceptionFiles = getFiles(request.getRealPath("/"),
                (ts == -1 ? System.currentTimeMillis() : ts) - 3600 * 1000);
        //System.out.println(exceptionFiles);
        out.println("疑似异常文件列表：<p></p>");
        out.println("<div style='color:red;'><b>");
        if (exceptionFiles.size() == 0) {
            out.println("未发现可疑文件。");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String date = Util.null2String(request.getParameter("date"));
        for (int i = 0; i < exceptionFiles.size(); i++) {
            File f = new File("" + exceptionFiles.get(i));
            Date d = new Date(f.lastModified());
            out.println("<p>" + StringUtils.replace(("" + exceptionFiles.get(i)), request.getRealPath("/"), "ecology" + File.separatorChar) + "---->" + sdf.format(d) + "</p>");
        }
        out.println("</b></div>");
    %>
</div>
</body>
</html>
