⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 remoteverifyservlet.java

📁 一套JAVA的CA证书签发系统.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     *   result=grant     *   dn-ou=OU     *   dn-o=O     *   dn-cn=CN     *   end     *   </pre>     * </li>     * <li>     * A rejected reply:     * <pre>     *   status=200 OK     *   result=reject     *   message=Wrong username/password.     *   end     *   </pre>     * </li>     * <li>     * A failed request:     * <pre>     *   status=400     *   message=Server can't handle given protocol version     *   end     *   </pre>     * </li>     * </ul>     * </p>     *     * @param req DOCUMENT ME!     * @param res DOCUMENT ME!     *     * @exception ServletException when servlet mechanism fails     * @exception IOException when something fails with basic I/O, such as reading/writing to     *            client.     */    protected void doPost(HttpServletRequest req, HttpServletResponse res)        throws ServletException, IOException {        increaseAccess();        res.setContentType("text/plain");        ServletOutputStream out = res.getOutputStream();        //        // Keep this for logging.        String remoteAddr = req.getRemoteAddr();        //        // Extract information about request type and how we were called.        // Also suitable for logging.        String method = req.getMethod();        String path = req.getServletPath();        //        // Extract the parameters passed to us using the utility        // HttpUtils.parsePostData available in the servlet package.        ServletInputStream in = req.getInputStream();        int len = req.getContentLength();        //        // Will this work with len == -1 ?? (Unknown length)        // Don't know, but -1 is possible only if we have a GET        // and we KNOW this is a POST :-)        Hashtable params = HttpUtils.parsePostData(len, in);        try {            // Extract parameters from client            String username = "";            String password = "";            String version = "";            try {                username = ((String[]) params.get(REQUEST_USERNAME))[0];                password = ((String[]) params.get(REQUEST_PASSWORD))[0];                version = ((String[]) params.get(REQUEST_VERSION))[0];            } catch (ArrayIndexOutOfBoundsException ignored) {                // No parameters will result in "" being used from                // step above            } catch (NullPointerException ignoredAsWell) {                // No parameters will result in "" being used from                // step above            }            //            // Extract and verify protocol version            int majorversion = 0;            int minorversion = 0;            // Split version on '.'            int dotAt = version.indexOf('.');            if (dotAt == -1) {                // No separator entered, assume minor == 0                try {                    majorversion = Integer.parseInt(version);                } catch (NumberFormatException nfe) {                    errorLog("doPost: Got " + nfe + " on call from " + remoteAddr +                        " for username '" + username +                        "'. Asuming version is OK. Tried to parse '" + version + "'");                }                minorversion = 0;            } else {                try {                    majorversion = Integer.parseInt(version.substring(0, dotAt));                    minorversion = Integer.parseInt(version.substring(1 + dotAt, version.length()));                } catch (NumberFormatException nfe) {                    errorLog("doPost: Got " + nfe + " on call from " + remoteAddr +                        " for username '" + username +                        "'. Asuming version is OK. Tried to parse '" + version + "'");                }            }            //            // Now let's make sure we can play this tune            if ((majorversion == PROTOCOL_VERSION_MAJOR) &&                    (minorversion <= PROTOCOL_VERSION_MINOR)) {                // We're in business, protocol matches                // This is the call to what the customer usually                // needs to care about.                // The call itself seldom needs to be changed...                //                // You should, of course, make sure that you like                // the given code, as it's only an example!                AuthResult result = authenticateUser(username, password);                //                // Now build the result we'll send to the client                // We treat grant and rejects slightly different                if (result.granted()) {                    increaseGranted();                    out.println(RESPONSE_STATUS + "=" + MSG_OK);                    out.println(RESPONSE_RESULT + "=" + GRANT);                    debugLog("GRANTING request for '" + username + "'");                    // loop over all elements in resultHash, print one by one                    Hashtable resultParams = result.getResult();                    String key;                    // Standard code for printing a Hash.                    for (Enumeration keys = resultParams.keys(); keys.hasMoreElements();) {                        key = (String) keys.nextElement();                        out.println(key + "=" + ((String) resultParams.get(key)));                    }                } else { // rejected.                    increaseRejected();                    out.println(RESPONSE_STATUS + "=" + MSG_OK);                    out.println(RESPONSE_RESULT + "=" + REJECT);                    out.println(RESPONSE_MESSAGE + "=" + result.getReason());                    debugLog("REJECTING request for '" + username + "'. Reason: " +                        result.getReason());                }                out.println(RESPONSE_END); // The end of response token            } else {                // protocol missmatch, reject and return                out.println(RESPONSE_STATUS + "=" + MSG_PROTOCOL_MISMATCH);                out.println("message=Accepting at most " + PROTOCOL_VERSION_MAJOR + "." +                    PROTOCOL_VERSION_MINOR);                errorLog("PROTOCOL MISSMATCH. Got '" + version + "', but accepts only '" +                    PROTOCOL_VERSION_MAJOR + "." + PROTOCOL_VERSION_MINOR + "'");            }        } catch (Exception e) {            out.println(RESPONSE_STATUS + "=" + MSG_GENERIC_ERROR + e);            out.println(RESPONSE_END); // The end of response token            errorLog("?Caught exception ", e);        }    }    /**     * Gets information for a user.     *     * @param username user to lookup.     *     * @return <b>null</b> (if no user found) or String[] with [0] as passwd and [1] as certificate     *         contents.     */    protected String[] findUserData(String username) {        if (users == null) {            debugLog("findUserData: No users found. Returning null for user '" + username + "'.");            return null;        }        String[] result = (String[]) users.get(username.toLowerCase());        if (result != null) {            debugLog("findUserData: Information for user '" + username + "'found.");        } else {            debugLog("findUserData: No information for user '" + username + "'found.");        }        return result;    }    protected synchronized void increaseAccess() {        countAccess++;    }    protected synchronized void increaseGranted() {        countGranted++;    }    protected synchronized void increaseRejected() {        countRejected++;    }    /**     * Loads userdatabase at first access.     *     * @param config DOCUMENT ME!     *     * @exception javax.servlet.ServletException The exception description.     */    public void init(ServletConfig config) throws ServletException {        super.init(config);        log = Logger.getLogger(this.getClass());        debugLog((new Date()).toString() + " RemoteVerify.init:");        loadUserDB();    }    /**     * Load user DB at servlet load time, ie first access to servlet. It's ok to call this method     * multiple times, since it simply clears the old cached data each time it's called.     */    protected synchronized void loadUserDB() {        // First we clear cached users.        Hashtable oldEnUsers = users;        users = null;        BufferedReader in = null;        debugLog((new Date()).toString() + "loadUserDB: Loading from file: '" +            getInitParameter("dbfilename") + "'.");        InputStream is = getServletContext().getResourceAsStream(getInitParameter("dbfilename"));        in = new BufferedReader(new InputStreamReader(is));        String line;        boolean readMore = true;        try {            while (readMore) {                line = in.readLine();                if (line == null) {                    readMore = false;                } else {                    if (!line.startsWith(LINE_COMMENT)) {                        Enumeration lineParts = new StringTokenizer(line, RECORD_SEPARATOR);                        String username = (String) lineParts.nextElement();                        debugLog("loadUserDB: username=" + username);                        String password = (String) lineParts.nextElement();                        debugLog("loadUserDB: password=" + password);                        String userDataString = (String) lineParts.nextElement();                        debugLog("loadUserDB: userDataString=" + userDataString);                        StringTokenizer st = new StringTokenizer(userDataString, DNPART_DELIMITER);                        debugLog("loadUserDB: st=" + st);                        String[] userData = new String[2];                        userData[0] = password;                        userData[1] = userDataString;                        debugLog("loadUserDB: calling addUserData." + userData);                        addUserData(username, userData);                    } else {                        debugLog("loadUserDB: skipping comment line." + line);                    }                }            }        } catch (IOException ioe) {            errorLog("loadUserDB: FAILED TO PARSE FILE: '" + getInitParameter("dbfilename") + "'.");            errorLog("loadUserDB: Got exception: ", ioe);            errorLog("loadUserDB: Restored previous version of DB");            users = oldEnUsers;        } finally {            try {                in.close();            } catch (IOException ignored) {            }        }        debugLog((new Date()).toString() + "loadUserDB: Done.");    }    /**     * Adds information for a user in an instance to users.     *     * @param username user to lookup.     * @param userData String[] with [0] as passwd and [1] as certificate contents.     */    protected void addUserData(String username, String[] userData) {        if (users == null) {            debugLog("addUserData: Creating new users.");            users = new Hashtable();        }        debugLog("addUserData: Adding '" + username);        users.put(username.toLowerCase(), userData);    }}// RemoteVerifyServlet

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -