1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
|
/*
* $Id: FtpSimpleClient.java,v 0.0 2009/01/21 00:00:00 t-imamura Exp $
*
* Copyright (c) 2009 t-imamura, All rights reserved.
*/
package ftp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* FTP簡易クライアント.
* <br>
* FTPの制御ソケットを作成し、直接コマンドを送信し操作を行います。
* PORTモード・PASVモード両方のモードにも対応しています。
* ファイルの送受信以外に、ディレクトリ操作なども行えます。
*
* <pre>
* FtpSimpleClient ftp = new FtpSimpleClient("ftp.example.com", false);
* // 接続
* ftp.connect();
* // ログイン
* ftp.logon("user", "pass");
*
* // ファイル送信
* byte[] data = 転送データ;
* ftp.put("/home/user/ftptest.txt", data);
*
* // ファイル受信
* OutputStream os = new OutputStream();
* ftp.get("/home/user/ftptest.txt", baos);
*
* // ファイル削除
* ftp.dele("/home/user/ftptest.txt");
*
* // 切断
* ftp.disconnect();
* </pre>
*/
public class FtpSimpleClient {
/** FTP制御ポート番号 */
private static final int FTP_PORT_NO = 21;
/** アノニマスログインID */
private static final String ANONYMOUS_USERID = "anonymous";
/** PASVモード時の接続先を取得する為の正規表現 */
private static final Pattern PASV_REPLY_MESSAGE = Pattern.compile(
"227 .*\\(([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3})\\).*");
/** カレントディレクトリを取得する為の正規表現 */
private static final Pattern PWD_REPLY_MESSAGE = Pattern.compile("257 .*\"(.*)\".*");
/** IPアドレス */
private final InetAddress address;
/** ポート番号 */
private final int portNo;
/** FTP制御ソケット */
private Socket ftpCtrl;
/** FTP制御入力(OutputStream) */
private BufferedWriter ctrlOut;
/** FTP制御出力(InputStream) */
private BufferedReader ctrlIn;
/** パッシブモードか */
private boolean passive = false;
/** デバッグモード */
private boolean debug = false;
/**
* FTP簡易クライアントオブジェクトを構築します。
*
* @param address IPアドレス or ホスト名
* @param passive パッシブモードか
* @throws UnknownHostException <code>address</code>のIPアドレスが見つからなかった場合
*/
public FtpSimpleClient(String address, boolean passive) throws UnknownHostException {
this(InetAddress.getByName(address), FTP_PORT_NO, passive);
}
/**
* FTP簡易クライアントオブジェクトを構築します。
*
* @param address IPアドレス
* @param passive パッシブモードか
*/
public FtpSimpleClient(InetAddress address, boolean passive) {
this(address, FTP_PORT_NO, passive);
}
/**
* FTP簡易クライアントオブジェクトを構築します。
*
* @param address IPアドレス
* @param portNo 制御ポート番号
* @param passive パッシブモードか
*/
public FtpSimpleClient(InetAddress address, int portNo, boolean passive) {
this.address = address;
this.portNo = portNo;
this.passive = passive;
}
@Override
protected void finalize() throws Throwable {
disconnect();
super.finalize();
}
/**
* パッシブモードかを設定します。
*
* @param passive パッシブモードか
*/
public void setPassive(boolean passive) {
this.passive = passive;
}
/**
* デバッグモードかを設定します。
*
* @param debug デバッグモードか
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* FTPコマンドを送信します。
* <br>
* 受信したリプライメッセージが必要な場合は、内容を入れる {@link StringBuffer} を
* <code>replyMessage</code> に指定します。
*
* @param command FTPコマンド
* @param replyMessage リプライメッセージ
* @return リプライコード
*/
private int sendCommand(String command, StringBuffer replyMessage) {
int replyCode = 0;
try {
// コマンド送信
if (command != null) {
debug("FTP > %s", command);
ctrlOut.write(command);
ctrlOut.write("\r\n");
ctrlOut.flush();
}
// レスポンス受信
String reply = null;
while ((reply = ctrlIn.readLine()) != null) {
debug("FTP < %s", reply);
if (replyMessage != null)
replyMessage.append(reply);
// リプライコード
replyCode = (reply.charAt(0) - '0') * 100;
replyCode += (reply.charAt(1) - '0') * 10;
replyCode += (reply.charAt(2) - '0') * 1;
// 続かない場合は、終わり
if (reply.charAt(3) == ' ') break;
replyCode = 0;
if (replyMessage != null)
replyMessage.append("\n");
}
} catch (IOException e) {
replyCode = 0;
}
return replyCode;
}
/**
* FTPコマンドを送信し、データコネクションを作成します。
*
* @param command FTPコマンド
* @return データコネクション
* @throws IOException 入出力エラーが発生した場合
*/
private Socket creatDataConnection(String command) throws IOException {
return passive ? creatDataConnectionPasv(command) : creatDataConnectionPort(command);
}
/**
* FTPコマンドを送信し、PORTモードでデータコネクションを作成します。
*
* @param command FTPコマンド
* @return データコネクション
* @throws IOException 入出力エラーが発生した場合
*/
private Socket creatDataConnectionPort(String command) throws IOException {
Socket ftpData = null;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(0, 1, ftpCtrl.getLocalAddress());
byte[] ip = serverSocket.getInetAddress().getAddress();
int port = serverSocket.getLocalPort();
debug("INFO: Open data connection. (%d.%d.%d.%d:%d)",
(ip[0] & 0xFF), (ip[1] & 0xFF), (ip[2] & 0xFF), (ip[3] & 0xFF), port);
String cmdPort = "PORT "
+ (ip[0] & 0xff) + "," + (ip[1] & 0xff) + ","
+ (ip[2] & 0xff) + "," + (ip[3] & 0xff) + ","
+ ((port / 256) & 0xff) + "," + (port & 0xff);
if (sendCommand(cmdPort, null) == 200) {
if (sendCommand(command, null) == 150) {
ftpData = serverSocket.accept();
}
}
} catch (IOException e) {
// Bug: nullであることが明らかな参照ftpDataを無駄にnullチェックしています
// if (ftpData != null) ftpData.close();
// ftpData = null;
throw e;
} finally {
if (serverSocket != null)
serverSocket.close();
}
return ftpData;
}
/**
* FTPコマンドを送信し、PASVモードでデータコネクションを作成します。
*
* @param command FTPコマンド
* @return データコネクション
* @throws IOException 入出力エラーが発生した場合
*/
private Socket creatDataConnectionPasv(String command) throws IOException {
Socket ftpData = null;
try {
StringBuffer msg = new StringBuffer();
if (sendCommand("PASV", msg) != 227) {
return null;
}
Matcher match = PASV_REPLY_MESSAGE.matcher(msg.toString());
if (!match.find() || match.groupCount() != 6) {
// データコネクションの情報が取れない。
return null;
}
String address = match.group(1) + "." + match.group(2) + "."
+ match.group(3) + "." + match.group(4);
int portNo = Integer.parseInt(match.group(5)) * 256
+ Integer.parseInt(match.group(6));
debug("INFO: Connect data connection. (%s:%d)", address, portNo);
ftpData = new Socket(address, portNo);
if (sendCommand(command, null) != 150) {
ftpData.close();
ftpData = null;
}
} catch (NumberFormatException e) {
ftpData = null;
} catch (IOException e) {
if (ftpData != null)
ftpData.close();
ftpData = null;
throw e;
}
return ftpData;
}
/**
* 接続します。
*
* @return 成功したか
*/
public boolean connect() {
if (ftpCtrl != null) return false;
try {
ftpCtrl = new Socket(address, portNo);
ctrlOut = new BufferedWriter(new OutputStreamWriter(ftpCtrl.getOutputStream()));
ctrlIn = new BufferedReader(new InputStreamReader(ftpCtrl.getInputStream()));
if (sendCommand(null, null) != 220) {
disconnect();
return false;
}
} catch (IOException e) {
try {
if (ctrlIn != null)
ctrlIn.close();
if (ctrlOut != null)
ctrlOut.close();
if (ftpCtrl != null)
ftpCtrl.close();
} catch (IOException ex) {
// クローズの例外は無視
}
ftpCtrl = null;
ctrlOut = null;
ctrlIn = null;
return false;
}
return true;
}
/**
* 切断します。
*
* @return 成功したか
*/
public boolean disconnect() {
if (ftpCtrl == null) return false;
boolean result = true;
// 終了
if (sendCommand("QUIT", null) != 221) {
result = false;
}
try {
if (ctrlIn != null)
ctrlIn.close();
} catch (IOException e) {
result = false;
} finally {
ctrlIn = null;
}
try {
if (ctrlOut != null)
ctrlOut.close();
} catch (IOException e) {
result = false;
} finally {
ctrlOut = null;
}
try {
if (ftpCtrl != null)
ftpCtrl.close();
} catch (IOException e) {
result = false;
} finally {
ftpCtrl = null;
}
return result;
}
/**
* アノニマスログインします。
*
* @return 成功したか
*/
public boolean anonymousLogon() {
return logon(ANONYMOUS_USERID, ANONYMOUS_USERID);
}
/**
* アノニマスログインします。
*
* @param email メールアドレス
* @return 成功したか
*/
public boolean anonymousLogon(String email) {
return logon(ANONYMOUS_USERID, email);
}
/**
* ログインします。
*
* @param user ユーザ名
* @param pass パスワード
* @return 成功したか
*/
public boolean logon(String user, String pass) {
if (user == null) return false;
if (pass == null) return false;
if (ftpCtrl == null) connect();
boolean result = true;
// ユーザ
if (sendCommand("USER " + user, null) != 331) {
result = false;
}
// パスワード
if (sendCommand("PASS " + pass, null) != 230) {
result = false;
}
return result;
}
/**
* 転送データの形式を設定します。
*
* @param binary バイナリデータか
* @return 成功したか
*/
public boolean type(boolean binary) {
if (ftpCtrl == null) return false;
boolean result = true;
if (sendCommand(binary ? "TYPE I" : "TYPE A", null) != 250) {
result = false;
}
return result;
}
/**
* データを送信します。
*
* @param name ファイル名
* @param data データ
* @return 成功したか
*/
public boolean put(String name, byte[] data) {
if (ftpCtrl == null) return false;
if (name == null || name.isEmpty()) return false;
if (data == null) return false;
boolean result = true;
Socket ftpData = null;
OutputStream dataOut = null;
InputStream dataIn = null;
try {
ftpData = creatDataConnection("STOR " + name);
dataOut = ftpData.getOutputStream();
dataIn = ftpData.getInputStream();
// データ送信
dataOut.write(data);
dataOut.close();
dataOut = null;
if (sendCommand(null, null) != 226) {
result = false;
}
} catch (IOException e) {
result = false;
} finally {
try {
if (dataIn != null)
dataIn.close();
} catch (IOException e) {
result = false;
} finally {
dataIn = null;
}
try {
if (dataOut != null)
dataOut.close();
} catch (IOException e) {
result = false;
} finally {
dataOut = null;
}
try {
if (ftpData != null)
ftpData.close();
} catch (IOException e) {
result = false;
} finally {
ftpData = null;
}
}
return result;
}
/**
* データを受信します。
*
* @param name ファイル名
* @param data データ
* @return 成功したか
*/
public boolean get(String name, OutputStream data) {
if (ftpCtrl == null) return false;
if (name == null || name.isEmpty()) return false;
if (data == null) return false;
boolean result = true;
Socket ftpData = null;
OutputStream dataOut = null;
InputStream dataIn = null;
try {
ftpData = creatDataConnection("RETR " + name);
dataOut = ftpData.getOutputStream();
dataIn = ftpData.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
// データ受信
while ((len = dataIn.read(buf)) != -1) {
data.write(buf, 0, len);
}
dataIn.close();
dataIn = null;
if (sendCommand(null, null) != 226) {
result = false;
}
} catch (IOException e) {
result = false;
} finally {
try {
if (dataIn != null)
dataIn.close();
} catch (IOException e) {
result = false;
} finally {
dataIn = null;
}
try {
if (dataOut != null)
dataOut.close();
} catch (IOException e) {
result = false;
} finally {
dataOut = null;
}
try {
if (ftpData != null)
ftpData.close();
} catch (IOException e) {
result = false;
} finally {
ftpData = null;
}
}
return result;
}
/**
* ファイルを削除します。
*
* @param name ファイル名
* @return 成功したか
*/
public boolean dele(String name) {
if (ftpCtrl == null) return false;
if (name == null || name.isEmpty()) return false;
boolean result = true;
if (sendCommand("DELE " + name, null) != 250) {
result = false;
}
return result;
}
/**
* 1つ上位のディレクトリにカレントディレクトリを移動します。
*
* @return 成功したか
*/
public boolean cdup() {
if (ftpCtrl == null) return false;
boolean result = true;
if (sendCommand("CDUP", null) != 250) {
result = false;
}
return result;
}
/**
* カレントディレクトリを移動します。
* ディレクトリパスは、絶対パスもしくは相対パスで指定します。
*
* @param path ディレクトリパス
* @return 成功したか
*/
public boolean cwd(String path) {
if (ftpCtrl == null) return false;
if (path == null || path.isEmpty()) return false;
boolean result = true;
if (sendCommand("CWD " + path, null) != 250) {
result = false;
}
return result;
}
/**
* 指定したディレクトリを削除します。
* ディレクトリパスは、絶対パスもしくは相対パスで指定します。
*
* @param path ディレクトリパス
* @return 成功したか
*/
public boolean rmd(String path) {
if (ftpCtrl == null) return false;
if (path == null || path.isEmpty()) return false;
boolean result = true;
if (sendCommand("RMD " + path, null) != 250) {
result = false;
}
return result;
}
/**
* 指定したディレクトリを作成します。
* ディレクトリパスは、絶対パスもしくは相対パスで指定します。
*
* @param path ディレクトリパス
* @return 成功したか
*/
public boolean mkd(String path) {
if (ftpCtrl == null) return false;
if (path == null || path.isEmpty()) return false;
boolean result = true;
if (sendCommand("MKD " + path, null) != 250) {
result = false;
}
return result;
}
/**
* カレントディレクトリのファイル一覧を取得します。
*
* @return ファイル一覧
*/
public String list() {
return list(null);
}
/**
* ファイル一覧を取得します。
*
* @param path ディレクトリパス
* @return ファイル一覧
*/
public String list(String path) {
if (ftpCtrl == null) return null;
Socket ftpData = null;
OutputStream dataOut = null;
InputStream dataIn = null;
ByteArrayOutputStream result = new ByteArrayOutputStream();
String command = "LIST";
if(path != null) command += " " + path;
try {
ftpData = creatDataConnection(command);
dataOut = ftpData.getOutputStream();
dataIn = ftpData.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
// データ受信
while ((len = dataIn.read(buf)) != -1) {
result.write(buf, 0, len);
}
result.flush();
dataIn.close();
dataIn = null;
if (sendCommand(null, null) != 226) {
result.reset();
}
} catch (IOException e) {
result.reset();
} finally {
try {
if (dataIn != null)
dataIn.close();
} catch (IOException e) {
result.reset();
} finally {
dataIn = null;
}
try {
if (dataOut != null)
dataOut.close();
} catch (IOException e) {
result.reset();
} finally {
dataOut = null;
}
try {
if (ftpData != null)
ftpData.close();
} catch (IOException e) {
result.reset();
} finally {
ftpData = null;
}
}
return result.toString();
}
/**
* カレントディレクトリを取得します。
*
* @return ディレクトリパス
*/
public String pwd() {
if (ftpCtrl == null) return null;
StringBuffer reply = new StringBuffer();
if (sendCommand("PWD", reply) != 257) {
return null;
}
Matcher match = PWD_REPLY_MESSAGE.matcher(reply.toString());
if (!match.find() || match.groupCount() != 1) {
return null;
}
return match.group(1);
}
/**
* 指定された書式の文字列と引数を使って、書式付き文字列をコンソールに出力します。
* <code>debug == false</code> の場合は、出力されません。
*
* @param format 書式文字列
* @param args 書式文字列内の書式指示子により参照される引数
*/
private void debug(String format, Object... args) {
if (!debug) return;
System.out.println(String.format(format, args));
}
} |
最終更新時間:2009年07月30日 12時11分21秒 指摘や意見などあればSandBoxのBBSへ。
FtpSimpleClient.java FtpSimpleClientTest.java