/**********************************************************************************
 * 프로그램명 : HttpAdmFileUpload.java 프로그램설명 : 작 성 자 : 작 성 일 : 최신변경일 :
 ***********************************************************************************/

package kr.co.kihyun.beans.totsys.board;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.io.MultipartRequest;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;
import kr.co.kihyun.util.MRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.board.HttpAdmFileUpload")
public class HttpAdmFileUpload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
        private static final Logger LOG = LoggerFactory.getLogger(HttpAdmFileUpload.class);
	MultipartRequest multi = null;

	String sql = "";
	String writeDate = "";

	final int maxSize = 100 * (1024 * 1024);

	// 100메가 제한

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();

		String svrFilename = "";
		String usrFilename = "";
		String boardGroupID = "";
		// String savePath = Moumi.getRoot()+"/totsys/sysadm/board/upfiles/";
		StringBuilder savePath = new StringBuilder(MoumiConfig.getSysAdmFileRoot().getPath())
				.append(System.getProperty("file.separator")).append("board")
				.append(System.getProperty("file.separator")).append("upfiles")
				.append(System.getProperty("file.separator"));

		String connURL = "";

		try {
			multi = new MultipartRequest(req, savePath.toString(), maxSize);
			boardGroupID = multi.getParameter("boardGroupID");
			usrFilename = multi.getParameter("appendFile");

                        //7.위험한 형식 파일 업로드(MultipartRequest)_CWE-434 : Add by KWON,HAN
                        int extIndex = 0 ;
                        extIndex = usrFilename.lastIndexOf('.');
                        if(extIndex < 0 ) {
                            LOG.debug("7.위험한 형식 파일 업로드(MultipartRequest)_CWE-434 : Not Test / usrFilename: {}", usrFilename);
                            out.print("<script language='javascript'>alert('확장자가 없는 파일입니다.');</script>");   
                            return;
                        }                        
                        String file_ext = usrFilename.substring(usrFilename.lastIndexOf('.') + 1); 
                        if( file_ext.equalsIgnoreCase("exe") || file_ext.equalsIgnoreCase("bat") || file_ext.equalsIgnoreCase("sh") ) { 
                            LOG.debug("7.위험한 형식 파일 업로드(MultipartRequest)_CWE-434 : Not Test / usrFilename: {}", usrFilename);
                            out.print("<script language='javascript'>alert('확장자가 [exe, bat, sh]는 업로드가 제한된 파일입니다.');</script>");   
                            return;
                        }
                        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                            
                        // 저장 경로
                        // savePath = Moumi.root+boardGroup.getSavePath(boardGroupID);
                        svrFilename = FileUtil.getName(usrFilename, Integer.toString(MRandom.getInt(100))); // 두자리의 랜덤 수치를 얻음
                        FileItem upFile = multi.getFileItem("appendFile");
                        
                        //3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Add by KWON,HAN
                        String chkFilename = "";
                        chkFilename = savePath + System.getProperty("file.separator") + svrFilename;
                        LOG.debug("chkFilename: {}", chkFilename);
                        if(chkFilename.contains("..") || chkFilename. contains("/")) { // 특수문자열 검증
                            LOG.debug("HttpAdmFileUpload doPost ===");
                            LOG.debug("3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Not Test {}", chkFilename);
                            LOG.debug("============================");
                            return;
                        }
                        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                        
                        upFile.write(new File(savePath + System.getProperty("file.separator") + svrFilename));

                        svrFilename = URLEncoder.encode(svrFilename, "UTF-8");
                        usrFilename = URLEncoder.encode(usrFilename, "UTF-8");

                       //v2. 1.HTTP 응답분할 : Update by KWON,HAN                        
//                        res.sendRedirect("/totsys/sysadm/board/write_file_upload.jsp?execMode=up&svrFilename=" + svrFilename
//                                        + "&usrFilename=" + usrFilename + "&boardGroupID=" + boardGroupID);
                        if (svrFilename != null || usrFilename != null) {               
                            // 수정 : 외부 입력값 필터링
                            String filtered_svrFilename = svrFilename.replaceAll("\r","").replaceAll("\n","");      
                            String filtered_usrFilename = usrFilename.replaceAll("\r","").replaceAll("\n","");      
                            LOG.debug("v2 1.HTTP 응답분할 : HttpAdmFileUpload.doPost() filtered_svrFilename={} Not Test", filtered_svrFilename);
                            LOG.debug("v2 1.HTTP 응답분할 : HttpAdmFileUpload.doPost() filtered_usrFilename={} Not Test", filtered_usrFilename);
                            res.sendRedirect("/totsys/sysadm/board/write_file_upload.jsp?execMode=up&svrFilename=" + filtered_svrFilename
                                            + "&usrFilename=" + filtered_usrFilename + "&boardGroupID=" + boardGroupID);
                        }                        
                        //========================================                        
		} catch (IOException ex) {
			out.println(ServletUtil.getJavaScript(connURL));
			ex.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
