1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation
  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. */
  16. package org.apache.commons.net.ftp;
  17. import java.io.BufferedInputStream;
  18. import java.io.BufferedOutputStream;
  19. import java.io.BufferedReader;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.InputStreamReader;
  23. import java.io.OutputStream;
  24. import java.net.InetAddress;
  25. import java.net.ServerSocket;
  26. import java.net.Socket;
  27. import java.util.Vector;
  28. import org.apache.commons.net.io.FromNetASCIIInputStream;
  29. import org.apache.commons.net.io.ToNetASCIIOutputStream;
  30. import org.apache.commons.net.io.Util;
  31. import org.apache.commons.net.MalformedServerReplyException;
  32. import org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory;
  33. import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
  34. /***
  35. * FTPClient encapsulates all the functionality necessary to store and
  36. * retrieve files from an FTP server. This class takes care of all
  37. * low level details of interacting with an FTP server and provides
  38. * a convenient higher level interface. As with all classes derived
  39. * from <a href="org.apache.commons.net.SocketClient.html"> SocketClient </a>,
  40. * you must first connect to the server with
  41. * <a href="org.apache.commons.net.SocketClient.html#connect"> connect </a>
  42. * before doing anything, and finally
  43. * <a href="org.apache.commons.net.SocketClient.html#disconnect"> disconnect </a>
  44. * after you're completely finished interacting with the server.
  45. * Then you need to check the FTP reply code to see if the connection
  46. * was successful. For example:
  47. * <pre>
  48. * try {
  49. * int reply;
  50. * ftp.connect("ftp.foobar.com");
  51. * System.out.println("Connected to " + server + ".");
  52. * System.out.print(ftp.getReplyString());
  53. *
  54. * // After connection attempt, you should check the reply code to verify
  55. * // success.
  56. * reply = ftp.getReplyCode();
  57. *
  58. * if(!FTPReply.isPositiveCompletion(reply)) {
  59. * ftp.disconnect();
  60. * System.err.println("FTP server refused connection.");
  61. * System.exit(1);
  62. * }
  63. * } catch(IOException e) {
  64. * if(ftp.isConnected()) {
  65. * try {
  66. * ftp.disconnect();
  67. * } catch(IOException f) {
  68. * // do nothing
  69. * }
  70. * }
  71. * System.err.println("Could not connect to server.");
  72. * e.printStackTrace();
  73. * System.exit(1);
  74. * }
  75. * </pre>
  76. * <p>
  77. * Immediately after connecting is the only real time you need to check the
  78. * reply code (because connect is of type void). The convention for all the
  79. * FTP command methods in FTPClient is such that they either return a
  80. * boolean value or some other value.
  81. * The boolean methods return true on a successful completion reply from
  82. * the FTP server and false on a reply resulting in an error condition or
  83. * failure. The methods returning a value other than boolean return a value
  84. * containing the higher level data produced by the FTP command, or null if a
  85. * reply resulted in an error condition or failure. If you want to access
  86. * the exact FTP reply code causing a success or failure, you must call
  87. * <a href="org.apache.commons.net.ftp.FTP.html#getReplyCode"> getReplyCode </a> after
  88. * a success or failure.
  89. * <p>
  90. * The default settings for FTPClient are for it to use
  91. * <code> FTP.ASCII_FILE_TYPE </code>,
  92. * <code> FTP.NON_PRINT_TEXT_FORMAT </code>,
  93. * <code> FTP.STREAM_TRANSFER_MODE </code>, and
  94. * <code> FTP.FILE_STRUCTURE </code>. The only file types directly supported
  95. * are <code> FTP.ASCII_FILE_TYPE </code> and
  96. * <code> FTP.IMAGE_FILE_TYPE </code> (which is the same as
  97. * <code> FTP.BINARY_FILE_TYPE </code>). Because there are at lest 4
  98. * different EBCDIC encodings, we have opted not to provide direct support
  99. * for EBCDIC. To transfer EBCDIC and other unsupported file types you
  100. * must create your own filter InputStreams and OutputStreams and wrap
  101. * them around the streams returned or required by the FTPClient methods.
  102. * FTPClient uses the NetASCII filter streams in
  103. * <a href="Package-org.apache.commons.net.io.html"> org.apache.commons.net.io </a> to provide
  104. * transparent handling of ASCII files. We will consider incorporating
  105. * EBCDIC support if there is enough demand.
  106. * <p>
  107. * <code> FTP.NON_PRINT_TEXT_FORMAT </code>,
  108. * <code> FTP.STREAM_TRANSFER_MODE </code>, and
  109. * <code> FTP.FILE_STRUCTURE </code> are the only supported formats,
  110. * transfer modes, and file structures.
  111. * <p>
  112. * Because the handling of sockets on different platforms can differ
  113. * significantly, the FTPClient automatically issues a new PORT command
  114. * prior to every transfer requiring that the server connect to the client's
  115. * data port. This ensures identical problem-free behavior on Windows, Unix,
  116. * and Macintosh platforms. Additionally, it relieves programmers from
  117. * having to issue the PORT command themselves and dealing with platform
  118. * dependent issues.
  119. * <p>
  120. * Additionally, for security purposes, all data connections to the
  121. * client are verified to ensure that they originated from the intended
  122. * party (host and port). If a data connection is initiated by an unexpected
  123. * party, the command will close the socket and throw an IOException. You
  124. * may disable this behavior with
  125. * <a href="#setRemoteVerificationEnabled">setRemoteVerificationEnabled()</a>.
  126. * <p>
  127. * You should keep in mind that the FTP server may choose to prematurely
  128. * close a connection if the client has been idle for longer than a
  129. * given time period (usually 900 seconds). The FTPClient class will detect a
  130. * premature FTP server connection closing when it receives a
  131. * <a href="org.apache.commons.net.ftp.FTPReply.html#SERVICE_NOT_AVAILABLE">
  132. * FTPReply.SERVICE_NOT_AVAILABLE </a> response to a command.
  133. * When that occurs, the FTP class method encountering that reply will throw
  134. * an <a href="org.apache.commons.net.ftp.FTPConnectionClosedException.html">
  135. * FTPConnectionClosedException </a>.
  136. * <code>FTPConnectionClosedException</code>
  137. * is a subclass of <code> IOException </code> and therefore need not be
  138. * caught separately, but if you are going to catch it separately, its
  139. * catch block must appear before the more general <code> IOException </code>
  140. * catch block. When you encounter an
  141. * <a href="org.apache.commons.net.ftp.FTPConnectionClosedException.html">
  142. * FTPConnectionClosedException </a>, you must disconnect the connection with
  143. * <a href="#disconnect"> disconnect() </a> to properly clean up the
  144. * system resources used by FTPClient. Before disconnecting, you may check the
  145. * last reply code and text with
  146. * <a href="org.apache.commons.net.ftp.FTP.html#getReplyCode"> getReplyCode </a>,
  147. * <a href="org.apache.commons.net.ftp.FTP.html#getReplyString"> getReplyString </a>,
  148. * and
  149. * <a href="org.apache.commons.net.ftp.FTP.html#getReplyStrings"> getReplyStrings</a>.
  150. * You may avoid server disconnections while the client is idle by
  151. * periodicaly sending NOOP commands to the server.
  152. * <p>
  153. * Rather than list it separately for each method, we mention here that
  154. * every method communicating with the server and throwing an IOException
  155. * can also throw a
  156. * <a href="org.apache.commons.net.MalformedServerReplyException.html">
  157. * MalformedServerReplyException </a>, which is a subclass
  158. * of IOException. A MalformedServerReplyException will be thrown when
  159. * the reply received from the server deviates enough from the protocol
  160. * specification that it cannot be interpreted in a useful manner despite
  161. * attempts to be as lenient as possible.
  162. * <p>
  163. * Listing API Examples
  164. * Both paged and unpaged examples of directory listings are available,
  165. * as follows:
  166. * <p>
  167. * Unpaged (whole list) access, using a parser accessible by auto-detect:
  168. * <pre>
  169. * FTPClient f=FTPClient();
  170. * f.connect(server);
  171. * f.login(username, password);
  172. * FTPFile[] files = listFiles(directory);
  173. * </pre>
  174. * <p>
  175. * Paged access, using a parser not accessible by auto-detect. The class
  176. * defined in the first parameter of initateListParsing should be derived
  177. * from org.apache.commons.net.FTPFileEntryParser:
  178. * <pre>
  179. * FTPClient f=FTPClient();
  180. * f.connect(server);
  181. * f.login(username, password);
  182. * FTPListParseEngine engine =
  183. * f.initiateListParsing("com.whatever.YourOwnParser", directory);
  184. *
  185. * while (engine.hasNext()) {
  186. * FTPFile[] files = engine.getNext(25); // "page size" you want
  187. * //do whatever you want with these files, display them, etc.
  188. * //expensive FTPFile objects not created until needed.
  189. * }
  190. * </pre>
  191. * <p>
  192. * Paged access, using a parser accessible by auto-detect:
  193. * <pre>
  194. * FTPClient f=FTPClient();
  195. * f.connect(server);
  196. * f.login(username, password);
  197. * FTPListParseEngine engine = f.initiateListParsing(directory);
  198. *
  199. * while (engine.hasNext()) {
  200. * FTPFile[] files = engine.getNext(25); // "page size" you want
  201. * //do whatever you want with these files, display them, etc.
  202. * //expensive FTPFile objects not created until needed.
  203. * }
  204. * </pre>
  205. * <p> * @author Daniel F. Savarese
  206. * @see FTP
  207. * @see FTPConnectionClosedException
  208. * @see FTPFileEntryParser
  209. * @see FTPFileEntryParserFactory
  210. * @see DefaultFTPFileEntryParserFactory
  211. * @see org.apache.commons.net.MalformedServerReplyException
  212. ***/
  213. public class FTPClient extends FTP
  214. {
  215. /***
  216. * A constant indicating the FTP session is expecting all transfers
  217. * to occur between the client (local) and server and that the server
  218. * should connect to the client's data port to initiate a data transfer.
  219. * This is the default data connection mode when and FTPClient instance
  220. * is created.
  221. ***/
  222. public static final int ACTIVE_LOCAL_DATA_CONNECTION_MODE = 0;
  223. /***
  224. * A constant indicating the FTP session is expecting all transfers
  225. * to occur between two remote servers and that the server
  226. * the client is connected to should connect to the other server's
  227. * data port to initiate a data transfer.
  228. ***/
  229. public static final int ACTIVE_REMOTE_DATA_CONNECTION_MODE = 1;
  230. /***
  231. * A constant indicating the FTP session is expecting all transfers
  232. * to occur between the client (local) and server and that the server
  233. * is in passive mode, requiring the client to connect to the
  234. * server's data port to initiate a transfer.
  235. ***/
  236. public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE = 2;
  237. /***
  238. * A constant indicating the FTP session is expecting all transfers
  239. * to occur between two remote servers and that the server
  240. * the client is connected to is in passive mode, requiring the other
  241. * server to connect to the first server's data port to initiate a data
  242. * transfer.
  243. ***/
  244. public static final int PASSIVE_REMOTE_DATA_CONNECTION_MODE = 3;
  245. private int __dataConnectionMode, __dataTimeout;
  246. private int __passivePort;
  247. private String __passiveHost;
  248. private int __fileType, __fileFormat, __fileStructure, __fileTransferMode;
  249. private boolean __remoteVerificationEnabled;
  250. private long __restartOffset;
  251. private FTPFileEntryParserFactory __parserFactory;
  252. // __systemName is a cached value that should not be referenced directly
  253. // except when assigned in getSystemName and __initDefaults.
  254. private String __systemName;
  255. // __entryParser is a cached value that should not be referenced directly
  256. // except when assigned in listFiles(String, String) and __initDefaults.
  257. private FTPFileEntryParser __entryParser;
  258. /***
  259. * Default FTPClient constructor. Creates a new FTPClient instance
  260. * with the data connection mode set to
  261. * <code> ACTIVE_LOCAL_DATA_CONNECTION_MODE </code>, the file type
  262. * set to <code> FTP.ASCII_FILE_TYPE </code>, the
  263. * file format set to <code> FTP.NON_PRINT_TEXT_FORMAT </code>,
  264. * the file structure set to <code> FTP.FILE_STRUCTURE </code>, and
  265. * the transfer mode set to <code> FTP.STREAM_TRANSFER_MODE </code>.
  266. ***/
  267. public FTPClient()
  268. {
  269. __initDefaults();
  270. __dataTimeout = -1;
  271. __remoteVerificationEnabled = true;
  272. __parserFactory = new DefaultFTPFileEntryParserFactory();
  273. }
  274. private void __initDefaults()
  275. {
  276. __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
  277. __passiveHost = null;
  278. __passivePort = -1;
  279. __fileType = FTP.ASCII_FILE_TYPE;
  280. __fileStructure = FTP.FILE_STRUCTURE;
  281. __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
  282. __fileTransferMode = FTP.STREAM_TRANSFER_MODE;
  283. __restartOffset = 0;
  284. __systemName = null;
  285. __entryParser = null;
  286. }
  287. private String __parsePathname(String reply)
  288. {
  289. int begin, end;
  290. begin = reply.indexOf('"') + 1;
  291. end = reply.indexOf('"', begin);
  292. return reply.substring(begin, end);
  293. }
  294. private void __parsePassiveModeReply(String reply)
  295. throws MalformedServerReplyException
  296. {
  297. int i, index, lastIndex;
  298. String octet1, octet2;
  299. StringBuffer host;
  300. reply = reply.substring(reply.indexOf('(') + 1,
  301. reply.indexOf(')')).trim();
  302. host = new StringBuffer(24);
  303. lastIndex = 0;
  304. index = reply.indexOf(',');
  305. host.append(reply.substring(lastIndex, index));
  306. for (i = 0; i < 3; i++)
  307. {
  308. host.append('.');
  309. lastIndex = index + 1;
  310. index = reply.indexOf(',', lastIndex);
  311. host.append(reply.substring(lastIndex, index));
  312. }
  313. lastIndex = index + 1;
  314. index = reply.indexOf(',', lastIndex);
  315. octet1 = reply.substring(lastIndex, index);
  316. octet2 = reply.substring(index + 1);
  317. // index and lastIndex now used as temporaries
  318. try
  319. {
  320. index = Integer.parseInt(octet1);
  321. lastIndex = Integer.parseInt(octet2);
  322. }
  323. catch (NumberFormatException e)
  324. {
  325. throw new MalformedServerReplyException(
  326. "Could not parse passive host information.\nServer Reply: " + reply);
  327. }
  328. index <<= 8;
  329. index |= lastIndex;
  330. __passiveHost = host.toString();
  331. __passivePort = index;
  332. }
  333. private boolean __storeFile(int command, String remote, InputStream local)
  334. throws IOException
  335. {
  336. OutputStream output;
  337. Socket socket;
  338. if ((socket = _openDataConnection_(command, remote)) == null)
  339. return false;
  340. // TODO: Buffer size may have to be adjustable in future to tune
  341. // performance.
  342. output = new BufferedOutputStream(socket.getOutputStream(),
  343. Util.DEFAULT_COPY_BUFFER_SIZE);
  344. if (__fileType == ASCII_FILE_TYPE)
  345. output = new ToNetASCIIOutputStream(output);
  346. // Treat everything else as binary for now
  347. try
  348. {
  349. Util.copyStream(local, output);
  350. }
  351. catch (IOException e)
  352. {
  353. try
  354. {
  355. socket.close();
  356. }
  357. catch (IOException f)
  358. {}
  359. throw e;
  360. }
  361. output.close();
  362. socket.close();
  363. return completePendingCommand();
  364. }
  365. private OutputStream __storeFileStream(int command, String remote)
  366. throws IOException
  367. {
  368. OutputStream output;
  369. Socket socket;
  370. if ((socket = _openDataConnection_(command, remote)) == null)
  371. return null;
  372. output = socket.getOutputStream();
  373. if (__fileType == ASCII_FILE_TYPE) {
  374. // We buffer ascii transfers because the buffering has to
  375. // be interposed between ToNetASCIIOutputSream and the underlying
  376. // socket output stream. We don't buffer binary transfers
  377. // because we don't want to impose a buffering policy on the
  378. // programmer if possible. Programmers can decide on their
  379. // own if they want to wrap the SocketOutputStream we return
  380. // for file types other than ASCII.
  381. output = new BufferedOutputStream(output,
  382. Util.DEFAULT_COPY_BUFFER_SIZE);
  383. output = new ToNetASCIIOutputStream(output);
  384. }
  385. return new org.apache.commons.net.io.SocketOutputStream(socket, output);
  386. }
  387. /**
  388. * Establishes a data connection with the FTP server, returning
  389. * a Socket for the connection if successful. If a restart
  390. * offset has been set with {@link #setRestartOffset(long)},
  391. * a REST command is issued to the server with the offset as
  392. * an argument before establishing the data connection. Active
  393. * mode connections also cause a local PORT command to be issued.
  394. * <p>
  395. * @param command The text representation of the FTP command to send.
  396. * @param arg The arguments to the FTP command. If this parameter is
  397. * set to null, then the command is sent with no argument.
  398. * @return A Socket corresponding to the established data connection.
  399. * Null is returned if an FTP protocol error is reported at
  400. * any point during the establishment and initialization of
  401. * the connection.
  402. * @exception IOException If an I/O error occurs while either sending a
  403. * command to the server or receiving a reply from the server.
  404. */
  405. protected Socket _openDataConnection_(int command, String arg)
  406. throws IOException
  407. {
  408. Socket socket;
  409. if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE &&
  410. __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE)
  411. return null;
  412. if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE)
  413. {
  414. ServerSocket server;
  415. server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());
  416. if (!FTPReply.isPositiveCompletion(port(getLocalAddress(),
  417. server.getLocalPort())))
  418. {
  419. server.close();
  420. return null;
  421. }
  422. if ((__restartOffset > 0) && !restart(__restartOffset))
  423. {
  424. server.close();
  425. return null;
  426. }
  427. if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
  428. {
  429. server.close();
  430. return null;
  431. }
  432. // For now, let's just use the data timeout value for waiting for
  433. // the data connection. It may be desirable to let this be a
  434. // separately configurable value. In any case, we really want
  435. // to allow preventing the accept from blocking indefinitely.
  436. if (__dataTimeout >= 0)
  437. server.setSoTimeout(__dataTimeout);
  438. socket = server.accept();
  439. server.close();
  440. }
  441. else
  442. { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE
  443. if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
  444. return null;
  445. __parsePassiveModeReply((String)_replyLines.elementAt(0));
  446. socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
  447. if ((__restartOffset > 0) && !restart(__restartOffset))
  448. {
  449. socket.close();
  450. return null;
  451. }
  452. if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
  453. {
  454. socket.close();
  455. return null;
  456. }
  457. }
  458. if (__remoteVerificationEnabled && !verifyRemote(socket))
  459. {
  460. InetAddress host1, host2;
  461. host1 = socket.getInetAddress();
  462. host2 = getRemoteAddress();
  463. socket.close();
  464. throw new IOException(
  465. "Host attempting data connection " + host1.getHostAddress() +
  466. " is not same as server " + host2.getHostAddress());
  467. }
  468. if (__dataTimeout >= 0)
  469. socket.setSoTimeout(__dataTimeout);
  470. return socket;
  471. }
  472. protected void _connectAction_() throws IOException
  473. {
  474. super._connectAction_();
  475. __initDefaults();
  476. }
  477. /***
  478. * Sets the timeout in milliseconds to use when reading from the
  479. * data connection. This timeout will be set immediately after
  480. * opening the data connection.
  481. * <p>
  482. * @param timeout The default timeout in milliseconds that is used when
  483. * opening a data connection socket.
  484. ***/
  485. public void setDataTimeout(int timeout)
  486. {
  487. __dataTimeout = timeout;
  488. }
  489. /**
  490. * set the factory used for parser creation to the supplied factory object.
  491. *
  492. * @param parserFactory
  493. * factory object used to create FTPFileEntryParsers
  494. *
  495. * @see org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory
  496. * @see org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory
  497. */
  498. public void setParserFactory(FTPFileEntryParserFactory parserFactory) {
  499. __parserFactory = parserFactory;
  500. }
  501. /***
  502. * Closes the connection to the FTP server and restores
  503. * connection parameters to the default values.
  504. * <p>
  505. * @exception IOException If an error occurs while disconnecting.
  506. ***/
  507. public void disconnect() throws IOException
  508. {
  509. super.disconnect();
  510. __initDefaults();
  511. }
  512. /***
  513. * Enable or disable verification that the remote host taking part
  514. * of a data connection is the same as the host to which the control
  515. * connection is attached. The default is for verification to be
  516. * enabled. You may set this value at any time, whether the
  517. * FTPClient is currently connected or not.
  518. * <p>
  519. * @param enable True to enable verification, false to disable verification.
  520. ***/
  521. public void setRemoteVerificationEnabled(boolean enable)
  522. {
  523. __remoteVerificationEnabled = enable;
  524. }
  525. /***
  526. * Return whether or not verification of the remote host participating
  527. * in data connections is enabled. The default behavior is for
  528. * verification to be enabled.
  529. * <p>
  530. * @return True if verification is enabled, false if not.
  531. ***/
  532. public boolean isRemoteVerificationEnabled()
  533. {
  534. return __remoteVerificationEnabled;
  535. }
  536. /***
  537. * Login to the FTP server using the provided username and password.
  538. * <p>
  539. * @param username The username to login under.
  540. * @param password The password to use.
  541. * @return True if successfully completed, false if not.
  542. * @exception FTPConnectionClosedException
  543. * If the FTP server prematurely closes the connection as a result
  544. * of the client being idle or some other reason causing the server
  545. * to send FTP reply code 421. This exception may be caught either
  546. * as an IOException or independently as itself.
  547. * @exception IOException If an I/O error occurs while either sending a
  548. * command to the server or receiving a reply from the server.
  549. ***/
  550. public boolean login(String username, String password) throws IOException
  551. {
  552. user(username);
  553. if (FTPReply.isPositiveCompletion(_replyCode))
  554. return true;
  555. // If we get here, we either have an error code, or an intermmediate
  556. // reply requesting password.
  557. if (!FTPReply.isPositiveIntermediate(_replyCode))
  558. return false;
  559. return FTPReply.isPositiveCompletion(pass(password));
  560. }
  561. /***
  562. * Login to the FTP server using the provided username, password,
  563. * and account. If no account is required by the server, only
  564. * the username and password, the account information is not used.
  565. * <p>
  566. * @param username The username to login under.
  567. * @param password The password to use.
  568. * @param account The account to use.
  569. * @return True if successfully completed, false if not.
  570. * @exception FTPConnectionClosedException
  571. * If the FTP server prematurely closes the connection as a result
  572. * of the client being idle or some other reason causing the server
  573. * to send FTP reply code 421. This exception may be caught either
  574. * as an IOException or independently as itself.
  575. * @exception IOException If an I/O error occurs while either sending a
  576. * command to the server or receiving a reply from the server.
  577. ***/
  578. public boolean login(String username, String password, String account)
  579. throws IOException
  580. {
  581. user(username);
  582. if (FTPReply.isPositiveCompletion(_replyCode))
  583. return true;
  584. // If we get here, we either have an error code, or an intermmediate
  585. // reply requesting password.
  586. if (!FTPReply.isPositiveIntermediate(_replyCode))
  587. return false;
  588. pass(password);
  589. if (FTPReply.isPositiveCompletion(_replyCode))
  590. return true;
  591. if (!FTPReply.isPositiveIntermediate(_replyCode))
  592. return false;
  593. return FTPReply.isPositiveCompletion(acct(account));
  594. }
  595. /***
  596. * Logout of the FTP server by sending the QUIT command.
  597. * <p>
  598. * @return True if successfully completed, false if not.
  599. * @exception FTPConnectionClosedException
  600. * If the FTP server prematurely closes the connection as a result
  601. * of the client being idle or some other reason causing the server
  602. * to send FTP reply code 421. This exception may be caught either
  603. * as an IOException or independently as itself.
  604. * @exception IOException If an I/O error occurs while either sending a
  605. * command to the server or receiving a reply from the server.
  606. ***/
  607. public boolean logout() throws IOException
  608. {
  609. return FTPReply.isPositiveCompletion(quit());
  610. }
  611. /***
  612. * Change the current working directory of the FTP session.
  613. * <p>
  614. * @param pathname The new current working directory.
  615. * @return True if successfully completed, false if not.
  616. * @exception FTPConnectionClosedException
  617. * If the FTP server prematurely closes the connection as a result
  618. * of the client being idle or some other reason causing the server
  619. * to send FTP reply code 421. This exception may be caught either
  620. * as an IOException or independently as itself.
  621. * @exception IOException If an I/O error occurs while either sending a
  622. * command to the server or receiving a reply from the server.
  623. ***/
  624. public boolean changeWorkingDirectory(String pathname) throws IOException
  625. {
  626. return FTPReply.isPositiveCompletion(cwd(pathname));
  627. }
  628. /***
  629. * Change to the parent directory of the current working directory.
  630. * <p>
  631. * @return True if successfully completed, false if not.
  632. * @exception FTPConnectionClosedException
  633. * If the FTP server prematurely closes the connection as a result
  634. * of the client being idle or some other reason causing the server
  635. * to send FTP reply code 421. This exception may be caught either
  636. * as an IOException or independently as itself.
  637. * @exception IOException If an I/O error occurs while either sending a
  638. * command to the server or receiving a reply from the server.
  639. ***/
  640. public boolean changeToParentDirectory() throws IOException
  641. {
  642. return FTPReply.isPositiveCompletion(cdup());
  643. }
  644. /***
  645. * Issue the FTP SMNT command.
  646. * <p>
  647. * @param pathname The pathname to mount.
  648. * @return True if successfully completed, false if not.
  649. * @exception FTPConnectionClosedException
  650. * If the FTP server prematurely closes the connection as a result
  651. * of the client being idle or some other reason causing the server
  652. * to send FTP reply code 421. This exception may be caught either
  653. * as an IOException or independently as itself.
  654. * @exception IOException If an I/O error occurs while either sending a
  655. * command to the server or receiving a reply from the server.
  656. ***/
  657. public boolean structureMount(String pathname) throws IOException
  658. {
  659. return FTPReply.isPositiveCompletion(smnt(pathname));
  660. }
  661. /***
  662. * Reinitialize the FTP session. Not all FTP servers support this
  663. * command, which issues the FTP REIN command.
  664. * <p>
  665. * @return True if successfully completed, false if not.
  666. * @exception FTPConnectionClosedException
  667. * If the FTP server prematurely closes the connection as a result
  668. * of the client being idle or some other reason causing the server
  669. * to send FTP reply code 421. This exception may be caught either
  670. * as an IOException or independently as itself.
  671. * @exception IOException If an I/O error occurs while either sending a
  672. * command to the server or receiving a reply from the server.
  673. ***/
  674. boolean reinitialize() throws IOException
  675. {
  676. rein();
  677. if (FTPReply.isPositiveCompletion(_replyCode) ||
  678. (FTPReply.isPositivePreliminary(_replyCode) &&
  679. FTPReply.isPositiveCompletion(getReply())))
  680. {
  681. __initDefaults();
  682. return true;
  683. }
  684. return false;
  685. }
  686. /***
  687. * Set the current data connection mode to
  688. * <code>ACTIVE_LOCAL_DATA_CONNECTION_MODE</code>. No communication
  689. * with the FTP server is conducted, but this causes all future data
  690. * transfers to require the FTP server to connect to the client's
  691. * data port. Additionally, to accommodate differences between socket
  692. * implementations on different platforms, this method causes the
  693. * client to issue a PORT command before every data transfer.
  694. ***/
  695. public void enterLocalActiveMode()
  696. {
  697. __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
  698. __passiveHost = null;
  699. __passivePort = -1;
  700. }
  701. /***
  702. * Set the current data connection mode to
  703. * <code> PASSIVE_LOCAL_DATA_CONNECTION_MODE </code>. Use this
  704. * method only for data transfers between the client and server.
  705. * This method causes a PASV command to be issued to the server
  706. * before the opening of every data connection, telling the server to
  707. * open a data port to which the client will connect to conduct
  708. * data transfers. The FTPClient will stay in
  709. * <code> PASSIVE_LOCAL_DATA_CONNECTION_MODE </code> until the
  710. * mode is changed by calling some other method such as
  711. * <a href="#enterLocalActiveMode"> enterLocalActiveMode() </a>
  712. ***/
  713. public void enterLocalPassiveMode()
  714. {
  715. __dataConnectionMode = PASSIVE_LOCAL_DATA_CONNECTION_MODE;
  716. // These will be set when just before a data connection is opened
  717. // in _openDataConnection_()
  718. __passiveHost = null;
  719. __passivePort = -1;
  720. }
  721. /***
  722. * Set the current data connection mode to
  723. * <code> ACTIVE_REMOTE_DATA_CONNECTION </code>. Use this method only
  724. * for server to server data transfers. This method issues a PORT
  725. * command to the server, indicating the other server and port to which
  726. * it should connect for data transfers. You must call this method
  727. * before EVERY server to server transfer attempt. The FTPClient will
  728. * NOT automatically continue to issue PORT commands. You also
  729. * must remember to call
  730. * <a href="#enterLocalActiveMode"> enterLocalActiveMode() </a> if you
  731. * wish to return to the normal data connection mode.
  732. * <p>
  733. * @param host The passive mode server accepting connections for data
  734. * transfers.
  735. * @param port The passive mode server's data port.
  736. * @return True if successfully completed, false if not.
  737. * @exception FTPConnectionClosedException
  738. * If the FTP server prematurely closes the connection as a result
  739. * of the client being idle or some other reason causing the server
  740. * to send FTP reply code 421. This exception may be caught either
  741. * as an IOException or independently as itself.
  742. * @exception IOException If an I/O error occurs while either sending a
  743. * command to the server or receiving a reply from the server.
  744. ***/
  745. public boolean enterRemoteActiveMode(InetAddress host, int port)
  746. throws IOException
  747. {
  748. if (FTPReply.isPositiveCompletion(port(host, port)))
  749. {
  750. __dataConnectionMode = ACTIVE_REMOTE_DATA_CONNECTION_MODE;
  751. __passiveHost = null;
  752. __passivePort = -1;
  753. return true;
  754. }
  755. return false;
  756. }
  757. /***
  758. * Set the current data connection mode to
  759. * <code> PASSIVE_REMOTE_DATA_CONNECTION_MODE </code>. Use this
  760. * method only for server to server data transfers.
  761. * This method issues a PASV command to the server, telling it to
  762. * open a data port to which the active server will connect to conduct
  763. * data transfers. You must call this method
  764. * before EVERY server to server transfer attempt. The FTPClient will
  765. * NOT automatically continue to issue PASV commands. You also
  766. * must remember to call
  767. * <a href="#enterLocalActiveMode"> enterLocalActiveMode() </a> if you
  768. * wish to return to the normal data connection mode.
  769. * <p>
  770. * @return True if successfully completed, false if not.
  771. * @exception FTPConnectionClosedException
  772. * If the FTP server prematurely closes the connection as a result
  773. * of the client being idle or some other reason causing the server
  774. * to send FTP reply code 421. This exception may be caught either
  775. * as an IOException or independently as itself.
  776. * @exception IOException If an I/O error occurs while either sending a
  777. * command to the server or receiving a reply from the server.
  778. ***/
  779. public boolean enterRemotePassiveMode() throws IOException
  780. {
  781. if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
  782. return false;
  783. __dataConnectionMode = PASSIVE_REMOTE_DATA_CONNECTION_MODE;
  784. __parsePassiveModeReply((String)_replyLines.elementAt(0));
  785. return true;
  786. }
  787. /***
  788. * Returns the hostname or IP address (in the form of a string) returned
  789. * by the server when entering passive mode. If not in passive mode,
  790. * returns null. This method only returns a valid value AFTER a
  791. * data connection has been opened after a call to
  792. * <a href="#enterLocalPassiveMode">enterLocalPassiveMode()</a>.
  793. * This is because FTPClient sends a PASV command to the server only
  794. * just before opening a data connection, and not when you call
  795. * <a href="#enterLocalPassiveMode">enterLocalPassiveMode()</a>.
  796. * <p>
  797. * @return The passive host name if in passive mode, otherwise null.
  798. ***/
  799. public String getPassiveHost()
  800. {
  801. return __passiveHost;
  802. }
  803. /***
  804. * If in passive mode, returns the data port of the passive host.
  805. * This method only returns a valid value AFTER a
  806. * data connection has been opened after a call to
  807. * <a href="#enterLocalPassiveMode">enterLocalPassiveMode()</a>.
  808. * This is because FTPClient sends a PASV command to the server only
  809. * just before opening a data connection, and not when you call
  810. * <a href="#enterLocalPassiveMode">enterLocalPassiveMode()</a>.
  811. * <p>
  812. * @return The data port of the passive server. If not in passive
  813. * mode, undefined.
  814. ***/
  815. public int getPassivePort()
  816. {
  817. return __passivePort;
  818. }
  819. /***
  820. * Returns the current data connection mode (one of the
  821. * <code> _DATA_CONNECTION_MODE </code> constants.
  822. * <p>
  823. * @return The current data connection mode (one of the
  824. * <code> _DATA_CONNECTION_MODE </code> constants.
  825. ***/
  826. public int getDataConnectionMode()
  827. {
  828. return __dataConnectionMode;
  829. }
  830. /***
  831. * Sets the file type to be transferred. This should be one of
  832. * <code> FTP.ASCII_FILE_TYPE </code>, <code> FTP.IMAGE_FILE_TYPE </code>,
  833. * etc. The file type only needs to be set when you want to change the
  834. * type. After changing it, the new type stays in effect until you change
  835. * it again. The default file type is <code> FTP.ASCII_FILE_TYPE </code>
  836. * if this method is never called.
  837. * <p>
  838. * @param fileType The <code> _FILE_TYPE </code> constant indcating the
  839. * type of file.
  840. * @return True if successfully completed, false if not.
  841. * @exception FTPConnectionClosedException
  842. * If the FTP server prematurely closes the connection as a result
  843. * of the client being idle or some other reason causing the server
  844. * to send FTP reply code 421. This exception may be caught either
  845. * as an IOException or independently as itself.
  846. * @exception IOException If an I/O error occurs while either sending a
  847. * command to the server or receiving a reply from the server.
  848. ***/
  849. public boolean setFileType(int fileType) throws IOException
  850. {
  851. if (FTPReply.isPositiveCompletion(type(fileType)))
  852. {
  853. __fileType = fileType;
  854. __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
  855. return true;
  856. }
  857. return false;
  858. }
  859. /***
  860. * Sets the file type to be transferred and the format. The type should be
  861. * one of <code> FTP.ASCII_FILE_TYPE </code>,
  862. * <code> FTP.IMAGE_FILE_TYPE </code>, etc. The file type only needs to
  863. * be set when you want to change the type. After changing it, the new
  864. * type stays in effect until you change it again. The default file type
  865. * is <code> FTP.ASCII_FILE_TYPE </code> if this method is never called.
  866. * The format should be one of the FTP class <code> TEXT_FORMAT </code>
  867. * constants, or if the type is <code> FTP.LOCAL_FILE_TYPE </code>, the
  868. * format should be the byte size for that type. The default format
  869. * is <code> FTP.NON_PRINT_TEXT_FORMAT </code> if this method is never
  870. * called.
  871. * <p>
  872. * @param fileType The <code> _FILE_TYPE </code> constant indcating the
  873. * type of file.
  874. * @param formatOrByteSize The format of the file (one of the
  875. * <code>_FORMAT</code> constants. In the case of
  876. * <code>LOCAL_FILE_TYPE</code>, the byte size.
  877. * <p>
  878. * @return True if successfully completed, false if not.
  879. * @exception FTPConnectionClosedException
  880. * If the FTP server prematurely closes the connection as a result
  881. * of the client being idle or some other reason causing the server
  882. * to send FTP reply code 421. This exception may be caught either
  883. * as an IOException or independently as itself.
  884. * @exception IOException If an I/O error occurs while either sending a
  885. * command to the server or receiving a reply from the server.
  886. ***/
  887. public boolean setFileType(int fileType, int formatOrByteSize)
  888. throws IOException
  889. {
  890. if (FTPReply.isPositiveCompletion(type(fileType, formatOrByteSize)))
  891. {
  892. __fileType = fileType;
  893. __fileFormat = formatOrByteSize;
  894. return true;
  895. }
  896. return false;
  897. }
  898. /***
  899. * Sets the file structure. The default structure is
  900. * <code> FTP.FILE_STRUCTURE </code> if this method is never called.
  901. * <p>
  902. * @param structure The structure of the file (one of the FTP class
  903. * <code>_STRUCTURE</code> constants).
  904. * @return True if successfully completed, false if not.
  905. * @exception FTPConnectionClosedException
  906. * If the FTP server prematurely closes the connection as a result
  907. * of the client being idle or some other reason causing the server
  908. * to send FTP reply code 421. This exception may be caught either
  909. * as an IOException or independently as itself.
  910. * @exception IOException If an I/O error occurs while either sending a
  911. * command to the server or receiving a reply from the server.
  912. ***/
  913. public boolean setFileStructure(int structure) throws IOException
  914. {
  915. if (FTPReply.isPositiveCompletion(stru(structure)))
  916. {
  917. __fileStructure = structure;
  918. return true;
  919. }
  920. return false;
  921. }
  922. /***
  923. * Sets the transfer mode. The default transfer mode
  924. * <code> FTP.STREAM_TRANSFER_MODE </code> if this method is never called.
  925. * <p>
  926. * @param mode The new transfer mode to use (one of the FTP class
  927. * <code>_TRANSFER_MODE</code> constants).
  928. * @return True if successfully completed, false if not.
  929. * @exception FTPConnectionClosedException
  930. * If the FTP server prematurely closes the connection as a result
  931. * of the client being idle or some other reason causing the server
  932. * to send FTP reply code 421. This exception may be caught either
  933. * as an IOException or independently as itself.
  934. * @exception IOException If an I/O error occurs while either sending a
  935. * command to the server or receiving a reply from the server.
  936. ***/
  937. public boolean setFileTransferMode(int mode) throws IOException
  938. {
  939. if (FTPReply.isPositiveCompletion(mode(mode)))
  940. {
  941. __fileTransferMode = mode;
  942. return true;
  943. }
  944. return false;
  945. }
  946. /***
  947. * Initiate a server to server file transfer. This method tells the
  948. * server to which the client is connected to retrieve a given file from
  949. * the other server.
  950. * <p>
  951. * @param filename The name of the file to retrieve.
  952. * @return True if successfully completed, false if not.
  953. * @exception FTPConnectionClosedException
  954. * If the FTP server prematurely closes the connection as a result
  955. * of the client being idle or some other reason causing the server
  956. * to send FTP reply code 421. This exception may be caught either
  957. * as an IOException or independently as itself.
  958. * @exception IOException If an I/O error occurs while either sending a
  959. * command to the server or receiving a reply from the server.
  960. ***/
  961. public boolean remoteRetrieve(String filename) throws IOException
  962. {
  963. if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
  964. __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
  965. return FTPReply.isPositivePreliminary(retr(filename));
  966. return false;
  967. }
  968. /***
  969. * Initiate a server to server file transfer. This method tells the
  970. * server to which the client is connected to store a file on
  971. * the other server using the given filename. The other server must
  972. * have had a <code> remoteRetrieve </code> issued to it by another
  973. * FTPClient.
  974. * <p>
  975. * @param filename The name to call the file that is to be stored.
  976. * @return True if successfully completed, false if not.
  977. * @exception FTPConnectionClosedException
  978. * If the FTP server prematurely closes the connection as a result
  979. * of the client being idle or some other reason causing the server
  980. * to send FTP reply code 421. This exception may be caught either
  981. * as an IOException or independently as itself.
  982. * @exception IOException If an I/O error occurs while either sending a
  983. * command to the server or receiving a reply from the server.
  984. ***/
  985. public boolean remoteStore(String filename) throws IOException
  986. {
  987. if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
  988. __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
  989. return FTPReply.isPositivePreliminary(stor(filename));
  990. return false;
  991. }
  992. /***
  993. * Initiate a server to server file transfer. This method tells the
  994. * server to which the client is connected to store a file on
  995. * the other server using a unique filename based on the given filename.
  996. * The other server must have had a <code> remoteRetrieve </code> issued
  997. * to it by another FTPClient.
  998. * <p>
  999. * @param filename The name on which to base the filename of the file
  1000. * that is to be stored.
  1001. * @return True if successfully completed, false if not.
  1002. * @exception FTPConnectionClosedException
  1003. * If the FTP server prematurely closes the connection as a result
  1004. * of the client being idle or some other reason causing the server
  1005. * to send FTP reply code 421. This exception may be caught either
  1006. * as an IOException or independently as itself.
  1007. * @exception IOException If an I/O error occurs while either sending a
  1008. * command to the server or receiving a reply from the server.
  1009. ***/
  1010. public boolean remoteStoreUnique(String filename) throws IOException
  1011. {
  1012. if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
  1013. __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
  1014. return FTPReply.isPositivePreliminary(stou(filename));
  1015. return false;
  1016. }
  1017. /***
  1018. * Initiate a server to server file transfer. This method tells the
  1019. * server to which the client is connected to store a file on
  1020. * the other server using a unique filename.
  1021. * The other server must have had a <code> remoteRetrieve </code> issued
  1022. * to it by another FTPClient. Many FTP servers require that a base
  1023. * filename be given from which the unique filename can be derived. For
  1024. * those servers use the other version of <code> remoteStoreUnique</code>
  1025. * <p>
  1026. * @return True if successfully completed, false if not.
  1027. * @exception FTPConnectionClosedException
  1028. * If the FTP server prematurely closes the connection as a result
  1029. * of the client being idle or some other reason causing the server
  1030. * to send FTP reply code 421. This exception may be caught either
  1031. * as an IOException or independently as itself.
  1032. * @exception IOException If an I/O error occurs while either sending a
  1033. * command to the server or receiving a reply from the server.
  1034. ***/
  1035. public boolean remoteStoreUnique() throws IOException
  1036. {
  1037. if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
  1038. __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
  1039. return FTPReply.isPositivePreliminary(stou());
  1040. return false;
  1041. }
  1042. // For server to server transfers
  1043. /***
  1044. * Initiate a server to server file transfer. This method tells the
  1045. * server to which the client is connected to append to a given file on
  1046. * the other server. The other server must have had a
  1047. * <code> remoteRetrieve </code> issued to it by another FTPClient.
  1048. * <p>
  1049. * @param filename The name of the file to be appended to, or if the
  1050. * file does not exist, the name to call the file being stored.
  1051. * <p>
  1052. * @return True if successfully completed, false if not.
  1053. * @exception FTPConnectionClosedException
  1054. * If the FTP server prematurely closes the connection as a result
  1055. * of the client being idle or some other reason causing the server
  1056. * to send FTP reply code 421. This exception may be caught either
  1057. * as an IOException or independently as itself.
  1058. * @exception IOException If an I/O error occurs while either sending a
  1059. * command to the server or receiving a reply from the server.
  1060. ***/
  1061. public boolean remoteAppend(String filename) throws IOException
  1062. {
  1063. if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
  1064. __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
  1065. return FTPReply.isPositivePreliminary(stor(filename));
  1066. return false;
  1067. }
  1068. /***
  1069. * There are a few FTPClient methods that do not complete the
  1070. * entire sequence of FTP commands to complete a transaction. These
  1071. * commands require some action by the programmer after the reception
  1072. * of a positive intermediate command. After the programmer's code
  1073. * completes its actions, it must call this method to receive
  1074. * the completion reply from the server and verify the success of the
  1075. * entire transaction.
  1076. * <p>
  1077. * For example,
  1078. * <pre>
  1079. * InputStream input;
  1080. * OutputStream output;
  1081. * input = new FileInputStream("foobaz.txt");
  1082. * output = ftp.storeFileStream("foobar.txt")
  1083. * if(!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) {
  1084. * input.close();
  1085. * output.close();
  1086. * ftp.logout();
  1087. * ftp.disconnect();
  1088. * System.err.println("File transfer failed.");
  1089. * System.exit(1);
  1090. * }
  1091. * Util.copyStream(input, output);
  1092. * input.close();
  1093. * output.close();
  1094. * // Must call completePendingCommand() to finish command.
  1095. * if(!ftp.completePendingCommand()) {
  1096. * ftp.logout();
  1097. * ftp.disconnect();
  1098. * System.err.println("File transfer failed.");
  1099. * System.exit(1);
  1100. * }
  1101. * </pre>
  1102. * <p>
  1103. * @return True if successfully completed, false if not.
  1104. * @exception FTPConnectionClosedException
  1105. * If the FTP server prematurely closes the connection as a result
  1106. * of the client being idle or some other reason causing the server
  1107. * to send FTP reply code 421. This exception may be caught either
  1108. * as an IOException or independently as itself.
  1109. * @exception IOException If an I/O error occurs while either sending a
  1110. * command to the server or receiving a reply from the server.
  1111. ***/
  1112. public boolean completePendingCommand() throws IOException
  1113. {
  1114. return FTPReply.isPositiveCompletion(getReply());
  1115. }
  1116. /***
  1117. * Retrieves a named file from the server and writes it to the given
  1118. * OutputStream. This method does NOT close the given OutputStream.
  1119. * If the current file type is ASCII, line separators in the file are
  1120. * converted to the local representation.
  1121. * <p>
  1122. * @param remote The name of the remote file.
  1123. * @param local The local OutputStream to which to write the file.
  1124. * @return True if successfully completed, false if not.
  1125. * @exception FTPConnectionClosedException
  1126. * If the FTP server prematurely closes the connection as a result
  1127. * of the client being idle or some other reason causing the server
  1128. * to send FTP reply code 421. This exception may be caught either
  1129. * as an IOException or independently as itself.
  1130. * @exception CopyStreamException If an I/O error occurs while actually
  1131. * transferring the file. The CopyStreamException allows you to
  1132. * determine the number of bytes transferred and the IOException
  1133. * causing the error. This exception may be caught either
  1134. * as an IOException or independently as itself.
  1135. * @exception IOException If an I/O error occurs while either sending a
  1136. * command to the server or receiving a reply from the server.
  1137. ***/
  1138. public boolean retrieveFile(String remote, OutputStream local)
  1139. throws IOException
  1140. {
  1141. InputStream input;
  1142. Socket socket;
  1143. if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null)
  1144. return false;
  1145. // TODO: Buffer size may have to be adjustable in future to tune
  1146. // performance.
  1147. input = new BufferedInputStream(socket.getInputStream(),
  1148. Util.DEFAULT_COPY_BUFFER_SIZE);
  1149. if (__fileType == ASCII_FILE_TYPE)
  1150. input = new FromNetASCIIInputStream(input);
  1151. // Treat everything else as binary for now
  1152. try
  1153. {
  1154. Util.copyStream(input, local);
  1155. }
  1156. catch (IOException e)
  1157. {
  1158. try
  1159. {
  1160. socket.close();
  1161. }
  1162. catch (IOException f)
  1163. {}
  1164. throw e;
  1165. }
  1166. socket.close();
  1167. return completePendingCommand();
  1168. }
  1169. /***
  1170. * Returns an InputStream from which a named file from the server
  1171. * can be read. If the current file type is ASCII, the returned
  1172. * InputStream will convert line separators in the file to
  1173. * the local representation. You must close the InputStream when you
  1174. * finish reading from it. The InputStream itself will take care of
  1175. * closing the parent data connection socket upon being closed. To
  1176. * finalize the file transfer you must call
  1177. * <a href="#completePendingCommand"> completePendingCommand </a> and
  1178. * check its return value to verify success.
  1179. * <p>
  1180. * @param remote The name of the remote file.
  1181. * @return An InputStream from which the remote file can be read. If
  1182. * the data connection cannot be opened (e.g., the file does not
  1183. * exist), null is returned (in which case you may check the reply
  1184. * code to determine the exact reason for failure).
  1185. * @exception FTPConnectionClosedException
  1186. * If the FTP server prematurely closes the connection as a result
  1187. * of the client being idle or some other reason causing the server
  1188. * to send FTP reply code 421. This exception may be caught either
  1189. * as an IOException or independently as itself.
  1190. * @exception IOException If an I/O error occurs while either sending a
  1191. * command to the server or receiving a reply from the server.
  1192. ***/
  1193. public InputStream retrieveFileStream(String remote) throws IOException
  1194. {
  1195. InputStream input;
  1196. Socket socket;
  1197. if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null)
  1198. return null;
  1199. input = socket.getInputStream();
  1200. if (__fileType == ASCII_FILE_TYPE) {
  1201. // We buffer ascii transfers because the buffering has to
  1202. // be interposed between FromNetASCIIOutputSream and the underlying
  1203. // socket input stream. We don't buffer binary transfers
  1204. // because we don't want to impose a buffering policy on the
  1205. // programmer if possible. Programmers can decide on their
  1206. // own if they want to wrap the SocketInputStream we return
  1207. // for file types other than ASCII.
  1208. input = new BufferedInputStream(input,
  1209. Util.DEFAULT_COPY_BUFFER_SIZE);
  1210. input = new FromNetASCIIInputStream(input);
  1211. }
  1212. return new org.apache.commons.net.io.SocketInputStream(socket, input);
  1213. }
  1214. /***
  1215. * Stores a file on the server using the given name and taking input
  1216. * from the given InputStream. This method does NOT close the given
  1217. * InputStream. If the current file type is ASCII, line separators in
  1218. * the file are transparently converted to the NETASCII format (i.e.,
  1219. * you should not attempt to create a special InputStream to do this).
  1220. * <p>
  1221. * @param remote The name to give the remote file.
  1222. * @param local The local InputStream from which to read the file.
  1223. * @return True if successfully completed, false if not.
  1224. * @exception FTPConnectionClosedException
  1225. * If the FTP server prematurely closes the connection as a result
  1226. * of the client being idle or some other reason causing the server
  1227. * to send FTP reply code 421. This exception may be caught either
  1228. * as an IOException or independently as itself.
  1229. * @exception CopyStreamException If an I/O error occurs while actually
  1230. * transferring the file. The CopyStreamException allows you to
  1231. * determine the number of bytes transferred and the IOException
  1232. * causing the error. This exception may be caught either
  1233. * as an IOException or independently as itself.
  1234. * @exception IOException If an I/O error occurs while either sending a
  1235. * command to the server or receiving a reply from the server.
  1236. ***/
  1237. public boolean storeFile(String remote, InputStream local)
  1238. throws IOException
  1239. {
  1240. return __storeFile(FTPCommand.STOR, remote, local);
  1241. }
  1242. /***
  1243. * Returns an OutputStream through which data can be written to store
  1244. * a file on the server using the given name. If the current file type
  1245. * is ASCII, the returned OutputStream will convert line separators in
  1246. * the file to the NETASCII format (i.e., you should not attempt to
  1247. * create a special OutputStream to do this). You must close the
  1248. * OutputStream when you finish writing to it. The OutputStream itself
  1249. * will take care of closing the parent data connection socket upon being
  1250. * closed. To finalize the file transfer you must call
  1251. * <a href="#completePendingCommand"> completePendingCommand </a> and
  1252. * check its return value to verify success.
  1253. * <p>
  1254. * @param remote The name to give the remote file.
  1255. * @return An OutputStream through which the remote file can be written. If
  1256. * the data connection cannot be opened (e.g., the file does not
  1257. * exist), null is returned (in which case you may check the reply
  1258. * code to determine the exact reason for failure).
  1259. * @exception FTPConnectionClosedException
  1260. * If the FTP server prematurely closes the connection as a result
  1261. * of the client being idle or some other reason causing the server
  1262. * to send FTP reply code 421. This exception may be caught either
  1263. * as an IOException or independently as itself.
  1264. * @exception IOException If an I/O error occurs while either sending a
  1265. * command to the server or receiving a reply from the server.
  1266. ***/
  1267. public OutputStream storeFileStream(String remote) throws IOException
  1268. {
  1269. return __storeFileStream(FTPCommand.STOR, remote);
  1270. }
  1271. /***
  1272. * Appends to a file on the server with the given name, taking input
  1273. * from the given InputStream. This method does NOT close the given
  1274. * InputStream. If the current file type is ASCII, line separators in
  1275. * the file are transparently converted to the NETASCII format (i.e.,
  1276. * you should not attempt to create a special InputStream to do this).
  1277. * <p>
  1278. * @param remote The name of the remote file.
  1279. * @param local The local InputStream from which to read the data to
  1280. * be appended to the remote file.
  1281. * @return True if successfully completed, false if not.
  1282. * @exception FTPConnectionClosedException
  1283. * If the FTP server prematurely closes the connection as a result
  1284. * of the client being idle or some other reason causing the server
  1285. * to send FTP reply code 421. This exception may be caught either
  1286. * as an IOException or independently as itself.
  1287. * @exception CopyStreamException If an I/O error occurs while actually
  1288. * transferring the file. The CopyStreamException allows you to
  1289. * determine the number of bytes transferred and the IOException
  1290. * causing the error. This exception may be caught either
  1291. * as an IOException or independently as itself.
  1292. * @exception IOException If an I/O error occurs while either sending a
  1293. * command to the server or receiving a reply from the server.
  1294. ***/
  1295. public boolean appendFile(String