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

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

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;

import java.io.*;
import java.net.*;

import kr.co.kihyun.io.*;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.report.HttpFileUpload")
public class HttpFileUpload extends HttpServlet {

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

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

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

	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 savePath = Moumi.getRoot()+"/totsys/repoper/fileUpload/";
		String savePath = MoumiConfig.getTotRoot().getPath() + System.getProperty("file.separator") + "repoper"
				+ System.getProperty("file.separator") + "fileUpload";
		String connURL = "";
		int succNum = -1;

		try {
			multi = new MultipartRequest(req, savePath);
			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;
                        }  
                        //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++                        

                        String docID = multi.getParameter("docID");
                        String dpID = multi.getParameter("deptID");

                        FileItem upFile = multi.getFileItem("appendFile");

                        svrFilename = docID + "_" + dpID + "_" + usrFilename;

                        //3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Add by KWON,HAN
                        //4.디렉토리 경로 조작(getProperty)_CWE-22/23/36
                        String chkFilename = "";
                        chkFilename = savePath + System.getProperty("file.separator") + svrFilename;
                        LOG.debug("chkFilename: {}", chkFilename); 
                        if(chkFilename.contains("..") || chkFilename. contains("/")) { // 특수문자열 검증
                            LOG.debug("HttpFileUpload doPost ===");
                            LOG.debug("3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Not Test {}", chkFilename);
                            LOG.debug("=========================");
                            return;
                        }
                        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                                
                        // succNum = upFile.saveAs(savePath+"/"+svrFilename);
                        upFile.write(new File(savePath + System.getProperty("file.separator") + svrFilename));

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

                        if (succNum == 1) {
                                res.sendRedirect("/totsys/repoper/mydocbox/tempbox/write_file_upload.jsp?execMode=up&svrFilename="
                                                + svrFilename + "&usrFilename=" + usrFilename + "&docID=" + docID + "&deptID=" + dpID);
                                return;
                        } else if (succNum == 2) {
                                out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.fileNameCh")));
                        } else if (succNum == -1) {
                                out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.incorrectFileName")));
                        }

                        connURL = "location='/totsys/repoper/mydocbox/tempbox/write_file_upload.jsp?execMode=jump&svrFilename="
                                        + svrFilename + "&usrFilename=" + usrFilename + "&docID=" + docID + "&deptID=" + dpID + "';";
                        
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN 
//                        out.println(ServletUtil.getJavaScript(connURL));
                        
                        // 수정 : 외부 입력값 필터링
                        String filtered_connURL = connURL.replaceAll("<","").replaceAll(">","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpFileUpload.doPost() try filtered_connURL={}, Not Test", filtered_connURL);
                        out.println(ServletUtil.getJavaScript(filtered_connURL));
                        //========================================                          
                        
		} catch (IOException ex) {
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN  
//			out.println(ServletUtil.getJavaScript(connURL));
                        
                        // 수정 : 외부 입력값 필터링
                        String filtered_connURL = connURL.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpFileUpload.doPost() catch filtered_connURL={}, Not Test", filtered_connURL);
                        out.println(ServletUtil.getJavaScript(filtered_connURL));
                        //========================================  
                        
			ex.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
