1
0
Fork 0
mirror of https://github.com/vanitasvitae/Smack.git synced 2025-09-12 02:29:38 +02:00

merged branch improve_bytestreams in trunk

git-svn-id: http://svn.igniterealtime.org/svn/repos/smack/trunk@11821 b35dd754-fafc-0310-a699-88a17e54d16e
This commit is contained in:
Henning Staib 2010-08-15 11:57:11 +00:00 committed by henning
parent ef74695a1b
commit 8b54f34153
74 changed files with 11866 additions and 1902 deletions

View file

@ -19,9 +19,20 @@
*/
package org.jivesoftware.smackx.filetransfer;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
@ -30,40 +41,26 @@ import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.packet.DataForm;
import org.jivesoftware.smackx.packet.StreamInitiation;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Manages the negotiation of file transfers according to JEP-0096. If a file is
* being sent the remote user chooses the type of stream under which the file
* will be sent.
*
* @author Alexander Wenckus
* @see <a href=http://www.jabber.org/jeps/jep-0096.html>JEP-0096: File Transfer</a>
* @see <a href="http://www.jabber.org/jeps/jep-0096.html">JEP-0096: File Transfer</a>
*/
public class FileTransferNegotiator {
// Static
/**
* The XMPP namespace of the SOCKS5 bytestream
*/
public static final String BYTE_STREAM = "http://jabber.org/protocol/bytestreams";
/**
* The XMPP namespace of the In-Band bytestream
*/
public static final String INBAND_BYTE_STREAM = "http://jabber.org/protocol/ibb";
private static final String[] NAMESPACE = {
"http://jabber.org/protocol/si/profile/file-transfer",
"http://jabber.org/protocol/si", BYTE_STREAM, INBAND_BYTE_STREAM};
private static final String[] PROTOCOLS = {BYTE_STREAM, INBAND_BYTE_STREAM};
"http://jabber.org/protocol/si"};
private static final Map<Connection, FileTransferNegotiator> transferObject =
new ConcurrentHashMap<Connection, FileTransferNegotiator>();
@ -121,14 +118,24 @@ public class FileTransferNegotiator {
final boolean isEnabled) {
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
for (String ns : NAMESPACE) {
List<String> namespaces = new ArrayList<String>();
namespaces.addAll(Arrays.asList(NAMESPACE));
namespaces.add(InBandBytestreamManager.NAMESPACE);
if (!IBB_ONLY) {
namespaces.add(Socks5BytestreamManager.NAMESPACE);
}
for (String namespace : namespaces) {
if (isEnabled) {
manager.addFeature(ns);
}
else {
manager.removeFeature(ns);
if (!manager.includesFeature(namespace)) {
manager.addFeature(namespace);
}
} else {
manager.removeFeature(namespace);
}
}
}
/**
@ -139,20 +146,31 @@ public class FileTransferNegotiator {
* @return True if all related services are enabled, false if they are not.
*/
public static boolean isServiceEnabled(final Connection connection) {
for (String ns : NAMESPACE) {
if (!ServiceDiscoveryManager.getInstanceFor(connection).includesFeature(ns))
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
List<String> namespaces = new ArrayList<String>();
namespaces.addAll(Arrays.asList(NAMESPACE));
namespaces.add(InBandBytestreamManager.NAMESPACE);
if (!IBB_ONLY) {
namespaces.add(Socks5BytestreamManager.NAMESPACE);
}
for (String namespace : namespaces) {
if (!manager.includesFeature(namespace)) {
return false;
}
}
return true;
}
/**
* A convience method to create an IQ packet.
* A convenience method to create an IQ packet.
*
* @param ID The packet ID of the
* @param to To whom the packet is addressed.
* @param from From whom the packet is sent.
* @param type The iq type of the packet.
* @param type The IQ type of the packet.
* @return The created IQ packet.
*/
public static IQ createIQ(final String ID, final String to,
@ -176,14 +194,19 @@ public class FileTransferNegotiator {
* @return Returns a collection of the supported transfer protocols.
*/
public static Collection<String> getSupportedProtocols() {
return Collections.unmodifiableList(Arrays.asList(PROTOCOLS));
List<String> protocols = new ArrayList<String>();
protocols.add(InBandBytestreamManager.NAMESPACE);
if (!IBB_ONLY) {
protocols.add(Socks5BytestreamManager.NAMESPACE);
}
return Collections.unmodifiableList(protocols);
}
// non-static
private final Connection connection;
private final Socks5TransferNegotiatorManager byteStreamTransferManager;
private final StreamNegotiator byteStreamTransferManager;
private final StreamNegotiator inbandTransferManager;
@ -191,7 +214,7 @@ public class FileTransferNegotiator {
configureConnection(connection);
this.connection = connection;
byteStreamTransferManager = new Socks5TransferNegotiatorManager(connection);
byteStreamTransferManager = new Socks5TransferNegotiator(connection);
inbandTransferManager = new IBBTransferNegotiator(connection);
}
@ -221,7 +244,6 @@ public class FileTransferNegotiator {
private void cleanup(final Connection connection) {
if (transferObject.remove(connection) != null) {
byteStreamTransferManager.cleanup();
inbandTransferManager.cleanup();
}
}
@ -288,10 +310,10 @@ public class FileTransferNegotiator {
boolean isIBB = false;
for (Iterator<FormField.Option> it = field.getOptions(); it.hasNext();) {
variable = it.next().getValue();
if (variable.equals(BYTE_STREAM) && !IBB_ONLY) {
if (variable.equals(Socks5BytestreamManager.NAMESPACE) && !IBB_ONLY) {
isByteStream = true;
}
else if (variable.equals(INBAND_BYTE_STREAM)) {
else if (variable.equals(InBandBytestreamManager.NAMESPACE)) {
isIBB = true;
}
}
@ -304,11 +326,11 @@ public class FileTransferNegotiator {
if (isByteStream && isIBB && field.getType().equals(FormField.TYPE_LIST_MULTI)) {
return new FaultTolerantNegotiator(connection,
byteStreamTransferManager.createNegotiator(),
byteStreamTransferManager,
inbandTransferManager);
}
else if (isByteStream) {
return byteStreamTransferManager.createNegotiator();
return byteStreamTransferManager;
}
else {
return inbandTransferManager;
@ -346,11 +368,11 @@ public class FileTransferNegotiator {
* the option of, accepting, rejecting, or not responding to a received file
* transfer request.
* <p/>
* If they accept, the packet will contain the other user's choosen stream
* If they accept, the packet will contain the other user's chosen stream
* type to send the file across. The two choices this implementation
* provides to the other user for file transfer are <a
* href="http://www.jabber.org/jeps/jep-0065.html">SOCKS5 Bytestreams</a>,
* which is the prefered method of transfer, and <a
* which is the preferred method of transfer, and <a
* href="http://www.jabber.org/jeps/jep-0047.html">In-Band Bytestreams</a>,
* which is the fallback mechanism.
* <p/>
@ -422,10 +444,10 @@ public class FileTransferNegotiator {
boolean isIBB = false;
for (Iterator<String> it = field.getValues(); it.hasNext();) {
variable = it.next();
if (variable.equals(BYTE_STREAM) && !IBB_ONLY) {
if (variable.equals(Socks5BytestreamManager.NAMESPACE) && !IBB_ONLY) {
isByteStream = true;
}
else if (variable.equals(INBAND_BYTE_STREAM)) {
else if (variable.equals(InBandBytestreamManager.NAMESPACE)) {
isIBB = true;
}
}
@ -438,10 +460,10 @@ public class FileTransferNegotiator {
if (isByteStream && isIBB) {
return new FaultTolerantNegotiator(connection,
byteStreamTransferManager.createNegotiator(), inbandTransferManager);
byteStreamTransferManager, inbandTransferManager);
}
else if (isByteStream) {
return byteStreamTransferManager.createNegotiator();
return byteStreamTransferManager;
}
else {
return inbandTransferManager;
@ -453,9 +475,9 @@ public class FileTransferNegotiator {
FormField field = new FormField(STREAM_DATA_FIELD_NAME);
field.setType(FormField.TYPE_LIST_MULTI);
if (!IBB_ONLY) {
field.addOption(new FormField.Option(BYTE_STREAM));
field.addOption(new FormField.Option(Socks5BytestreamManager.NAMESPACE));
}
field.addOption(new FormField.Option(INBAND_BYTE_STREAM));
field.addOption(new FormField.Option(InBandBytestreamManager.NAMESPACE));
form.addField(field);
return form;
}

View file

@ -1,26 +0,0 @@
/**
* $Revision:$
* $Date:$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
/**
*
*/
public interface FileTransferNegotiatorManager {
StreamNegotiator createNegotiator();
}

View file

@ -19,402 +19,107 @@
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.packet.IBBExtensions;
import org.jivesoftware.smackx.packet.IBBExtensions.Open;
import org.jivesoftware.smackx.packet.StreamInitiation;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromContainsFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamRequest;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamSession;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Open;
import org.jivesoftware.smackx.packet.StreamInitiation;
/**
* The in-band bytestream file transfer method, or IBB for short, transfers the
* The In-Band Bytestream file transfer method, or IBB for short, transfers the
* file over the same XML Stream used by XMPP. It is the fall-back mechanism in
* case the SOCKS5 bytestream method of transfering files is not available.
*
* case the SOCKS5 bytestream method of transferring files is not available.
*
* @author Alexander Wenckus
* @see <a href="http://www.jabber.org/jeps/jep-0047.html">JEP-0047: In-Band
* @author Henning Staib
* @see <a href="http://xmpp.org/extensions/xep-0047.html">XEP-0047: In-Band
* Bytestreams (IBB)</a>
*/
public class IBBTransferNegotiator extends StreamNegotiator {
protected static final String NAMESPACE = "http://jabber.org/protocol/ibb";
public static final int DEFAULT_BLOCK_SIZE = 4096;
private Connection connection;
private InBandBytestreamManager manager;
/**
* The default constructor for the In-Band Bystream Negotiator.
*
* The default constructor for the In-Band Bytestream Negotiator.
*
* @param connection The connection which this negotiator works on.
*/
protected IBBTransferNegotiator(Connection connection) {
this.connection = connection;
}
public PacketFilter getInitiationPacketFilter(String from, String streamID) {
return new AndFilter(new FromContainsFilter(
from), new IBBOpenSidFilter(streamID));
}
InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException {
Open openRequest = (Open) streamInitiation;
if (openRequest.getType().equals(IQ.Type.ERROR)) {
throw new XMPPException(openRequest.getError());
}
PacketFilter dataFilter = new IBBMessageSidFilter(openRequest.getFrom(),
openRequest.getSessionID());
PacketFilter closeFilter = new AndFilter(new PacketTypeFilter(
IBBExtensions.Close.class), new FromMatchesFilter(openRequest
.getFrom()));
InputStream stream = new IBBInputStream(openRequest.getSessionID(),
dataFilter, closeFilter);
initInBandTransfer(openRequest);
return stream;
}
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException {
Packet openRequest = initiateIncomingStream(connection, initiation);
return negotiateIncomingStream(openRequest);
}
/**
* Creates and sends the response for the open request.
*
* @param openRequest The open request recieved from the peer.
*/
private void initInBandTransfer(final Open openRequest) {
connection.sendPacket(FileTransferNegotiator.createIQ(openRequest
.getPacketID(), openRequest.getFrom(), openRequest.getTo(),
IQ.Type.RESULT));
this.manager = InBandBytestreamManager.getByteStreamManager(connection);
}
public OutputStream createOutgoingStream(String streamID, String initiator,
String target) throws XMPPException {
Open openIQ = new Open(streamID, DEFAULT_BLOCK_SIZE);
openIQ.setTo(target);
openIQ.setType(IQ.Type.SET);
String target) throws XMPPException {
InBandBytestreamSession session = this.manager.establishSession(target, streamID);
session.setCloseBothStreamsEnabled(true);
return session.getOutputStream();
}
// wait for the result from the peer
PacketCollector collector = connection
.createPacketCollector(new PacketIDFilter(openIQ.getPacketID()));
connection.sendPacket(openIQ);
// We don't want to wait forever for the result
IQ openResponse = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
public InputStream createIncomingStream(StreamInitiation initiation)
throws XMPPException {
/*
* In-Band Bytestream initiation listener must ignore next in-band
* bytestream request with given session ID
*/
this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());
if (openResponse == null) {
throw new XMPPException("No response from peer on IBB open");
}
Packet streamInitiation = initiateIncomingStream(this.connection, initiation);
return negotiateIncomingStream(streamInitiation);
}
IQ.Type type = openResponse.getType();
if (!type.equals(IQ.Type.RESULT)) {
if (type.equals(IQ.Type.ERROR)) {
throw new XMPPException("Target returned an error",
openResponse.getError());
}
else {
throw new XMPPException("Target returned unknown response");
}
}
public PacketFilter getInitiationPacketFilter(String from, String streamID) {
/*
* this method is always called prior to #negotiateIncomingStream() so
* the In-Band Bytestream initiation listener must ignore the next
* In-Band Bytestream request with the given session ID
*/
this.manager.ignoreBytestreamRequestOnce(streamID);
return new IBBOutputStream(target, streamID, DEFAULT_BLOCK_SIZE);
return new AndFilter(new FromContainsFilter(from), new IBBOpenSidFilter(streamID));
}
public String[] getNamespaces() {
return new String[]{NAMESPACE};
return new String[] { InBandBytestreamManager.NAMESPACE };
}
InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException {
// build In-Band Bytestream request
InBandBytestreamRequest request = new ByteStreamRequest(this.manager,
(Open) streamInitiation);
// always accept the request
InBandBytestreamSession session = request.accept();
session.setCloseBothStreamsEnabled(true);
return session.getInputStream();
}
public void cleanup() {
}
private class IBBOutputStream extends OutputStream {
protected byte[] buffer;
protected int count = 0;
protected int seq = 0;
final String userID;
final private IQ closePacket;
private String messageID;
private String sid;
IBBOutputStream(String userID, String sid, int blockSize) {
if (blockSize <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buffer = new byte[blockSize];
this.userID = userID;
Message template = new Message(userID);
messageID = template.getPacketID();
this.sid = sid;
closePacket = createClosePacket(userID, sid);
}
private IQ createClosePacket(String userID, String sid) {
IQ packet = new IBBExtensions.Close(sid);
packet.setTo(userID);
packet.setType(IQ.Type.SET);
return packet;
}
public void write(int b) throws IOException {
if (count >= buffer.length) {
flushBuffer();
}
buffer[count++] = (byte) b;
}
public synchronized void write(byte b[], int off, int len)
throws IOException {
if (len >= buffer.length) {
// "byte" off the first chunck to write out
writeOut(b, off, buffer.length);
// recursivly call this method again with the lesser amount subtracted.
write(b, off + buffer.length, len - buffer.length);
} else {
writeOut(b, off, len);
}
}
private void writeOut(byte b[], int off, int len) {
if (len > buffer.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buffer, count, len);
count += len;
}
private synchronized void flushBuffer() {
writeToXML(buffer, 0, count);
count = 0;
}
private synchronized void writeToXML(byte[] buffer, int offset, int len) {
Message template = createTemplate(messageID + "_" + seq);
IBBExtensions.Data ext = new IBBExtensions.Data(sid);
template.addExtension(ext);
String enc = StringUtils.encodeBase64(buffer, offset, len, false);
ext.setData(enc);
ext.setSeq(seq);
synchronized (this) {
try {
this.wait(100);
}
catch (InterruptedException e) {
/* Do Nothing */
}
}
connection.sendPacket(template);
seq = (seq + 1 == 65535 ? 0 : seq + 1);
}
public void close() throws IOException {
this.flush();
connection.sendPacket(closePacket);
}
public void flush() throws IOException {
flushBuffer();
}
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
public Message createTemplate(String messageID) {
Message template = new Message(userID);
template.setPacketID(messageID);
return template;
}
}
private class IBBInputStream extends InputStream implements PacketListener {
private String streamID;
private PacketCollector dataCollector;
private byte[] buffer;
private int bufferPointer;
private int seq = -1;
private boolean isDone;
private boolean isEOF;
private boolean isClosed;
private IQ closeConfirmation;
private Message lastMess;
private IBBInputStream(String streamID, PacketFilter dataFilter,
PacketFilter closeFilter) {
this.streamID = streamID;
this.dataCollector = connection.createPacketCollector(dataFilter);
connection.addPacketListener(this, closeFilter);
this.bufferPointer = -1;
}
public synchronized int read() throws IOException {
if (isEOF || isClosed) {
return -1;
}
if (bufferPointer == -1 || bufferPointer >= buffer.length) {
loadBufferWait();
}
return (int) buffer[bufferPointer++];
}
public synchronized int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public synchronized int read(byte[] b, int off, int len)
throws IOException {
if (isEOF || isClosed) {
return -1;
}
if (bufferPointer == -1 || bufferPointer >= buffer.length) {
if (!loadBufferWait()) {
isEOF = true;
return -1;
}
}
if (len - off > buffer.length - bufferPointer) {
len = buffer.length - bufferPointer;
}
System.arraycopy(buffer, bufferPointer, b, off, len);
bufferPointer += len;
return len;
}
private boolean loadBufferWait() throws IOException {
IBBExtensions.Data data;
Message mess = null;
while (mess == null) {
if (isDone) {
mess = (Message) dataCollector.pollResult();
if (mess == null) {
return false;
}
}
else {
mess = (Message) dataCollector.nextResult(1000);
}
}
lastMess = mess;
data = (IBBExtensions.Data) mess.getExtension(
IBBExtensions.Data.ELEMENT_NAME,
IBBExtensions.NAMESPACE);
checkSequence(mess, (int) data.getSeq());
buffer = StringUtils.decodeBase64(data.getData());
bufferPointer = 0;
return true;
}
private void checkSequence(Message mess, int seq) throws IOException {
if (this.seq == 65535) {
this.seq = -1;
}
if (seq - 1 != this.seq) {
cancelTransfer(mess);
throw new IOException("Packets out of sequence");
}
else {
this.seq = seq;
}
}
private void cancelTransfer(Message mess) {
cleanup();
sendCancelMessage(mess);
}
private void cleanup() {
dataCollector.cancel();
connection.removePacketListener(this);
}
private void sendCancelMessage(Message message) {
IQ error = FileTransferNegotiator.createIQ(message.getPacketID(), message.getFrom(), message.getTo(),
IQ.Type.ERROR);
error.setError(new XMPPError(XMPPError.Condition.remote_server_timeout, "Cancel Message Transfer"));
connection.sendPacket(error);
}
public boolean markSupported() {
return false;
}
public void processPacket(Packet packet) {
IBBExtensions.Close close = (IBBExtensions.Close) packet;
if (close.getSessionID().equals(streamID)) {
isDone = true;
closeConfirmation = FileTransferNegotiator.createIQ(packet
.getPacketID(), packet.getFrom(), packet.getTo(),
IQ.Type.RESULT);
}
}
public synchronized void close() throws IOException {
if (isClosed) {
return;
}
cleanup();
if (isEOF) {
sendCloseConfirmation();
}
else if (lastMess != null) {
sendCancelMessage(lastMess);
}
isClosed = true;
}
private void sendCloseConfirmation() {
connection.sendPacket(closeConfirmation);
}
}
private static class IBBOpenSidFilter implements PacketFilter {
/**
* This PacketFilter accepts an incoming In-Band Bytestream open request
* with a specified session ID.
*/
private static class IBBOpenSidFilter extends PacketTypeFilter {
private String sessionID;
public IBBOpenSidFilter(String sessionID) {
super(Open.class);
if (sessionID == null) {
throw new IllegalArgumentException("StreamID cannot be null");
}
@ -422,39 +127,26 @@ public class IBBTransferNegotiator extends StreamNegotiator {
}
public boolean accept(Packet packet) {
if (!IBBExtensions.Open.class.isInstance(packet)) {
return false;
}
IBBExtensions.Open open = (IBBExtensions.Open) packet;
String sessionID = open.getSessionID();
if (super.accept(packet)) {
Open bytestream = (Open) packet;
return (sessionID != null && sessionID.equals(this.sessionID));
// packet must by of type SET and contains the given session ID
return this.sessionID.equals(bytestream.getSessionID())
&& IQ.Type.SET.equals(bytestream.getType());
}
return false;
}
}
private static class IBBMessageSidFilter implements PacketFilter {
/**
* Derive from InBandBytestreamRequest to access protected constructor.
*/
private static class ByteStreamRequest extends InBandBytestreamRequest {
private final String sessionID;
private String from;
public IBBMessageSidFilter(String from, String sessionID) {
this.from = from;
this.sessionID = sessionID;
private ByteStreamRequest(InBandBytestreamManager manager, Open byteStreamRequest) {
super(manager, byteStreamRequest);
}
public boolean accept(Packet packet) {
if (!(packet instanceof Message)) {
return false;
}
if (!packet.getFrom().equalsIgnoreCase(from)) {
return false;
}
IBBExtensions.Data data = (IBBExtensions.Data) packet.
getExtension(IBBExtensions.Data.ELEMENT_NAME, IBBExtensions.NAMESPACE);
return data != null && data.getSessionID() != null
&& data.getSessionID().equalsIgnoreCase(sessionID);
}
}
}

View file

@ -1,10 +1,4 @@
/**
* $RCSfile$
* $Revision: $
* $Date: $
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -19,119 +13,100 @@
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromMatchesFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.Bytestream;
import org.jivesoftware.smackx.packet.Bytestream.StreamHost;
import org.jivesoftware.smackx.packet.Bytestream.StreamHostUsed;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamRequest;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamSession;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.jivesoftware.smackx.packet.StreamInitiation;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Iterator;
/**
* A SOCKS5 bytestream is negotiated partly over the XMPP XML stream and partly
* over a seperate socket. The actual transfer though takes place over a
* seperatly created socket.
* <p/>
* A SOCKS5 file transfer generally has three parites, the initiator, the
* target, and the stream host. The stream host is a specialized SOCKS5 proxy
* setup on the server, or, the Initiator can act as the Stream Host if the
* proxy is not available.
* <p/>
* The advantage of having a seperate proxy over directly connecting to
* eachother is if the Initator and the Target are not on the same LAN and are
* operating behind NAT, the proxy allows for a common location for both parties
* to connect to and transfer the file.
* <p/>
* Smack will attempt to automatically discover any proxies present on your
* server. If any are detected they will be forwarded to any user attempting to
* recieve files from you.
*
* @author Alexander Wenckus
* @see <a href="http://www.jabber.org/jeps/jep-0065.html">JEP-0065: SOCKS5
* Bytestreams</a>
* Negotiates a SOCKS5 Bytestream to be used for file transfers. The implementation is based on the
* {@link Socks5BytestreamManager} and the {@link Socks5BytestreamRequest}.
*
* @author Henning Staib
* @see <a href="http://xmpp.org/extensions/xep-0065.html">XEP-0065: SOCKS5 Bytestreams</a>
*/
public class Socks5TransferNegotiator extends StreamNegotiator {
protected static final String NAMESPACE = "http://jabber.org/protocol/bytestreams";
private Connection connection;
/**
* The number of connection failures it takes to a streamhost for that particular streamhost
* to be blacklisted. When a host is blacklisted no more connection attempts will be made to
* it for a period of 2 hours.
*/
private static final int CONNECT_FAILURE_THRESHOLD = 2;
private Socks5BytestreamManager manager;
public static boolean isAllowLocalProxyHost = true;
private final Connection connection;
private Socks5TransferNegotiatorManager transferNegotiatorManager;
public Socks5TransferNegotiator(Socks5TransferNegotiatorManager transferNegotiatorManager,
final Connection connection)
{
Socks5TransferNegotiator(Connection connection) {
this.connection = connection;
this.transferNegotiatorManager = transferNegotiatorManager;
this.manager = Socks5BytestreamManager.getBytestreamManager(this.connection);
}
public PacketFilter getInitiationPacketFilter(String from, String sessionID) {
return new AndFilter(new FromMatchesFilter(from),
new BytestreamSIDFilter(sessionID));
@Override
public OutputStream createOutgoingStream(String streamID, String initiator, String target)
throws XMPPException {
try {
return this.manager.establishSession(target, streamID).getOutputStream();
}
catch (IOException e) {
throw new XMPPException("error establishing SOCKS5 Bytestream", e);
}
catch (InterruptedException e) {
throw new XMPPException("error establishing SOCKS5 Bytestream", e);
}
}
/*
* (non-Javadoc)
*
* @see org.jivesoftware.smackx.filetransfer.StreamNegotiator#initiateDownload(
* org.jivesoftware.smackx.packet.StreamInitiation, java.io.File)
*/
InputStream negotiateIncomingStream(Packet streamInitiation)
throws XMPPException {
Bytestream streamHostsInfo = (Bytestream) streamInitiation;
@Override
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException,
InterruptedException {
/*
* SOCKS5 initiation listener must ignore next SOCKS5 Bytestream request with given session
* ID
*/
this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());
if (streamHostsInfo.getType().equals(IQ.Type.ERROR)) {
throw new XMPPException(streamHostsInfo.getError());
}
SelectedHostInfo selectedHost;
Packet streamInitiation = initiateIncomingStream(this.connection, initiation);
return negotiateIncomingStream(streamInitiation);
}
@Override
public PacketFilter getInitiationPacketFilter(final String from, String streamID) {
/*
* this method is always called prior to #negotiateIncomingStream() so the SOCKS5
* InitiationListener must ignore the next SOCKS5 Bytestream request with the given session
* ID
*/
this.manager.ignoreBytestreamRequestOnce(streamID);
return new AndFilter(new FromMatchesFilter(from), new BytestreamSIDFilter(streamID));
}
@Override
public String[] getNamespaces() {
return new String[] { Socks5BytestreamManager.NAMESPACE };
}
@Override
InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException,
InterruptedException {
// build SOCKS5 Bytestream request
Socks5BytestreamRequest request = new ByteStreamRequest(this.manager,
(Bytestream) streamInitiation);
// always accept the request
Socks5BytestreamSession session = request.accept();
// test input stream
try {
// select appropriate host
selectedHost = selectHost(streamHostsInfo);
}
catch (XMPPException ex) {
if (ex.getXMPPError() != null) {
IQ errorPacket = super.createError(streamHostsInfo.getTo(),
streamHostsInfo.getFrom(), streamHostsInfo.getPacketID(),
ex.getXMPPError());
connection.sendPacket(errorPacket);
}
throw (ex);
}
// send used-host confirmation
Bytestream streamResponse = createUsedHostConfirmation(
selectedHost.selectedHost, streamHostsInfo.getFrom(),
streamHostsInfo.getTo(), streamHostsInfo.getPacketID());
connection.sendPacket(streamResponse);
try {
PushbackInputStream stream = new PushbackInputStream(
selectedHost.establishedSocket.getInputStream());
PushbackInputStream stream = new PushbackInputStream(session.getInputStream());
int firstByte = stream.read();
stream.unread(firstByte);
return stream;
@ -139,435 +114,51 @@ public class Socks5TransferNegotiator extends StreamNegotiator {
catch (IOException e) {
throw new XMPPException("Error establishing input stream", e);
}
}
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException {
Packet streamInitiation = initiateIncomingStream(connection, initiation);
return negotiateIncomingStream(streamInitiation);
}
/**
* The used host confirmation is sent to the initiator to indicate to them
* which of the hosts they provided has been selected and successfully
* connected to.
*
* @param selectedHost The selected stream host.
* @param initiator The initiator of the stream.
* @param target The target of the stream.
* @param packetID The of the packet being responded to.
* @return The packet that was created to send to the initiator.
*/
private Bytestream createUsedHostConfirmation(StreamHost selectedHost,
String initiator, String target, String packetID) {
Bytestream streamResponse = new Bytestream();
streamResponse.setTo(initiator);
streamResponse.setFrom(target);
streamResponse.setType(IQ.Type.RESULT);
streamResponse.setPacketID(packetID);
streamResponse.setUsedHost(selectedHost.getJID());
return streamResponse;
}
/**
* Selects a host to connect to over which the file will be transmitted.
*
* @param streamHostsInfo the packet recieved from the initiator containing the available hosts
* to transfer the file
* @return the selected host and socket that were created.
* @throws XMPPException when there is no appropriate host.
*/
private SelectedHostInfo selectHost(Bytestream streamHostsInfo)
throws XMPPException {
Iterator<StreamHost> it = streamHostsInfo.getStreamHosts().iterator();
StreamHost selectedHost = null;
Socket socket = null;
while (it.hasNext()) {
selectedHost = (StreamHost) it.next();
String address = selectedHost.getAddress();
// Check to see if this address has been blacklisted
int failures = getConnectionFailures(address);
if (failures >= CONNECT_FAILURE_THRESHOLD) {
continue;
}
// establish socket
try {
socket = new Socket(address, selectedHost
.getPort());
establishSOCKS5ConnectionToProxy(socket, createDigest(
streamHostsInfo.getSessionID(), streamHostsInfo
.getFrom(), streamHostsInfo.getTo()));
break;
}
catch (IOException e) {
e.printStackTrace();
incrementConnectionFailures(address);
selectedHost = null;
socket = null;
}
}
if (selectedHost == null || socket == null || !socket.isConnected()) {
String errorMessage = "Could not establish socket with any provided host";
throw new XMPPException(errorMessage, new XMPPError(
XMPPError.Condition.no_acceptable, errorMessage));
}
return new SelectedHostInfo(selectedHost, socket);
}
private void incrementConnectionFailures(String address) {
transferNegotiatorManager.incrementConnectionFailures(address);
}
private int getConnectionFailures(String address) {
return transferNegotiatorManager.getConnectionFailures(address);
}
/**
* Creates the digest needed for a byte stream. It is the SHA1(sessionID +
* initiator + target).
*
* @param sessionID The sessionID of the stream negotiation
* @param initiator The inititator of the stream negotiation
* @param target The target of the stream negotiation
* @return SHA-1 hash of the three parameters
*/
private String createDigest(final String sessionID, final String initiator,
final String target) {
return StringUtils.hash(sessionID + StringUtils.parseName(initiator)
+ "@" + StringUtils.parseServer(initiator) + "/"
+ StringUtils.parseResource(initiator)
+ StringUtils.parseName(target) + "@"
+ StringUtils.parseServer(target) + "/"
+ StringUtils.parseResource(target));
}
/*
* (non-Javadoc)
*
* @see org.jivesoftware.smackx.filetransfer.StreamNegotiator#initiateUpload(java.lang.String,
* org.jivesoftware.smackx.packet.StreamInitiation, java.io.File)
*/
public OutputStream createOutgoingStream(String streamID, String initiator,
String target) throws XMPPException
{
Socket socket;
try {
socket = initBytestreamSocket(streamID, initiator, target);
}
catch (Exception e) {
throw new XMPPException("Error establishing transfer socket", e);
}
if (socket != null) {
try {
return new BufferedOutputStream(socket.getOutputStream());
}
catch (IOException e) {
throw new XMPPException("Error establishing output stream", e);
}
}
return null;
}
private Socket initBytestreamSocket(final String sessionID,
String initiator, String target) throws Exception {
Socks5TransferNegotiatorManager.ProxyProcess process;
try {
process = establishListeningSocket();
}
catch (IOException io) {
process = null;
}
Socket conn;
try {
String localIP;
try {
localIP = discoverLocalIP();
}
catch (UnknownHostException e1) {
localIP = null;
}
Bytestream query = createByteStreamInit(initiator, target, sessionID,
localIP, (process != null ? process.getPort() : 0));
// if the local host is one of the options we need to wait for the
// remote connection.
conn = waitForUsedHostResponse(sessionID, process, createDigest(
sessionID, initiator, target), query).establishedSocket;
}
finally {
cleanupListeningSocket();
}
return conn;
}
/**
* Waits for the peer to respond with which host they chose to use.
*
* @param sessionID The session id of the stream.
* @param proxy The server socket which will listen locally for remote
* connections.
* @param digest the digest of the userids and the session id
* @param query the query which the response is being awaited
* @return the selected host
* @throws XMPPException when the response from the peer is an error or doesn't occur
* @throws IOException when there is an error establishing the local socket
*/
private SelectedHostInfo waitForUsedHostResponse(String sessionID,
final Socks5TransferNegotiatorManager.ProxyProcess proxy, final String digest,
final Bytestream query) throws XMPPException, IOException
{
SelectedHostInfo info = new SelectedHostInfo();
PacketCollector collector = connection
.createPacketCollector(new PacketIDFilter(query.getPacketID()));
connection.sendPacket(query);
Packet packet = collector.nextResult(10000);
collector.cancel();
Bytestream response;
if (packet != null && packet instanceof Bytestream) {
response = (Bytestream) packet;
}
else {
throw new XMPPException("Unexpected response from remote user");
}
// check for an error
if (response.getType().equals(IQ.Type.ERROR)) {
throw new XMPPException("Remote client returned error, stream hosts expected",
response.getError());
}
StreamHostUsed used = response.getUsedHost();
StreamHost usedHost = query.getStreamHost(used.getJID());
if (usedHost == null) {
throw new XMPPException("Remote user responded with unknown host");
}
// The local computer is acting as the proxy
if (used.getJID().equals(query.getFrom())) {
info.establishedSocket = proxy.getSocket(digest);
info.selectedHost = usedHost;
return info;
}
else {
info.establishedSocket = new Socket(usedHost.getAddress(), usedHost
.getPort());
establishSOCKS5ConnectionToProxy(info.establishedSocket, digest);
Bytestream activate = createByteStreamActivate(sessionID, response
.getTo(), usedHost.getJID(), response.getFrom());
collector = connection.createPacketCollector(new PacketIDFilter(
activate.getPacketID()));
connection.sendPacket(activate);
IQ serverResponse = (IQ) collector.nextResult(SmackConfiguration
.getPacketReplyTimeout());
collector.cancel();
if (!serverResponse.getType().equals(IQ.Type.RESULT)) {
info.establishedSocket.close();
return null;
}
return info;
}
}
private Socks5TransferNegotiatorManager.ProxyProcess establishListeningSocket()
throws IOException {
return transferNegotiatorManager.addTransfer();
}
private void cleanupListeningSocket() {
transferNegotiatorManager.removeTransfer();
}
private String discoverLocalIP() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
/**
* The bytestream init looks like this:
* <p/>
* <pre>
* &lt;iq type='set'
* from='initiator@host1/foo'
* to='target@host2/bar'
* id='initiate'&gt;
* &lt;query xmlns='http://jabber.org/protocol/bytestreams'
* sid='mySID'
* mode='tcp'&gt;
* &lt;streamhost
* jid='initiator@host1/foo'
* host='192.168.4.1'
* port='5086'/&gt;
* &lt;streamhost
* jid='proxy.host3'
* host='24.24.24.1'
* zeroconf='_jabber.bytestreams'/&gt;
* &lt;/query&gt;
* &lt;/iq&gt;
* </pre>
*
* @param from initiator@host1/foo - the file transfer initiator.
* @param to target@host2/bar - the file transfer target.
* @param sid 'mySID' - the unique identifier for this file transfer
* @param localIP the IP of the local machine if it is being provided, null otherwise.
* @param port the port of the local mahine if it is being provided, null otherwise.
* @return the created <b><i>Bytestream</b></i> packet
*/
private Bytestream createByteStreamInit(final String from, final String to,
final String sid, final String localIP, final int port)
{
Bytestream bs = new Bytestream();
bs.setTo(to);
bs.setFrom(from);
bs.setSessionID(sid);
bs.setType(IQ.Type.SET);
bs.setMode(Bytestream.Mode.tcp);
if (localIP != null && port > 0) {
bs.addStreamHost(from, localIP, port);
}
// make sure the proxies have been initialized completely
Collection<Bytestream.StreamHost> streamHosts = transferNegotiatorManager.getStreamHosts();
if (streamHosts != null) {
for (StreamHost host : streamHosts) {
bs.addStreamHost(host);
}
}
return bs;
}
/**
* Returns the packet to send notification to the stream host to activate
* the stream.
*
* @param sessionID the session ID of the file transfer to activate.
* @param from the sender of the bytestreeam
* @param to the JID of the stream host
* @param target the JID of the file transfer target.
* @return the packet to send notification to the stream host to
* activate the stream.
*/
private static Bytestream createByteStreamActivate(final String sessionID,
final String from, final String to, final String target)
{
Bytestream activate = new Bytestream(sessionID);
activate.setMode(null);
activate.setToActivate(target);
activate.setFrom(from);
activate.setTo(to);
activate.setType(IQ.Type.SET);
return activate;
}
public String[] getNamespaces() {
return new String[]{NAMESPACE};
}
private void establishSOCKS5ConnectionToProxy(Socket socket, String digest)
throws IOException {
byte[] cmd = new byte[3];
cmd[0] = (byte) 0x05;
cmd[1] = (byte) 0x01;
cmd[2] = (byte) 0x00;
OutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(cmd);
InputStream in = new DataInputStream(socket.getInputStream());
byte[] response = new byte[2];
in.read(response);
cmd = createOutgoingSocks5Message(1, digest);
out.write(cmd);
createIncomingSocks5Message(in);
}
static String createIncomingSocks5Message(InputStream in)
throws IOException {
byte[] cmd = new byte[5];
in.read(cmd, 0, 5);
byte[] addr = new byte[cmd[4]];
in.read(addr, 0, addr.length);
String digest = new String(addr);
in.read();
in.read();
return digest;
}
static byte[] createOutgoingSocks5Message(int cmd, String digest) {
byte addr[] = digest.getBytes();
byte[] data = new byte[7 + addr.length];
data[0] = (byte) 5;
data[1] = (byte) cmd;
data[2] = (byte) 0;
data[3] = (byte) 0x3;
data[4] = (byte) addr.length;
System.arraycopy(addr, 0, data, 5, addr.length);
data[data.length - 2] = (byte) 0;
data[data.length - 1] = (byte) 0;
return data;
}
@Override
public void cleanup() {
/* do nothing */
}
private static class SelectedHostInfo {
protected XMPPException exception;
protected StreamHost selectedHost;
protected Socket establishedSocket;
SelectedHostInfo(StreamHost selectedHost, Socket establishedSocket) {
this.selectedHost = selectedHost;
this.establishedSocket = establishedSocket;
}
public SelectedHostInfo() {
}
}
private static class BytestreamSIDFilter implements PacketFilter {
/**
* This PacketFilter accepts an incoming SOCKS5 Bytestream request with a specified session ID.
*/
private static class BytestreamSIDFilter extends PacketTypeFilter {
private String sessionID;
public BytestreamSIDFilter(String sessionID) {
super(Bytestream.class);
if (sessionID == null) {
throw new IllegalArgumentException("StreamID cannot be null");
}
this.sessionID = sessionID;
}
@Override
public boolean accept(Packet packet) {
if (!Bytestream.class.isInstance(packet)) {
return false;
}
Bytestream bytestream = (Bytestream) packet;
String sessionID = bytestream.getSessionID();
if (super.accept(packet)) {
Bytestream bytestream = (Bytestream) packet;
return (sessionID != null && sessionID.equals(this.sessionID));
// packet must by of type SET and contains the given session ID
return this.sessionID.equals(bytestream.getSessionID())
&& IQ.Type.SET.equals(bytestream.getType());
}
return false;
}
}
/**
* Derive from Socks5BytestreamRequest to access protected constructor.
*/
private static class ByteStreamRequest extends Socks5BytestreamRequest {
private ByteStreamRequest(Socks5BytestreamManager manager, Bytestream byteStreamRequest) {
super(manager, byteStreamRequest);
}
}
}

View file

@ -1,388 +0,0 @@
/**
* $Revision:$
* $Date:$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.util.Cache;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.DiscoverItems;
import org.jivesoftware.smackx.packet.Bytestream;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.*;
import java.io.*;
/**
*
*/
public class Socks5TransferNegotiatorManager implements FileTransferNegotiatorManager {
private static final long BLACKLIST_LIFETIME = 60 * 1000 * 120;
// locks the proxies during their initialization process
private final Object proxyLock = new Object();
private static ProxyProcess proxyProcess;
// locks on the proxy process during its initiatilization process
private final Object processLock = new Object();
private final Cache<String, Integer> addressBlacklist
= new Cache<String, Integer>(100, BLACKLIST_LIFETIME);
private Connection connection;
private List<String> proxies;
private List<Bytestream.StreamHost> streamHosts;
public Socks5TransferNegotiatorManager(Connection connection) {
this.connection = connection;
}
public StreamNegotiator createNegotiator() {
return new Socks5TransferNegotiator(this, connection);
}
public void incrementConnectionFailures(String address) {
Integer count = addressBlacklist.get(address);
if (count == null) {
count = 1;
}
else {
count += 1;
}
addressBlacklist.put(address, count);
}
public int getConnectionFailures(String address) {
Integer count = addressBlacklist.get(address);
return count != null ? count : 0;
}
public ProxyProcess addTransfer() throws IOException {
synchronized (processLock) {
if (proxyProcess == null) {
proxyProcess = new ProxyProcess(new ServerSocket(7777));
proxyProcess.start();
}
}
proxyProcess.addTransfer();
return proxyProcess;
}
public void removeTransfer() {
if (proxyProcess == null) {
return;
}
proxyProcess.removeTransfer();
}
public Collection<Bytestream.StreamHost> getStreamHosts() {
synchronized (proxyLock) {
if (proxies == null) {
initProxies();
}
}
return Collections.unmodifiableCollection(streamHosts);
}
/**
* Checks the service discovery item returned from a server component to verify if it is
* a File Transfer proxy or not.
*
* @param manager the service discovery manager which will be used to query the component
* @param item the discovered item on the server relating
* @return returns the JID of the proxy if it is a proxy or null if the item is not a proxy.
*/
private String checkIsProxy(ServiceDiscoveryManager manager, DiscoverItems.Item item) {
DiscoverInfo info;
try {
info = manager.discoverInfo(item.getEntityID());
}
catch (XMPPException e) {
return null;
}
Iterator<DiscoverInfo.Identity> itx = info.getIdentities();
while (itx.hasNext()) {
DiscoverInfo.Identity identity = itx.next();
if ("proxy".equalsIgnoreCase(identity.getCategory())
&& "bytestreams".equalsIgnoreCase(
identity.getType())) {
return info.getFrom();
}
}
return null;
}
private void initProxies() {
proxies = new ArrayList<String>();
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
try {
DiscoverItems discoItems = manager.discoverItems(connection.getServiceName());
Iterator<DiscoverItems.Item> it = discoItems.getItems();
while (it.hasNext()) {
DiscoverItems.Item item = it.next();
String proxy = checkIsProxy(manager, item);
if (proxy != null) {
proxies.add(proxy);
}
}
}
catch (XMPPException e) {
return;
}
if (proxies.size() > 0) {
initStreamHosts();
}
}
/**
* Loads streamhost address and ports from the proxies on the local server.
*/
private void initStreamHosts() {
List<Bytestream.StreamHost> streamHosts = new ArrayList<Bytestream.StreamHost>();
Iterator<String> it = proxies.iterator();
IQ query;
PacketCollector collector;
Bytestream response;
while (it.hasNext()) {
String jid = it.next();
query = new IQ() {
public String getChildElementXML() {
return "<query xmlns=\"http://jabber.org/protocol/bytestreams\"/>";
}
};
query.setType(IQ.Type.GET);
query.setTo(jid);
collector = connection.createPacketCollector(new PacketIDFilter(
query.getPacketID()));
connection.sendPacket(query);
response = (Bytestream) collector.nextResult(SmackConfiguration
.getPacketReplyTimeout());
if (response != null) {
streamHosts.addAll(response.getStreamHosts());
}
collector.cancel();
}
this.streamHosts = streamHosts;
}
public void cleanup() {
synchronized (processLock) {
if (proxyProcess != null) {
proxyProcess.stop();
proxyProcess = null;
}
}
}
class ProxyProcess implements Runnable {
private final ServerSocket listeningSocket;
private final Map<String, Socket> connectionMap = new HashMap<String, Socket>();
private boolean done = false;
private Thread thread;
private int transfers;
public void run() {
try {
try {
listeningSocket.setSoTimeout(10000);
}
catch (SocketException e) {
// There was a TCP error, lets print the stack trace
e.printStackTrace();
return;
}
while (!done) {
Socket conn = null;
synchronized (ProxyProcess.this) {
while (transfers <= 0 && !done) {
transfers = -1;
try {
ProxyProcess.this.wait();
}
catch (InterruptedException e) {
/* Do nothing */
}
}
}
if (done) {
break;
}
try {
synchronized (listeningSocket) {
conn = listeningSocket.accept();
}
if (conn == null) {
continue;
}
String digest = establishSocks5UploadConnection(conn);
synchronized (connectionMap) {
connectionMap.put(digest, conn);
}
}
catch (SocketTimeoutException e) {
/* Do Nothing */
}
catch (IOException e) {
/* Do Nothing */
}
catch (XMPPException e) {
e.printStackTrace();
if (conn != null) {
try {
conn.close();
}
catch (IOException e1) {
/* Do Nothing */
}
}
}
}
}
finally {
try {
listeningSocket.close();
}
catch (IOException e) {
/* Do Nothing */
}
}
}
/**
* Negotiates the Socks 5 bytestream when the local computer is acting as
* the proxy.
*
* @param connection the socket connection with the peer.
* @return the SHA-1 digest that is used to uniquely identify the file
* transfer.
* @throws XMPPException
* @throws IOException
*/
private String establishSocks5UploadConnection(Socket connection) throws XMPPException, IOException {
OutputStream out = new DataOutputStream(connection.getOutputStream());
InputStream in = new DataInputStream(connection.getInputStream());
// first byte is version should be 5
int b = in.read();
if (b != 5) {
throw new XMPPException("Only SOCKS5 supported");
}
// second byte number of authentication methods supported
b = in.read();
int[] auth = new int[b];
for (int i = 0; i < b; i++) {
auth[i] = in.read();
}
int authMethod = -1;
for (int anAuth : auth) {
authMethod = (anAuth == 0 ? 0 : -1); // only auth method
// 0, no
// authentication,
// supported
if (authMethod == 0) {
break;
}
}
if (authMethod != 0) {
throw new XMPPException("Authentication method not supported");
}
byte[] cmd = new byte[2];
cmd[0] = (byte) 0x05;
cmd[1] = (byte) 0x00;
out.write(cmd);
String responseDigest = Socks5TransferNegotiator.createIncomingSocks5Message(in);
cmd = Socks5TransferNegotiator.createOutgoingSocks5Message(0, responseDigest);
if (!connection.isConnected()) {
throw new XMPPException("Socket closed by remote user");
}
out.write(cmd);
return responseDigest;
}
public void start() {
thread.start();
}
public void stop() {
done = true;
synchronized (this) {
this.notify();
}
synchronized (listeningSocket) {
listeningSocket.notify();
}
}
public int getPort() {
return listeningSocket.getLocalPort();
}
ProxyProcess(ServerSocket listeningSocket) {
thread = new Thread(this, "File Transfer Connection Listener");
this.listeningSocket = listeningSocket;
}
public Socket getSocket(String digest) {
synchronized (connectionMap) {
return connectionMap.get(digest);
}
}
public void addTransfer() {
synchronized (this) {
if (transfers == -1) {
transfers = 1;
this.notify();
}
else {
transfers++;
}
}
}
public void removeTransfer() {
synchronized (this) {
transfers--;
}
}
}
}

View file

@ -37,7 +37,7 @@ import java.io.OutputStream;
/**
* After the file transfer negotiation process is completed according to
* JEP-0096, the negotation process is passed off to a particular stream
* JEP-0096, the negotiation process is passed off to a particular stream
* negotiator. The stream negotiator will then negotiate the chosen stream and
* return the stream to transfer the file.
*
@ -49,9 +49,9 @@ public abstract class StreamNegotiator {
* Creates the initiation acceptance packet to forward to the stream
* initiator.
*
* @param streamInitiationOffer The offer from the stream initatior to connect for a stream.
* @param streamInitiationOffer The offer from the stream initiator to connect for a stream.
* @param namespaces The namespace that relates to the accepted means of transfer.
* @return The response to be forwarded to the initator.
* @return The response to be forwarded to the initiator.
*/
public StreamInitiation createInitiationAccept(
StreamInitiation streamInitiationOffer, String[] namespaces)
@ -104,7 +104,7 @@ public abstract class StreamNegotiator {
* Returns the packet filter that will return the initiation packet for the appropriate stream
* initiation.
*
* @param from The initiatior of the file transfer.
* @param from The initiator of the file transfer.
* @param streamID The stream ID related to the transfer.
* @return The <b><i>PacketFilter</b></i> that will return the packet relatable to the stream
* initiation.
@ -112,23 +112,26 @@ public abstract class StreamNegotiator {
public abstract PacketFilter getInitiationPacketFilter(String from, String streamID);
abstract InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException;
abstract InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException,
InterruptedException;
/**
* This method handles the file stream download negotiation process. The
* appropriate stream negotiator's initiate incoming stream is called after
* an appropriate file transfer method is selected. The manager will respond
* to the initatior with the selected means of transfer, then it will handle
* any negotation specific to the particular transfer method. This method
* to the initiator with the selected means of transfer, then it will handle
* any negotiation specific to the particular transfer method. This method
* returns the InputStream, ready to transfer the file.
*
* @param initiation The initation that triggered this download.
* @return After the negotation process is complete, the InputStream to
* @param initiation The initiation that triggered this download.
* @return After the negotiation process is complete, the InputStream to
* write a file to is returned.
* @throws XMPPException If an error occurs during this process an XMPPException is
* thrown.
* @throws InterruptedException If thread is interrupted.
*/
public abstract InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException;
public abstract InputStream createIncomingStream(StreamInitiation initiation)
throws XMPPException, InterruptedException;
/**
* This method handles the file upload stream negotiation process. The
@ -138,7 +141,7 @@ public abstract class StreamNegotiator {
*
* @param streamID The streamID that uniquely identifies the file transfer.
* @param initiator The fully-qualified JID of the initiator of the file transfer.
* @param target The fully-qualified JID of the target or reciever of the file
* @param target The fully-qualified JID of the target or receiver of the file
* transfer.
* @return The negotiated stream ready for data.
* @throws XMPPException If an error occurs during the negotiation process an