ftpsession.java~2~
上传用户:lybcsm
上传日期:2007-04-26
资源大小:26k
文件大小:11k
源码类别:

Ftp服务器

开发平台:

Java

  1. package ftpserver;
  2. import java.io.*;
  3. import java.util.*;
  4. import java.net.*;
  5. import java.text.*;
  6. import java.text.SimpleDateFormat;
  7. public class ftpsession implements Runnable {
  8.     private ftpframe frame;
  9.     private String linesep;
  10.     private Socket cs;
  11.     private Socket ds;
  12.     boolean blnBinary;
  13.     BufferedReader inData;
  14.     PrintWriter outData;
  15.     File rootPath=new File(".");
  16.     File currentPath=rootPath;
  17.     String loginname="";
  18.     //Constructor
  19.     public ftpsession(Socket cs,ftpframe frame){
  20.        this.cs=cs;
  21.        this.frame=frame;
  22.        //Line Separator
  23.        linesep=System.getProperty("line.separator");
  24.       }
  25.     public void showMessage(String Msg){
  26.        outData.println(Msg);
  27.        frame.jLog.append(Msg+linesep);
  28.        frame.jLog.setCaretPosition(frame.jLog.getText().length());
  29.      }
  30.     public void resetDefault(){
  31.        blnBinary=false;
  32.        currentPath=rootPath;
  33.      }
  34.     public void run(){
  35.       try{
  36.           inData=new BufferedReader(
  37.                new InputStreamReader(cs.getInputStream()));
  38.           outData=new PrintWriter(cs.getOutputStream(),true);
  39.           showMessage("220 Java FTP Server-<version 1.0>-ready.");
  40.           String ftpCmd="";
  41.           //Process FTP client command
  42.           while(!(ftpCmd.toLowerCase().startsWith("quit"))){
  43.                try{
  44.                     ftpCmd=inData.readLine();
  45.                     ftpCommand(ftpCmd);
  46.                   }
  47.                 catch(IOException ex){
  48.                    ex.printStackTrace();
  49.                    ftpCmd="quit";
  50.                  }
  51.                }
  52.           //Close FTP Session
  53.           try{
  54.               cs.close();
  55.             }
  56.           catch(IOException e){
  57.              e.printStackTrace();
  58.            }
  59.           cs=null;
  60.           inData=null;
  61.           outData=null;
  62.         }
  63.         catch(Exception e){
  64.           e.printStackTrace();
  65.         }
  66.       }
  67.   void ftpCommand(String cmd){
  68.       if(cmd==null) cmd="";
  69.       StringTokenizer ftpCmdtok=new StringTokenizer(cmd.toLowerCase());
  70.       String ftpCmd="";
  71.       try{
  72.           ftpCmd=ftpCmdtok.nextToken();
  73.           SimpleDateFormat formatter=new SimpleDateFormat("EEE,d MMM yyyy hh:mm:ss z");
  74.           System.out.println(formatter.format(new Date())+""+cmd);
  75.           //syst
  76.           if(ftpCmd.equals("syst")){
  77.               showMessage("215 Java FTP Server.");
  78.             }
  79.           //user:Login
  80.           else if("user".indexOf(ftpCmd)!=-1){
  81.              try{
  82.                 loginname=ftpCmdtok.nextToken();
  83.                 showMessage("331 Password required for"+loginname);
  84.               }
  85.              catch(Exception e){
  86.                showMessage("500 User syntax.");
  87.              }
  88.            }
  89.           //pass: Verify password
  90.           else if("pass".indexOf(ftpCmd)!=-1){
  91.               //Add the logic of verifying password here
  92.                 showMessage("230 User"+loginname+"logged in.");
  93.                 resetDefault();
  94.               }
  95.            //port
  96.            else if(ftpCmd.equals("port")){
  97.               try{
  98.                  StringTokenizer arg=new
  99.                  StringTokenizer(ftpCmdtok.nextToken(),",",false);
  100.                  String clientIP="";
  101.                  String ipString="";
  102.                  int cmdPort;
  103.                  if(ds!=null){
  104.                      ds.close();
  105.                      ds=null;
  106.                    }
  107.                  clientIP=arg.nextToken();
  108.                  ipString=clientIP;
  109.                  //get Client IP
  110.                  for(int i=0;i<3;i++){
  111.                     String hIP=arg.nextToken();
  112.                     clientIP=clientIP+"."+hIP;
  113.                     ipString=ipString+","+hIP;
  114.                   }
  115.                  String p1=arg.nextToken();
  116.                  ipString=ipString+","+p1;
  117.                  cmdPort=new Integer(p1).intValue();
  118.                  cmdPort *=256;
  119.                  String p2= arg.nextToken();
  120.                  ipString=ipString+","+p2;
  121.                  cmdPort+=new Integer(p2).intValue();
  122.                  //Establish data connection
  123.                  ds=new Socket(clientIP,cmdPort);
  124.                  showMessage("PORT"+ipString);
  125.                  showMessage("200 PORT command successful.");
  126.                }
  127.              catch(Exception e){
  128.                 showMessage("500 Port number syntax.");
  129.               }
  130.             }
  131.           //type
  132.         else if(ftpCmd.equals("type")){
  133.            try{
  134.               String arg=ftpCmdtok.nextToken();
  135.               //Binary
  136.               if("i".indexOf(arg)!=-1){
  137.                  blnBinary=true;
  138.                  showMessage("200 Type set to I.");
  139.                }
  140.              //ASCII
  141.              else if("a".indexOf(arg)!=-1){
  142.                blnBinary=false;
  143.                showMessage("200 Type set to A.");
  144.               }
  145.              else showMessage("501 Type"+arg+"syntax.");
  146.            }
  147.           catch(Exception e){
  148.             showMessage("500 TYPE syntax.");
  149.             }
  150.           }
  151.         //mode
  152.         else if(ftpCmd.equals("mode")){
  153.            try{
  154.              String arg=ftpCmdtok.nextToken();
  155.              if(arg.equals("s"))
  156.                 showMessage("200 MODE S.");
  157.              else showMessage("501 MODE S not found.");
  158.            }
  159.          catch(Exception e){
  160.            showMessage("500 MODE syntax.");
  161.          }
  162.        }
  163.      //stru
  164.      else if(ftpCmd.equals("stru")){
  165.        try{
  166.           String arg=ftpCmdtok.nextToken();
  167.           if(arg.equals("f"))
  168.               showMessage("200 STRU F.");
  169.           else showMessage("501 STRU F not found.");
  170.         }
  171.       catch(Exception e){
  172.          showMessage("500 STRU syntax.");
  173.        }
  174.      }
  175.    //list
  176.    else if("list".indexOf(ftpCmd)!=-1){
  177.        String arg;
  178.        if(ftpCmdtok.hasMoreTokens())
  179.             arg=ftpCmdtok.nextToken();
  180.        else arg=".";
  181.        ftpList(arg);
  182.     }
  183.   //nlst
  184.   else if("nlst".indexOf(ftpCmd)!=-1){
  185.       String arg;
  186.       if(ftpCmdtok.hasMoreTokens())
  187.           arg=ftpCmdtok.nextToken();
  188.       else arg=".";
  189.       ftpList(arg);
  190.     }
  191.   else if(ftpCmd.equals("cdup"))
  192.       changeDirectory(currentPath.getParent());
  193.   else if(ftpCmd.equals("cwd")){
  194.       try{
  195.          String arg=ftpCmdtok.nextToken();
  196.          changeDirectory(arg);
  197.        }
  198.       catch(Exception e){
  199.          showMessage("500 CWD syntax.");
  200.        }
  201.      }
  202.    //xpwd:Current Directory(pwd)
  203.    else if("xpwd".indexOf(ftpCmd)!=-1){
  204.        showMessage("200 PWD"+currentPath);
  205.      }
  206.    //stor:PUT
  207.   else if(ftpCmd.equals("stor")){
  208.      try{
  209.         String arg=ftpCmdtok.nextToken();
  210.         File path=new File(currentPath,arg);
  211.         if(!path.getCanonicalPath().startsWith(rootPath.getCanonicalPath()))
  212.             throw new SecurityException();
  213.         if(blnBinary)
  214.             putLocalBinaryFile(path,arg);
  215.         else  putLocalASCIIFile(path,arg);
  216.       }
  217.     catch(Exception ex){
  218.        showMessage("500 STOR syntax.");
  219.      }
  220.    }
  221.  //retr:GET
  222.  else if(ftpCmd.equals("retr")){
  223.      try{
  224.         String arg=ftpCmdtok.nextToken();
  225.         File path=new File(currentPath,arg);
  226.         if(!path.getCanonicalPath().startsWith(rootPath.getCanonicalPath()))
  227.             throw new SecurityException();
  228.         getRemoteFile(path,arg);
  229.       }
  230.     catch(Exception ex){
  231.        showMessage("500 RETR syntax.");
  232.     }
  233.   }
  234. //help:Remote Help (remotehelp)
  235.  else if("help".indexOf(ftpCmd)!=-1){
  236.      String strhelp=
  237.         "Java FTP Server -<version 1.0>-ready."+linesep+"Help Message";
  238.       showMessage("200 Remotehelp"+strhelp);
  239.     }
  240.   //noop:No Operation
  241.  else if(ftpCmd.equals("noop"))
  242.      showMessage("200 OK.");
  243.  //quit
  244.  else if(ftpCmd.equals("quit")){
  245.      showMessage("211 Service closing control connection.Goodbye.");
  246.      resetDefault();
  247.    }
  248.  else showMessage("502"+ftpCmd+"nod found.");
  249. }
  250. catch(Exception e){
  251.   showMessage("500"+ftpCmd+"Systax.");
  252. }
  253. }
  254. void ftpList(String arg){
  255.    try{
  256.       File path=new File(currentPath,arg);
  257.       if(!path.getCanonicalPath().startsWith(rootPath.getCanonicalPath()))
  258.          throw new SecurityException();
  259.       if(path.isDirectory()){
  260.          String[] filename=path.list();
  261.          PrintWriter outFile=new
  262.          PrintWriter(ds.getOutputStream(),true);
  263.          if(blnBinary)
  264.              showMessage("150 Opening BINARY mode data connection for"+path+".");
  265.          else showMessage("150 Opening ASCII mode data connection for"+path+".");
  266.        for(int i=0;i<filename.length;i++){
  267.           outFile.println(filename[i]);
  268.         }
  269.        outFile.flush();
  270.        outFile.close();
  271.        showMessage("226 Transfer complete.");
  272.      }
  273.      else showMessage("550 Can not find the file specified.");
  274.    }
  275.    catch(Exception e){
  276.       showMessage("550 Can not find the file specified.");
  277.     }
  278.   }
  279. void changeDirectory(String arg){
  280.   try{
  281.       File path=new File(currentPath,arg);
  282.       if(!path.isDirectory()){
  283.          showMessage("550"+path+"is not a directory.");
  284.        }
  285.       else if(!path.getCanonicalPath().startsWith(rootPath.getCanonicalPath()))
  286.          showMessage("550 Not a subdirectory of"+rootPath.getCanonicalPath());
  287.       else {
  288.          currentPath=new File(path.getCanonicalPath());
  289.          showMessage("250 CWD command successful. OK."+currentPath);
  290.        }
  291.      }
  292.    catch(Exception e){
  293.       showMessage("500"+e);
  294.     }
  295.   }
  296. void putLocalBinaryFile(File file,String arg){
  297.    byte abyte[]= new byte[1024];
  298.    int inbytes;
  299.    try{
  300.       InputStream dataIn=ds.getInputStream();
  301.       FileOutputStream fileOut=new FileOutputStream(file);
  302.       if(blnBinary)
  303.          showMessage("150 Opening BINARY mode data connection for"+arg+".");
  304.       else showMessage("150 Opening ASCII mode data connection for"+arg+".");
  305.       do{
  306.          inbytes=dataIn.read(abyte);
  307.          if(inbytes!=-1)
  308.             fileOut.write(abyte,0,inbytes);
  309.         }
  310.       while(inbytes!=-1);
  311.       fileOut.flush();
  312.       fileOut.close();
  313.       showMessage("226 Closing data connection.Transfer Complete.");
  314.     }
  315.     catch(Exception e){
  316.         showMessage("550 Exception "+e);
  317.       }
  318. }
  319. void putLocalASCIIFile(File file,String arg){
  320.   String strdata;
  321.   try{
  322.       BufferedReader dataIn=new BufferedReader(new InputStreamReader(ds.getInputStream()));
  323.       PrintWriter fileOut=new PrintWriter(
  324.          new FileOutputStream(file),false);
  325.       if(blnBinary)
  326.          showMessage("150 Opening BINARY mode data connection for"+arg+".");
  327.       else showMessage("150 Opening ASCII mode data connection for"+arg+".");
  328.       do{
  329.          strdata=dataIn.readLine();
  330.          if(strdata!=null)
  331.            fileOut.println(strdata);
  332.        }
  333.       while(strdata!=null);
  334.       fileOut.flush();
  335.       fileOut.close();
  336.       showMessage("226 Closing data connection.Transfer Complete.");
  337.     }
  338.    catch(Exception e){
  339.       showMessage("550 Exception "+e);
  340.     }
  341.   }
  342.   void getRemoteFile(File file,String arg){
  343.     byte abyte[]=new byte[1024];
  344.     int inbytes;
  345.     try{
  346.        FileInputStream fileIn=new FileInputStream(file);
  347.        OutputStream dataOut=ds.getOutputStream();
  348.        if(blnBinary)
  349.           showMessage("150 Opening BINARY mode data connection for"+arg+".");
  350.        else showMessage("150 Opening ASCII mode data connection for"+arg+".");
  351.        do{
  352.           inbytes=fileIn.read(abyte);
  353.           if(inbytes!=-1)
  354.              dataOut.write(abyte,0,inbytes);
  355.          }
  356.        while(inbytes!=-1);
  357.        dataOut.flush();
  358.        dataOut.close();
  359.        showMessage("226 Closing data connection.Transfer Complete.");
  360.      }
  361.     catch(Exception e){
  362.       showMessage("550 Exception"+e);
  363.     }
  364.   }
  365. }