1/*
2 * Copyright 2008 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.mockftpserver.fake.command;
17
18import org.mockftpserver.core.command.Command;
19import org.mockftpserver.core.command.ReplyCodes;
20import org.mockftpserver.core.session.Session;
21import org.mockftpserver.core.session.SessionKeys;
22import org.mockftpserver.core.util.IoUtil;
23import org.mockftpserver.fake.filesystem.FileEntry;
24import org.mockftpserver.fake.filesystem.FileSystemEntry;
25import org.mockftpserver.fake.filesystem.FileSystemException;
26
27import java.io.ByteArrayOutputStream;
28import java.io.IOException;
29import java.io.InputStream;
30
31/**
32 * CommandHandler for the RETR command. Handler logic:
33 * <ol>
34 * <li>If the user has not logged in, then reply with 530 and terminate</li>
35 * <li>If the required pathname parameter is missing, then reply with 501 and terminate</li>
36 * <li>If the pathname parameter does not specify a valid, existing filename, then reply with 550 and terminate</li>
37 * <li>If the current user does not have read access to the file at the specified path or execute permission to its directory, then reply with 550 and terminate</li>
38 * <li>Send an initial reply of 150</li>
39 * <li>Send the contents of the named file across the data connection</li>
40 * <li>If there is an error reading the file, then reply with 550 and terminate</li>
41 * <li>Send a final reply with 226</li>
42 * </ol>
43 *
44 * @author Chris Mair
45 * @version $Revision$ - $Date$
46 */
47public class RetrCommandHandler extends AbstractFakeCommandHandler {
48
49    protected void handle(Command command, Session session) {
50        verifyLoggedIn(session);
51        this.replyCodeForFileSystemException = ReplyCodes.READ_FILE_ERROR;
52
53        String path = getRealPath(session, command.getRequiredParameter(0));
54        FileSystemEntry entry = getFileSystem().getEntry(path);
55        verifyFileSystemCondition(entry != null, path, "filesystem.doesNotExist");
56        verifyFileSystemCondition(!entry.isDirectory(), path, "filesystem.isNotAFile");
57        FileEntry fileEntry = (FileEntry) entry;
58
59        // User must have read permission to the file
60        verifyReadPermission(session, path);
61
62        // User must have execute permission to the parent directory
63        verifyExecutePermission(session, getFileSystem().getParent(path));
64
65        sendReply(session, ReplyCodes.TRANSFER_DATA_INITIAL_OK);
66        InputStream input = fileEntry.createInputStream();
67        session.openDataConnection();
68        byte[] bytes = null;
69        try {
70            bytes = IoUtil.readBytes(input);
71        }
72        catch (IOException e) {
73            LOG.error("Error reading from file [" + fileEntry.getPath() + "]", e);
74            throw new FileSystemException(fileEntry.getPath(), null, e);
75        }
76        finally {
77            try {
78                input.close();
79            }
80            catch (IOException e) {
81                LOG.error("Error closing InputStream for file [" + fileEntry.getPath() + "]", e);
82            }
83        }
84
85        if (isAsciiMode(session)) {
86            bytes = convertLfToCrLf(bytes);
87        }
88        session.sendData(bytes, bytes.length);
89        session.closeDataConnection();
90        sendReply(session, ReplyCodes.TRANSFER_DATA_FINAL_OK);
91    }
92
93    /**
94     * Within the specified byte array, replace all LF (\n) that are NOT preceded by a CR (\r) into CRLF (\r\n).
95     *
96     * @param bytes - the bytes to be converted
97     * @return the result of converting LF to CRLF
98     */
99    protected byte[] convertLfToCrLf(byte[] bytes) {
100        ByteArrayOutputStream out = new ByteArrayOutputStream();
101        char lastChar = ' ';
102        for (int i = 0; i < bytes.length; i++) {
103            char ch = (char) bytes[i];
104            if (ch == '\n' && lastChar != '\r') {
105                out.write('\r');
106                out.write('\n');
107            } else {
108                out.write(bytes[i]);
109            }
110            lastChar = ch;
111        }
112        return out.toByteArray();
113    }
114
115    private boolean isAsciiMode(Session session) {
116        // Defaults to true
117        return session.getAttribute(SessionKeys.ASCII_TYPE) != Boolean.FALSE;
118    }
119
120}