001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.vfs2.provider.sftp;
018
019import java.io.IOException;
020import java.io.InputStreamReader;
021import java.util.Collection;
022
023import org.apache.commons.vfs2.Capability;
024import org.apache.commons.vfs2.FileObject;
025import org.apache.commons.vfs2.FileSystemException;
026import org.apache.commons.vfs2.FileSystemOptions;
027import org.apache.commons.vfs2.UserAuthenticationData;
028import org.apache.commons.vfs2.provider.AbstractFileName;
029import org.apache.commons.vfs2.provider.AbstractFileSystem;
030import org.apache.commons.vfs2.provider.GenericFileName;
031import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
032
033import com.jcraft.jsch.ChannelExec;
034import com.jcraft.jsch.ChannelSftp;
035import com.jcraft.jsch.JSchException;
036import com.jcraft.jsch.Session;
037import com.jcraft.jsch.SftpException;
038
039/**
040 * Represents the files on an SFTP server.
041 */
042public class SftpFileSystem
043    extends AbstractFileSystem
044{
045    private static final int SLEEP_MILLIS = 100;
046
047    private static final int EXEC_BUFFER_SIZE = 128;
048
049    private static final long LAST_MOD_TIME_ACCURACY = 1000L;
050
051    private Session session;
052
053    // private final JSch jSch;
054
055    private ChannelSftp idleChannel;
056
057    /**
058     * Cache for the user ID (-1 when not set)
059     */
060    private int uid = -1;
061
062    /**
063     * Cache for the user groups ids (null when not set)
064     */
065    private int[] groupsIds;
066
067    protected SftpFileSystem(final GenericFileName rootName,
068                             final Session session,
069                             final FileSystemOptions fileSystemOptions)
070    {
071        super(rootName, null, fileSystemOptions);
072        this.session = session;
073    }
074
075    @Override
076    protected void doCloseCommunicationLink()
077    {
078        if (idleChannel != null)
079        {
080            idleChannel.disconnect();
081            idleChannel = null;
082        }
083
084        if (session != null)
085        {
086            session.disconnect();
087            session = null;
088        }
089    }
090
091    /**
092     * Returns an SFTP channel to the server.
093     *
094     * @throws FileSystemException if a session cannot be created.
095     * @throws IOException if an I/O error is detected.
096     */
097    protected ChannelSftp getChannel() throws IOException
098    {
099        ensureSession();
100        try
101        {
102            // Use the pooled channel, or create a new one
103            final ChannelSftp channel;
104            if (idleChannel != null)
105            {
106                channel = idleChannel;
107                idleChannel = null;
108            }
109            else
110            {
111                channel = (ChannelSftp) session.openChannel("sftp");
112                channel.connect();
113                final Boolean userDirIsRoot =
114                    SftpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(getFileSystemOptions());
115                final String workingDirectory = getRootName().getPath();
116                if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
117                {
118                    try
119                    {
120                        channel.cd(workingDirectory);
121                    }
122                    catch (final SftpException e)
123                    {
124                        throw new FileSystemException("vfs.provider.sftp/change-work-directory.error",
125                            workingDirectory, e);
126                    }
127                }
128            }
129
130            final String fileNameEncoding = SftpFileSystemConfigBuilder.getInstance().getFileNameEncoding(
131                    getFileSystemOptions());
132
133            if (fileNameEncoding != null) {
134                try {
135                    channel.setFilenameEncoding(fileNameEncoding);
136                } catch (final SftpException e) {
137                    throw new FileSystemException("vfs.provider.sftp/filename-encoding.error", fileNameEncoding);
138                }
139            }
140                        return channel;
141        }
142        catch (final JSchException e)
143        {
144            throw new FileSystemException("vfs.provider.sftp/connect.error", getRootName(), e);
145        }
146    }
147
148    /**
149     * Ensures that the session link is established.
150     *
151     * @throws FileSystemException if a session cannot be created.
152     */
153    private void ensureSession() throws FileSystemException
154    {
155        if (this.session == null || !this.session.isConnected())
156        {
157            doCloseCommunicationLink();
158
159            // channel closed. e.g. by freeUnusedResources, but now we need it again
160            Session session;
161            UserAuthenticationData authData = null;
162            try
163            {
164                final GenericFileName rootName = (GenericFileName) getRootName();
165
166                authData = UserAuthenticatorUtils.authenticate(getFileSystemOptions(),
167                        SftpFileProvider.AUTHENTICATOR_TYPES);
168
169                session = SftpClientFactory.createConnection(
170                        rootName.getHostName(),
171                        rootName.getPort(),
172                        UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
173                                UserAuthenticatorUtils.toChar(rootName.getUserName())),
174                        UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
175                                UserAuthenticatorUtils.toChar(rootName.getPassword())),
176                        getFileSystemOptions());
177            }
178            catch (final Exception e)
179            {
180                throw new FileSystemException("vfs.provider.sftp/connect.error", getRootName(), e);
181            }
182            finally
183            {
184                UserAuthenticatorUtils.cleanup(authData);
185            }
186            this.session = session;
187        }
188    }
189
190    /**
191     * Returns a channel to the pool.
192     */
193    protected void putChannel(final ChannelSftp channel)
194    {
195        if (idleChannel == null)
196        {
197            // put back the channel only if it is still connected
198            if (channel.isConnected() && !channel.isClosed())
199            {
200                idleChannel = channel;
201            }
202        }
203        else
204        {
205            channel.disconnect();
206        }
207    }
208
209    /**
210     * Adds the capabilities of this file system.
211     */
212    @Override
213    protected void addCapabilities(final Collection<Capability> caps)
214    {
215        caps.addAll(SftpFileProvider.capabilities);
216    }
217
218    /**
219     * Creates a file object.  This method is called only if the requested
220     * file is not cached.
221     */
222    @Override
223    protected FileObject createFile(final AbstractFileName name)
224        throws FileSystemException
225    {
226        return new SftpFileObject(name, this);
227    }
228
229    /**
230     * Last modification time is only an int and in seconds, thus can be off by 999.
231     *
232     * @return 1000
233     */
234    @Override
235    public double getLastModTimeAccuracy()
236    {
237        return LAST_MOD_TIME_ACCURACY;
238    }
239
240    /**
241     * Gets the (numeric) group IDs.
242     *
243     * @return the (numeric) group IDs.
244     * @throws JSchException If a problem occurs while retrieving the group IDs.
245     * @throws IOException if an I/O error is detected.
246     * @since 2.1
247     */
248    public int[] getGroupsIds() throws JSchException, IOException
249    {
250        if (groupsIds == null)
251        {
252            final StringBuilder output = new StringBuilder();
253            final int code = executeCommand("id -G", output);
254            if (code != 0)
255            {
256                throw new JSchException("Could not get the groups id of the current user (error code: " + code + ")");
257            }
258
259            // Retrieve the different groups
260            final String[] groups = output.toString().trim().split("\\s+");
261
262            final int[] groupsIds = new int[groups.length];
263            for (int i = 0; i < groups.length; i++)
264            {
265                groupsIds[i] = Integer.parseInt(groups[i]);
266            }
267
268            this.groupsIds = groupsIds;
269        }
270        return groupsIds;
271    }
272
273    /**
274     * Get the (numeric) group IDs.
275     *
276     * @return The numeric user ID
277     * @throws JSchException If a problem occurs while retrieving the group ID.
278     * @throws IOException if an I/O error is detected.
279     * @since 2.1
280     */
281    public int getUId() throws JSchException, IOException
282    {
283        if (uid < 0)
284        {
285            final StringBuilder output = new StringBuilder();
286            final int code = executeCommand("id -u", output);
287            if (code != 0)
288            {
289                throw new FileSystemException("Could not get the user id of the current user (error code: " + code
290                        + ")");
291            }
292            uid = Integer.parseInt(output.toString().trim());
293        }
294        return uid;
295    }
296
297    /**
298     * Execute a command and returns the (standard) output through a StringBuilder.
299     *
300     * @param command The command
301     * @param output The output
302     * @return The exit code of the command
303     * @throws JSchException if a JSch error is detected.
304     * @throws FileSystemException if a session cannot be created.
305     * @throws IOException if an I/O error is detected.
306     */
307    private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException
308    {
309        ensureSession();
310        final ChannelExec channel = (ChannelExec) session.openChannel("exec");
311
312        channel.setCommand(command);
313        channel.setInputStream(null);
314        final InputStreamReader stream = new InputStreamReader(channel.getInputStream());
315        channel.setErrStream(System.err, true);
316        channel.connect();
317
318        // Read the stream
319        final char[] buffer = new char[EXEC_BUFFER_SIZE];
320        int read;
321        while ((read = stream.read(buffer, 0, buffer.length)) >= 0)
322        {
323            output.append(buffer, 0, read);
324        }
325        stream.close();
326
327        // Wait until the command finishes (should not be long since we read the output stream)
328        while (!channel.isClosed())
329        {
330            try
331            {
332                Thread.sleep(SLEEP_MILLIS);
333            }
334            catch (final Exception ee)
335            {
336                // TODO: swallow exception, really?
337            }
338        }
339        channel.disconnect();
340        return channel.getExitStatus();
341    }
342}