Serwer w Java

0

Witam.
Muszę szybko stworzyć serwer FTP w Java, a nie czuję się w tym jeszcze...
Potrzebuję pomocy: mam kod z dekompilatora pewnego gotowego i prostego (pomijając GUI) serwera, ale zawiera masę błędów. Zwracam się więc o pomoc do kogoś kto się zna. Powiedzmy, że jeśli uda się to komuś rozgryźć, to ma u mnie duuuuużą flachę....
Proszę pisać na e-mail: [email protected]
Pozdrawiam
Gabriela


/////klasa FtpGoServer
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.*;

import javax.imageio.ImageIO;
import javax.swing.*;




public class FtpGoServer extends JFrame implements ActionListener, Runnable
{
	FtpGoServer()
    {
        try
        {
            setIconImage(ImageIO.read(getClass().getResource("l")));
        }
        catch(Exception exception) { }
        setTitle(" FtpGoServer 2.1");
        JPanel jpanel = new JPanel(new GridLayout(7, 1));
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(jpanel, "Center");
        JPanel jpanel1 = new JPanel();
        jpanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Root directory for FTP access"));
        jpanel1.add(dname = new JLabel());
        jpanel.add(jpanel1);
        jpanel1.setToolTipText("Local directory used as virtual FTP root");
        jpanel1 = new JPanel();
        ButtonGroup buttongroup = new ButtonGroup();
        jpanel.add(jpanel1);
        jpanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Access permission"));
        no = new JRadioButton("Read only");
        buttongroup.add(no);
        jpanel1.add(no);
        no.setSelected(true);
        no.setToolTipText("All files in the current directory and below it are read only");
        yes = new JRadioButton("Read & write");
        buttongroup.add(yes);
        jpanel1.add(yes);
        yes.setToolTipText("Read/Write access to current dir and below");
        jpanel1 = new JPanel();
        buttongroup = new ButtonGroup();
        jpanel.add(jpanel1);
        jpanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Control socket timeout"));
        nto = new JRadioButton("No timeout");
        buttongroup.add(nto);
        jpanel1.add(nto);
        nto.setSelected(true);
        yto = new JRadioButton("Timeout after 20 minutes inactivity");
        buttongroup.add(yto);
        jpanel1.add(yto);
        jpanel1 = new JPanel(new GridLayout(1, 2));
        jpanel.add(jpanel1);
        JPanel jpanel2 = new JPanel();
        jpanel1.add(jpanel2);
        jpanel2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Read only password"));
        jpanel2.add(ropass = new JPasswordField(10));
        ropass.setToolTipText("<html>This login password is required for read only access.<br>If not specified (ie. blank) all logins get read only access.<br>Username is always ignored.</html>");
        JPanel jpanel3 = new JPanel();
        jpanel1.add(jpanel3);
        jpanel3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Read/Write password"));
        jpanel3.add(rwpass = new JPasswordField(10));
        rwpass.setToolTipText("<html>If read & write is allowed this password is required for write access.<br>Neither password is ever stored on disk.</html>");
        jpanel1 = new JPanel();
        jpanel1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Server URL"));
        jpanel1.add(url = new JLabel("Not running"));
        jpanel.add(jpanel1);
        jpanel1 = new JPanel(new GridLayout(1, 2));
        JPanel jpanel4 = new JPanel();
        jpanel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "MBytes uploaded"));
        jpanel4.add(upl = new JLabel("0"));
        jpanel1.add(jpanel4);
        JPanel jpanel5 = new JPanel();
        jpanel5.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "MBytes downloaded"));
        jpanel5.add(dwl = new JLabel("0"));
        jpanel1.add(jpanel5);
        jpanel.add(jpanel1);
        ImageIcon imageicon = new ImageIcon(getClass().getResource("d"));
        jpanel1 = new JPanel(new FlowLayout(1, 3, 15));
        jpanel.add(jpanel1);
        jpanel1.setBorder(BorderFactory.createEtchedBorder());
        jpanel1.add(start = new JButton("Start"));
        start.addActionListener(this);
        start.setIcon(imageicon);
        start.setToolTipText("Start FTP server running");
        jpanel1.add(dir = new JButton("Set root"));
        dir.addActionListener(this);
        dir.setToolTipText("Directory in local file system to use as virtual root");
        dir.setIcon(imageicon);
        jpanel1.add(about = new JButton("About"));
        about.addActionListener(this);
        about.setIcon(imageicon);
        jpanel1.add(exit = new JButton("Exit"));
        exit.addActionListener(this);
        exit.setIcon(imageicon);
        lp();
        pack();
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension dimension1 = getSize();
        setLocation((dimension.width - dimension1.width) / 2, (dimension.height - dimension1.height) / 2);
        setVisible(true);
        addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent windowevent)
            {
                System.exit(0);
            }
            
            final FtpGoServer this$0;

            
            {
                this$0 = FtpGoServer.this;
                super();
            }
        });
    }
	public void actionPerformed(ActionEvent actionevent)
    {
        Object obj = actionevent.getSource();
        if(obj == exit)
            System.exit(0);
        else
        if(obj == start)
        {
            sp();
            if(yes.isSelected() && rwpass.getPassword().length == 0 && JOptionPane.showConfirmDialog(this, "Are you sure you want to allow Read/Write access with no password?", "Security warning", 0) == 1)
                return;
            start.setEnabled(false);
            dir.setEnabled(false);
            no.setEnabled(false);
            yes.setEnabled(false);
            ropass.setEditable(false);
            ropass.setEnabled(false);
            rwpass.setEditable(false);
            rwpass.setEnabled(false);
            about.setEnabled(false);
            url.setFont(new Font("Dialog", 1, 15));
            url.setForeground(Color.red);
            url.setText("Starting...");
            (new Thread(this)).start();
        } else
        if(obj == dir)
        {
            JFileChooser jfilechooser = new JFileChooser();
            jfilechooser.setFileSelectionMode(1);
            jfilechooser.setCurrentDirectory(root);
            jfilechooser.setDialogTitle(" Choose root directory");
            int i = jfilechooser.showOpenDialog(this);
            if(i == 1)
                return;
            File file = jfilechooser.getSelectedFile();
            if(file != null && file.exists() && file.isDirectory())
            {
                dname.setText(file.getAbsolutePath());
                root = file;
            }
        } else
        if(obj == about)
        {
            String s = "<html><center>FtpGoServer is written by Colin Mummery<br>at www.cellspark.com and is <br>subject to international copyright laws.<br> No warranties as to the correctness of <br>it's operation are offered or implied.</center></html>";
            JOptionPane.showMessageDialog(this, s, "FtpGoServer", 1);
        }
    }

    public void lp()
    {
        nto.setSelected(true);
        root = new File(System.getProperty("user.dir"));
        File file = new File("FtpGoServer.prefs");
        if(file.exists())
            try
            {
                DataInputStream datainputstream = new DataInputStream(new FileInputStream(file));
                File file1 = new File(datainputstream.readUTF());
                if(file1.exists() && file1.isDirectory())
                    root = file1;
                if(datainputstream.readBoolean())
                    yto.setSelected(true);
                datainputstream.close();
            }
            catch(Exception exception)
            {
                System.out.println(exception.getMessage());
            }
        dname.setText(root.getAbsolutePath());
    }

    public void sp()
    {
        try
        {
            DataOutputStream dataoutputstream = new DataOutputStream(new FileOutputStream(new File("FtpGoServer.prefs")));
            dataoutputstream.writeUTF(root.getAbsolutePath());
            dataoutputstream.writeBoolean(yto.isSelected());
            dataoutputstream.close();
        }
        catch(Exception exception)
        {
            System.out.println(exception.getMessage());
        }
    }

    public static void main(String args[])
    {
        new FtpGoServer();
    }

    public void run()
    {
        try
        {
            Socket socket = new Socket("www.microsoft.com", 80);
            InetAddress inetaddress = socket.getLocalAddress();
            socket.close();
            StringBuffer stringbuffer = new StringBuffer(100);
            stringbuffer.append("227 Entering Passive Mode (");
            byte abyte0[] = inetaddress.getAddress();
            int i = abyte0.length;
            for(int j = 0; j < i; j++)
                stringbuffer.append(abyte0[j] & 0xff).append(',');

            PA = stringbuffer.toString();
            ServerSocket serversocket = new ServerSocket(21, 10, inetaddress);
            stringbuffer.setLength(0);
            stringbuffer.append("ftp://");
            for(int k = 0; k < i; k++)
                stringbuffer.append(abyte0[k] & 0xff).append('.');

            stringbuffer.setLength(stringbuffer.length() - 1);
            url.setText(stringbuffer.toString());
            stringbuffer = null;
            do
            {
                Socket socket1 = serversocket.accept();
                (new Thread(new CN(socket1, inetaddress, no.isSelected(), root, new String(ropass.getPassword()), new String(rwpass.getPassword()), yto.isSelected()))).start();
            } while(true);
        }
        catch(Exception exception)
        {
            JOptionPane.showMessageDialog(this, exception.getMessage(), "FtpGoServer", 0);
        }
    }
	
	
	static File root;
    static String PA;
    JButton start;
    JButton exit;
    JButton dir;
    JButton about;
    JLabel dname;
    static JLabel upl;
    static JLabel dwl;
    JLabel url;
    JPasswordField ropass;
    JPasswordField rwpass;
    JRadioButton yes;
    JRadioButton no;
    JRadioButton yto;
    JRadioButton nto;
}


//////////////Klasa CN
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.Calendar;
import javax.swing.*;

// Referenced classes of package com.cellspark.ftpserver:
//            FtpGoServer

class CN
    implements Runnable
{

    public CN(Socket socket, InetAddress inetaddress, boolean flag, File file, String s1, String s2, boolean flag1)
    throws IOException
    {
        sb = new StringBuffer(256);
        bf = new byte[512];
        cal = Calendar.getInstance();
        s = socket;
        ip = inetaddress;
        ro = flag;
        root = cd = file;
        rop = s1;
        rwp = s2;
        if(flag1)
            socket.setSoTimeout(0x124f80);
        rPath = file.getCanonicalPath();
        rLen = rPath.length();
        if(flag && s1.equals(""))
            li = true;
        else
        if(!flag && s2.equals(""))
            li = true;
    }

    synchronized int gp()
    {
        pnum++;
        if(pnum == 9200)
            pnum += 10;
        if(pnum == 65500)
            pnum = 5000;
        return pnum;
    }

    synchronized void ul(int i)
    {
        ult += i;
        FtpGoServer.upl.setText(String.valueOf(ult >> 20));
    }

    synchronized void dl(int i)
    {
        dlt += i;
        FtpGoServer.dwl.setText(String.valueOf(dlt >> 20));
    }

    public void run()
    
    {  
    	isr = new InputStreamReader(s.getInputStream(), "US-ASCII");
        ps = new PrintStream(s.getOutputStream(), true, "US-ASCII");
        ps.print("220 Features: a p .\r\n");
label0:
        do
        {
            sb.setLength(0);
            do
            {
                int i = isr.read();
                if(i <= 0)
                {
                    if(sb.length() <= 0)
                        break label0;
                    break;
                }
                char c = (char)i;
                if(c == '\r')
                {
                    isr.skip(1L);
                    break;
                }
                sb.append(c);
            } while(true);
            int j = sb.length();
            for(int i1 = j - 1; i1 >= 0 && sb.charAt(i1) == ' '; i1--)
                sb.setLength(--j);

            if(j == 0)
                continue;
            rp = sb.toString();
            if(rp.startsWith("SYST"))
            {
                ps.print("215 UNIX Type: L8\r\n");
                continue;
            }
            if(rp.startsWith("USER"))
            {
                ps.print(li ? "230 OK\r\n" : "331 Need password\r\n");
                continue;
            }
            if(rp.startsWith("PASS"))
            {
                if(!li && (!ro || !rp.endsWith(rop)) && (ro || !rp.endsWith(rwp)))
                    if(!ro && rop.equals(""))
                        ro = true;
                    else
                    if(!ro && rp.endsWith(rop))
                    {
                        ro = true;
                    } else
                    {
                        ps.print("550 Error\r\n");
                        continue;
                    }
                ps.print("230 OK\r\n");
                li = true;
                continue;
            }
            if(!li)
            {
                ps.print("550 Error\r\n");
                continue;
            }
            if(rp.startsWith("PORT"))
            {
                sb.setLength(0);
                int j1 = 5;
                int k1 = 0;
                for(int l1 = 0; l1 < 4; l1++)
                {
                    k1 = rp.indexOf(',', j1);
                    sb.append(rp.substring(j1, k1));
                    if(l1 != 3)
                        sb.append('.');
                    j1 = k1 + 1;
                }

                String s1 = sb.toString();
                k1 = rp.indexOf(',', j1);
                sb.setLength(0);
                sb.append(Integer.toHexString(Integer.parseInt(rp.substring(j1, k1))));
                k1++;
                sb.append(Integer.toHexString(Integer.parseInt(rp.substring(k1))));
                ds = new Socket(s1, Integer.parseInt(sb.toString(), 16));
                ps.print("200 OK\r\n");
                continue;
            }
            if(rp.startsWith("PASV"))
            {
                sb.setLength(0);
                int k = gp();
                sb.append(FtpGoServer.PA).append(k >>> 8 & 0xff).append(',');
                sb.append(k & 0xff).append(')').append("\r\n");
                ServerSocket serversocket = new ServerSocket(k, 10, ip);
                ps.print(sb.toString());
                ds = serversocket.accept();
                continue;
            }
            if(rp.startsWith("LIST"))
            {
                ps.print("150 OK\r\n");
                PrintStream printstream = new PrintStream(ds.getOutputStream());
                File afile[] = cd.listFiles();
                int i2 = afile.length;
                for(int j2 = 0; j2 < i2; j2++)
                {
                    File file9 = afile[j2];
                    sb.setLength(0);
                    if(file9.isDirectory())
                        sb.append("drwxr-xr-x   2 ftpgo    server  ");
                    else
                        sb.append("-rw-r--r--   1 ftpgo    server  ");
                    String s2 = file9.isDirectory() ? "512" : String.valueOf(file9.length());
                    int l = 9 - s2.length();
                    for(int k2 = 0; k2 < l; k2++)
                        sb.append(' ');

                    sb.append(s2).append(' ');
                    cal.setTimeInMillis(file9.lastModified());
                    sb.append(mons[cal.get(2)]).append(' ');
                    String s3 = String.valueOf(cal.get(5));
                    if(s3.length() == 1)
                        sb.append('0');
                    sb.append(s3).append(' ').append(' ');
                    sb.append(String.valueOf(cal.get(1))).append(' ').append(file9.getName()).append("\r\n");
                    printstream.print(sb.toString());
                }

                ds.close();
                ds = null;
                ps.print("226 OK\r\n");
                System.gc();
                continue;
            }
            if(rp.startsWith("STOR"))
            {
                File file = gf(5);
                if(ro || file == null || file.exists() && (file.isDirectory() || !file.canWrite()))
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    ps.print("150 OK\r\n");
                    ul(cs(ds.getInputStream(), new FileOutputStream(file)));
                    ds.close();
                    ds = null;
                    ps.print("226 OK\r\n");
                }
                continue;
            }
            if(rp.startsWith("RETR"))
            {
                File file1 = gf(5);
                if(file1 == null || !file1.exists() || file1.isDirectory() || !file1.canRead())
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    ps.print("150 OK\r\n");
                    dl(cs(new FileInputStream(file1), ds.getOutputStream()));
                    ds.close();
                    ds = null;
                    ps.print("226 OK\r\n");
                }
                continue;
            }
            if(rp.startsWith("MKD"))
            {
                File file2 = gf(4);
                if(ro || file2 == null || file2.exists())
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    file2.mkdir();
                    ps.print("257 OK\r\n");
                }
                continue;
            }
            if(rp.startsWith("CWD"))
            {
                File file3 = gf(4);
                if(file3 == null || !file3.exists() || !file3.isDirectory() || !file3.canRead())
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    cd = file3;
                    pwd("250");
                }
                continue;
            }
            if(rp.startsWith("SIZE"))
            {
                File file4 = gf(5);
                if(file4 == null || !file4.exists() || file4.isDirectory() || !file4.canRead())
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    sb.setLength(0);
                    sb.append("213 ").append(file4.length()).append("\r\n");
                    ps.print(sb.toString());
                }
                continue;
            }
            if(rp.startsWith("CDUP"))
            {
                if(!cd.equals(root))
                    cd = cd.getParentFile();
                pwd("250");
                continue;
            }
            if(rp.startsWith("DELE"))
            {
                File file5 = gf(5);
                if(ro || file5 == null || !file5.exists() || file5.isDirectory() || !file5.canWrite())
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    file5.delete();
                    ps.print("250 OK\r\n");
                }
                continue;
            }
            if(rp.startsWith("RMD"))
            {
                File file6 = gf(4);
                if(ro || file6 == null || !file6.exists() || !file6.isDirectory() || !file6.canWrite() || file6.list().length != 0)
                {
                    ps.print("550 Error\r\n");
                } else
                {
                    file6.delete();
                    ps.print("250 OK\r\n");
                }
                continue;
            }
            if(rp.startsWith("PWD"))
            {
                pwd("257");
                continue;
            }
            if(rp.startsWith("TYPE"))
            {
                ps.print("200 OK\r\n");
                continue;
            }
            if(rp.startsWith("RNFR"))
            {
                File file7 = gf(5);
                if(ro || file7 == null || !file7.exists() || !file7.canWrite())
                {
                    ps.print("550 Error\r\n");
                    of = null;
                } else
                {
                    of = file7;
                    ps.print("350 \r\n");
                }
                continue;
            }
            if(rp.startsWith("RNTO"))
            {
                File file8 = gf(5);
                if(of == null || file8 == null || file8.exists())
                {
                    ps.print("550 Error\r\n");
                    of = null;
                } else
                {
                    of.renameTo(file8);
                    of = null;
                    ps.print("250 OK\r\n");
                }
                continue;
            }
            if(rp.startsWith("QUIT"))
            {
                ps.print("221 Bye.\r\n");
                break;
            }
            ps.print("550 Error\r\n");
        } while(true);
        
////////////////
        
        
        try
        {
            if(ds != null)
                ds.close();
            if(s != null)
                s.close();
        }
       
        
        catch(java.io.IOException exception) { }
        System.gc();
        break MISSING_BLOCK_LABEL_2126;
        
        Exception exception1;
        exception1;
        System.out.println(exception1.getMessage());
        try
        {
            if(ds != null)
                ds.close();
            if(s != null)
                s.close();
        }
        catch(Exception exception2) { }
        System.gc();
        break MISSING_BLOCK_LABEL_2126;
        Exception exception3;
        exception3;
        //System.out.println(exception3.getMessage());
        try
        {
            if(ds != null)
                ds.close();
            if(s != null)
                s.close();
        }
        catch(Exception exception4) { }
        System.gc();
        throw exception3;
        
        
        //////////////////////////////
    }

    File gf(int i) throws Exception
    {
        if(i >= rp.length())
            return null;
        String s1 = rp.substring(i);
        File file = (new File(s1.startsWith("/") ? root : cd, s1)).getCanonicalFile();
        if(!file.getAbsolutePath().startsWith(rPath))
            return null;
        else
            return file;
    }

    void pwd(String s1)
    {
        String s2 = cd.getAbsolutePath();
        int i = s2.length();
        sb.setLength(0);
        sb.append(s1).append(" \"");
        if(i > rLen)
            sb.append(s2.substring(rLen).replace('\\', '/'));
        else
            sb.append('/');
        sb.append('"').append("\r\n");
        ps.print(sb.toString());
    }

    public int cs(InputStream inputstream, OutputStream outputstream)
        throws IOException
    {
        int i = 0;
        int j = 0;
        while((i = inputstream.read(bf, 0, 512)) > -1) 
        {
            j += i;
            outputstream.write(bf, 0, i);
        }
        inputstream.close();
        outputstream.close();
        return j;
    }

    static final String E = "550 Error\r\n";
    static final String mons[] = {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 
        "Nov", "Dec"
    };
    static long ult;
    static long dlt;
    StringBuffer sb;
    byte bf[];
    static int pnum = 5000;
    boolean ro;
    String rp;
    Calendar cal;
    Socket s;
    Socket ds;
    InetAddress ip;
    InputStreamReader isr;
    PrintStream ps;
    final File root;
    final String rPath;
    final int rLen;
    File cd;
    File of;
    String rop;
    String rwp;
    boolean li;

}

0

hehe sam sobie to rozgryzaj :D lepiej i szybciej zrobić serwer od nowa :)

0

a co do flachy to chyba sobie żartujesz ! minimum z 5 flaszek ;-)

1 użytkowników online, w tym zalogowanych: 0, gości: 1