📄 sftp.java
字号:
/* * Copyright (c) 2001 Sun Microsystems, Inc. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Sun Microsystems, Inc. for Project JXTA." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", * nor may "JXTA" appear in their name, without prior written * permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of Project JXTA. For more * information on Project JXTA, please see * <http://www.jxta.org/>. * * This license is based on the BSD license adopted by the Apache Foundation. * * $Id: sftp.java,v 1.9 2004/06/02 19:59:29 bondolo Exp $ */package net.jxta.impl.shell.bin.sftp;import net.jxta.impl.shell.*;import java.io.*;import java.util.*;import net.jxta.exception.*;import net.jxta.discovery.*;import net.jxta.endpoint.*;import net.jxta.pipe.*;import net.jxta.impl.pipe.*;import net.jxta.peergroup.*;import net.jxta.document.*;import net.jxta.id.*;import net.jxta.protocol.*;/** * fsend Shell command: send a file to a user. * */public class sftp extends ShellApp implements Runnable { private DiscoveryService discovery=null; private ShellEnv env = null; private PipeAdvertisement userAdv = null; private static final int WaitingTime = 2000; private static final int MAXRETRIES = 5; public static final String SftpNameTag = "JxtaSftpUserName"; public static final String SftpIDTag = "JxtaSftpPipeID"; private static final String EnvName = "sftpd"; // local user private String userName = null; private static final String SenderName = "JxtaSftpSenderName"; private static final String JftpData = "JxtaSftpData"; private static final String FileInfo = "JxtaSftpInfo"; private Thread thread = null; // Some file stuff private String fsep = ""; private static final String fdirname = "sftp"; private String fdir = null; public sftp() { // Set up a directory path for sftp repository try { fsep = System.getProperty("file.separator"); } catch (Exception e) { ; } // should never happen fdir = fdirname + fsep; File f = new File(fdir); if (!f.exists()) { try { if (!f.mkdir()) { // try "home" directory as root fdir = ""; } } catch (Exception ex) { fdir = null; println("Exception = " + ex.getMessage() + "while creating new file " + fdir); } } } public void stopApp() {} private int syntaxError() { println("Usage: sftp -register userName"); println(" sftp -login userName "); println(" sftp -logout userName "); println(" sftp -s userName destUserName filename"); println(" sftp -search"); return ShellApp.appParamError; } public int startApp(String[] args) { if ((args == null) || (args.length == 0)) { return syntaxError(); } env = getEnv(); discovery= getGroup().getDiscoveryService(); if (args[0].equals("-register")) { return registerNewUser(args); } if (args[0].equals("-login")) { return login(args); } if (args[0].equals("-logout")) { return logout(args); } if (args[0].equals("-search")) { return findUsers(); } return sendFile(args); } private boolean daemonRunning(String name) { ShellObject obj = env.get(EnvName + "." + name + "@" + (getGroup().getPeerGroupAdvertisement()).getName()); if (obj == null) { return false; } else { return true; } } private int login(String[] args) { if (args.length != 2) { return syntaxError(); } String name = args[1]; if (daemonRunning(name)) { println("sftp: user " + name + " is already listening"); return ShellApp.appMiscError; } PipeAdvertisement adv = findUserAdv(name); if (adv == null) { println("ftpd: " + name + " is not a registered user"); return ShellApp.appMiscError; } else discovery.remotePublish(adv); runDaemon(name, adv); return ShellApp.appNoError; } private int findUsers() { Enumeration each; int i =0; discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, PipeAdvertisement.NameTag, SftpNameTag +".*", 20, null); while (true) { try { if (i > MAXRETRIES) { println(""); break; } Thread.sleep(WaitingTime); print("."); i++; } catch (Exception e) { println("findUsers, exception = " + e.getMessage()); } } try { each = discovery.getLocalAdvertisements(DiscoveryService.ADV, PipeAdvertisement.NameTag, SftpNameTag +".*"); if ((each != null) && (each.hasMoreElements())) { PipeAdvertisement adv = null; println("found the following registrations:"); while (each.hasMoreElements()) { try { adv = (PipeAdvertisement) each.nextElement(); println(adv.getName()); } catch(Exception e) { println("findUsers, exception = " + e.getMessage()); continue; } } } } catch (Exception e) { println("findUsers, exception = " + e.getMessage()); } return ShellApp.appNoError; } private int logout(String[] args) { if (args.length != 2) { return syntaxError(); } String name = args[1]; if (!daemonRunning(name)) { println("ftpd: user " + name + " is not listening"); return ShellApp.appMiscError; } stopDaemon(name); return ShellApp.appNoError; } // sftp -s <source pipe> <dest pipe> <filename> // is required private static final int OBUFLEN = 15000; private int sendFile(String[] args) { if (!args[0].equals("-s") || args.length != 4) { return syntaxError(); } String srcName = args[1]; String name = args[2]; String fileName = args[3]; // check if the srcName is registered if (!daemonRunning(srcName)) { println("sftpd: user " + srcName + " is not logged in"); return ShellApp.appMiscError; } // Locate target name PipeAdvertisement adv = findUserAdv(name); if (adv == null) { println("sftp: " + name + " is not a registered user"); return ShellApp.appMiscError; } // Try and connect to target OutputPipe pipeOut = null; try { println("found user's advertisement attempting to connect"); pipeOut = getGroup().getPipeService().createOutputPipe(adv, 120000); println("Please be patient ..."); if (pipeOut == null) { println("sftp: user " + name + " is not listening. Try again later"); return ShellApp.appMiscError; } } catch (Exception e) { println("sftp: user " + name + " is not listening. Try again later" + "\n Exception = " + e.getMessage()); return ShellApp.appMiscError; } // Try and open the file File f = null; DataInputStream fs = null; try { f = new File(fileName); fs = new DataInputStream( new FileInputStream(f) ); } catch (Exception e) { println("sftp: Could not open " + fileName + "\n Exception = " + e.getMessage()); pipeOut.close(); return ShellApp.appMiscError; } // Get the user text long fileSize = f.length(); // fileinfo message // Strip any path info int pix = fileName.lastIndexOf(fsep); String stripped = null; if (pix != -1) stripped = fileName.substring(pix+1); else stripped = fileName; // Make file info element for first message only String start = stripped + "\n" + fileSize; Message msg = null; byte[] buf = new byte[OBUFLEN]; int n16kbufs = (int)(fileSize/OBUFLEN); int lastBufSize = (int)(fileSize % OBUFLEN); boolean infoDone = false; int offset = 0; long stime = System.currentTimeMillis(); int chunks = n16kbufs + (int)(lastBufSize == 0 ? 0 : 1); println("sftp is connected to user " + name); println("Sending file " + fileName + ", size = " + fileSize + " bytes" + " in " + chunks + " chunks"); for (int i = 0; i < n16kbufs; i++) { try { // Build a message msg = new Message(); // set file info element in first message if (i == 0) { infoDone = true; // file info msg.addMessageElement( new ByteArrayMessageElement( FileInfo, null, start.getBytes(), null ) ); } // read the data fs.readFully(buf, 0, OBUFLEN); offset += OBUFLEN; // data elements msg.addMessageElement( new ByteArrayMessageElement( JftpData, null, buf, null) ); // src name msg.addMessageElement( new ByteArrayMessageElement( SenderName, null, srcName.getBytes(), null) ); pipeOut.send(msg); print("!"); } catch (Exception e) { printStackTrace( "Failed to send file " + fileName + " to user :" + name, e ); try { fs.close(); } catch (Exception ex) { printStackTrace( "Close failed for " + fileName, ex ); } pipeOut.close(); return ShellApp.appMiscError; } } // See if we have one more buffer to send if (lastBufSize != 0) { try { // Build a message msg = new Message(); // set file info element in first message only if (!infoDone) { // file info msg.addMessageElement( new ByteArrayMessageElement( FileInfo, null, start.getBytes(), null ) ); } // read the data fs.readFully(buf, 0, lastBufSize); // data element msg.addMessageElement( new ByteArrayMessageElement( JftpData, null, buf, 0, lastBufSize, null ) ); // src name element msg.addMessageElement( new ByteArrayMessageElement( SenderName, null, srcName.getBytes(), null ) ); pipeOut.send(msg); print("!"); } catch (Exception e) { printStackTrace( "Failed to send file " + fileName + " to user :" + name, e ); try { fs.close(); } catch (Exception ex) { printStackTrace( "Close failed for " + fileName, ex ); } pipeOut.close(); return ShellApp.appMiscError; } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -