more efficant way of calculating the sha1 sum. closing connections

This commit is contained in:
Daniel Gultsch 2014-04-13 11:32:45 +02:00
parent 7b554f2001
commit 27d5966ac3
10 changed files with 204 additions and 109 deletions

View file

@ -9,6 +9,7 @@ public class Message extends AbstractEntity {
public static final String TABLENAME = "messages"; public static final String TABLENAME = "messages";
public static final int STATUS_RECIEVING = -1;
public static final int STATUS_RECIEVED = 0; public static final int STATUS_RECIEVED = 0;
public static final int STATUS_UNSEND = 1; public static final int STATUS_UNSEND = 1;
public static final int STATUS_SEND = 2; public static final int STATUS_SEND = 2;

View file

@ -1,15 +1,10 @@
package eu.siacs.conversations.persistance; package eu.siacs.conversations.persistance;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
@ -20,7 +15,7 @@ import android.util.LruCache;
import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.xmpp.jingle.JingleFile;
public class FileBackend { public class FileBackend {
@ -43,13 +38,13 @@ public class FileBackend {
} }
public File getImageFile(Message message) { public JingleFile getImageFile(Message message) {
Conversation conversation = message.getConversation(); Conversation conversation = message.getConversation();
String prefix = context.getFilesDir().getAbsolutePath(); String prefix = context.getFilesDir().getAbsolutePath();
String path = prefix + "/" + conversation.getAccount().getJid() + "/" String path = prefix + "/" + conversation.getAccount().getJid() + "/"
+ conversation.getContactJid(); + conversation.getContactJid();
String filename = message.getUuid() + ".webp"; String filename = message.getUuid() + ".webp";
return new File(path + "/" + filename); return new JingleFile(path + "/" + filename);
} }
private Bitmap resize(Bitmap originalBitmap, int size) { private Bitmap resize(Bitmap originalBitmap, int size) {
@ -73,11 +68,11 @@ public class FileBackend {
} }
} }
public File copyImageToPrivateStorage(Message message, Uri image) { public JingleFile copyImageToPrivateStorage(Message message, Uri image) {
try { try {
InputStream is = context.getContentResolver() InputStream is = context.getContentResolver()
.openInputStream(image); .openInputStream(image);
File file = getImageFile(message); JingleFile file = getImageFile(message);
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
file.createNewFile(); file.createNewFile();
OutputStream os = new FileOutputStream(file); OutputStream os = new FileOutputStream(file);
@ -89,7 +84,6 @@ public class FileBackend {
Log.d("xmppService", "couldnt compress"); Log.d("xmppService", "couldnt compress");
} }
os.close(); os.close();
message.setBody(this.createSha1(file));
return file; return file;
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
@ -118,43 +112,4 @@ public class FileBackend {
} }
return thumbnail; return thumbnail;
} }
private String createSha1(final File file) {
InputStream fis = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
fis = new FileInputStream(file);
int n = 0;
byte[] buffer = new byte[8192];
while (n != -1) {
n = fis.read(buffer);
if (n > 0) {
digest.update(buffer, 0, n);
}
}
fis.close();
return CryptoHelper.bytesToHex(digest.digest());
} catch (NoSuchAlgorithmException e) {
return null;
} catch (FileNotFoundException e) {
if (fis!=null) {
try {
fis.close();
return null;
} catch (IOException e1) {
return null;
}
}
} catch (IOException e) {
if (fis!=null) {
try {
fis.close();
return null;
} catch (IOException e1) {
return null;
}
}
}
return null;
}
} }

View file

@ -365,6 +365,8 @@ public class XmppConnectionService extends Service {
processRosterItems(account, query); processRosterItems(account, query);
mergePhoneContactsWithRoster(null); mergePhoneContactsWithRoster(null);
} }
} else {
Log.d(LOGTAG,"iq packet arrived "+packet.toString());
} }
} }
}; };
@ -1390,6 +1392,8 @@ public class XmppConnectionService extends Service {
public void markMessage(Message message, int status) { public void markMessage(Message message, int status) {
message.setStatus(status); message.setStatus(status);
databaseBackend.updateMessage(message); databaseBackend.updateMessage(message);
convChangedListener.onConversationListChanged(); if (convChangedListener!=null) {
convChangedListener.onConversationListChanged();
}
} }
} }

View file

@ -1,19 +1,23 @@
package eu.siacs.conversations.xmpp.jingle; package eu.siacs.conversations.xmpp.jingle;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.util.Log; import android.util.Log;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.Content; import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket; import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
import eu.siacs.conversations.xmpp.stanzas.IqPacket; import eu.siacs.conversations.xmpp.stanzas.IqPacket;
public class JingleConnection { public class JingleConnection {
@ -24,6 +28,8 @@ public class JingleConnection {
public static final int STATUS_INITIATED = 0; public static final int STATUS_INITIATED = 0;
public static final int STATUS_ACCEPTED = 1; public static final int STATUS_ACCEPTED = 1;
public static final int STATUS_TERMINATED = 2; public static final int STATUS_TERMINATED = 2;
public static final int STATUS_CANCELED = 3;
public static final int STATUS_FINISHED = 4;
public static final int STATUS_FAILED = 99; public static final int STATUS_FAILED = 99;
private int status = -1; private int status = -1;
@ -34,7 +40,7 @@ public class JingleConnection {
private String responder; private String responder;
private List<Element> candidates = new ArrayList<Element>(); private List<Element> candidates = new ArrayList<Element>();
private HashMap<String, SocksConnection> connections = new HashMap<String, SocksConnection>(); private HashMap<String, SocksConnection> connections = new HashMap<String, SocksConnection>();
private File file = null; private JingleFile file = null;
private OnIqPacketReceived responseListener = new OnIqPacketReceived() { private OnIqPacketReceived responseListener = new OnIqPacketReceived() {
@ -50,7 +56,6 @@ public class JingleConnection {
public JingleConnection(JingleConnectionManager mJingleConnectionManager) { public JingleConnection(JingleConnectionManager mJingleConnectionManager) {
this.mJingleConnectionManager = mJingleConnectionManager; this.mJingleConnectionManager = mJingleConnectionManager;
this.mXmppConnectionService = mJingleConnectionManager.getXmppConnectionService(); this.mXmppConnectionService = mJingleConnectionManager.getXmppConnectionService();
this.sessionId = this.mJingleConnectionManager.nextRandomId();
} }
public String getSessionId() { public String getSessionId() {
@ -68,10 +73,12 @@ public class JingleConnection {
public void deliverPacket(JinglePacket packet) { public void deliverPacket(JinglePacket packet) {
if (packet.isAction("session-terminate")) { if (packet.isAction("session-terminate")) {
if (status == STATUS_INITIATED) { Reason reason = packet.getReason();
mXmppConnectionService.markMessage(message, Message.STATUS_SEND_REJECTED); if (reason.hasChild("cancel")) {
this.cancel();
} else if (reason.hasChild("success")) {
this.finish();
} }
status = STATUS_TERMINATED;
} else if (packet.isAction("session-accept")) { } else if (packet.isAction("session-accept")) {
accept(packet); accept(packet);
} else if (packet.isAction("transport-info")) { } else if (packet.isAction("transport-info")) {
@ -86,6 +93,7 @@ public class JingleConnection {
this.account = message.getConversation().getAccount(); this.account = message.getConversation().getAccount();
this.initiator = this.account.getFullJid(); this.initiator = this.account.getFullJid();
this.responder = this.message.getCounterpart(); this.responder = this.message.getCounterpart();
this.sessionId = this.mJingleConnectionManager.nextRandomId();
if (this.candidates.size() > 0) { if (this.candidates.size() > 0) {
this.sendInitRequest(); this.sendInitRequest();
} else { } else {
@ -103,6 +111,19 @@ public class JingleConnection {
} }
public void init(Account account, JinglePacket packet) {
Conversation conversation = this.mXmppConnectionService.findOrCreateConversation(account, packet.getFrom().split("/")[0], false);
this.message = new Message(conversation, "receiving image file", Message.ENCRYPTION_NONE);
this.message.setType(Message.TYPE_IMAGE);
this.message.setStatus(Message.STATUS_RECIEVING);
this.account = account;
this.initiator = packet.getFrom();
this.responder = this.account.getFullJid();
this.sessionId = packet.getSessionId();
this.candidates.addAll(packet.getJingleContent().getCanditates());
Log.d("xmppService","new incomming jingle session "+this.sessionId+" num canditaes:"+this.candidates.size());
}
private void sendInitRequest() { private void sendInitRequest() {
JinglePacket packet = this.bootstrapPacket(); JinglePacket packet = this.bootstrapPacket();
packet.setAction("session-initiate"); packet.setAction("session-initiate");
@ -145,8 +166,16 @@ public class JingleConnection {
Log.d("xmppService","transport info : "+content.toString()); Log.d("xmppService","transport info : "+content.toString());
String cid = content.getUsedCandidate(); String cid = content.getUsedCandidate();
if (cid!=null) { if (cid!=null) {
final File file = this.mXmppConnectionService.getFileBackend().getImageFile(this.message); final JingleFile file = this.mXmppConnectionService.getFileBackend().getImageFile(this.message);
final SocksConnection connection = this.connections.get(cid); final SocksConnection connection = this.connections.get(cid);
final OnFileTransmitted callback = new OnFileTransmitted() {
@Override
public void onFileTransmitted(JingleFile file) {
Log.d("xmppService","sucessfully transmitted file. sha1:"+file.getSha1Sum());
}
};
final IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT);
if (connection.isProxy()) { if (connection.isProxy()) {
IqPacket activation = new IqPacket(IqPacket.TYPE_SET); IqPacket activation = new IqPacket(IqPacket.TYPE_SET);
activation.setTo(connection.getJid()); activation.setTo(connection.getJid());
@ -157,16 +186,30 @@ public class JingleConnection {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
account.getXmppConnection().sendIqPacket(response, null);
Log.d("xmppService","activation result: "+packet.toString()); Log.d("xmppService","activation result: "+packet.toString());
connection.send(file); connection.send(file,callback);
} }
}); });
} else { } else {
connection.send(file); account.getXmppConnection().sendIqPacket(response, null);
connection.send(file,callback);
} }
} }
} }
private void finish() {
this.status = STATUS_FINISHED;
this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND);
this.disconnect();
}
public void cancel() {
this.disconnect();
this.status = STATUS_CANCELED;
this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_REJECTED);
}
private void connectWithCandidates() { private void connectWithCandidates() {
for(Element canditate : this.candidates) { for(Element canditate : this.candidates) {
String host = canditate.getAttribute("host"); String host = canditate.getAttribute("host");
@ -179,6 +222,15 @@ public class JingleConnection {
} }
} }
private void disconnect() {
Iterator<Entry<String, SocksConnection>> it = this.connections.entrySet().iterator();
while (it.hasNext()) {
Entry<String, SocksConnection> pairs = it.next();
pairs.getValue().disconnect();
it.remove();
}
}
private void sendCandidateUsed(String cid) { private void sendCandidateUsed(String cid) {
} }
@ -190,4 +242,8 @@ public class JingleConnection {
public String getResponder() { public String getResponder() {
return this.responder; return this.responder;
} }
public int getStatus() {
return this.status;
}
} }

View file

@ -32,15 +32,20 @@ public class JingleConnectionManager {
} }
public void deliverPacket(Account account, JinglePacket packet) { public void deliverPacket(Account account, JinglePacket packet) {
for (JingleConnection connection : connections) { if (packet.isAction("session-initiate")) {
if (connection.getAccountJid().equals(account.getJid()) && connection JingleConnection connection = new JingleConnection(this);
.getSessionId().equals(packet.getSessionId()) && connection connection.init(account,packet);
.getCounterPart().equals(packet.getFrom())) { } else {
connection.deliverPacket(packet); for (JingleConnection connection : connections) {
return; if (connection.getAccountJid().equals(account.getJid()) && connection
.getSessionId().equals(packet.getSessionId()) && connection
.getCounterPart().equals(packet.getFrom())) {
connection.deliverPacket(packet);
return;
}
} }
Log.d("xmppService","delivering packet failed "+packet.toString());
} }
Log.d("xmppService","delivering packet failed "+packet.toString());
} }
public JingleConnection createNewConnection(Message message) { public JingleConnection createNewConnection(Message message) {

View file

@ -0,0 +1,35 @@
package eu.siacs.conversations.xmpp.jingle;
import java.io.File;
public class JingleFile extends File {
private static final long serialVersionUID = 2247012619505115863L;
private long expectedSize = 0;
private String sha1sum;
public JingleFile(String path) {
super(path);
}
public long getSize() {
return super.length();
}
public long getExpectedSize() {
return this.expectedSize;
}
public void setExpectedSize(long size) {
this.expectedSize = size;
}
public String getSha1Sum() {
return this.sha1sum;
}
public void setSha1Sum(String sum) {
this.sha1sum = sum;
}
}

View file

@ -0,0 +1,5 @@
package eu.siacs.conversations.xmpp.jingle;
public interface OnFileTransmitted {
public void onFileTransmitted(JingleFile file);
}

View file

@ -1,6 +1,5 @@
package eu.siacs.conversations.xmpp.jingle; package eu.siacs.conversations.xmpp.jingle;
import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
@ -27,7 +26,8 @@ public class SocksConnection {
private String destination; private String destination;
private OutputStream outputStream; private OutputStream outputStream;
public SocksConnection(JingleConnection jingleConnection, String host, String jid, int port, String type) { public SocksConnection(JingleConnection jingleConnection, String host,
String jid, int port, String type) {
this.jingleConnection = jingleConnection; this.jingleConnection = jingleConnection;
this.host = host; this.host = host;
this.jid = jid; this.jid = jid;
@ -40,8 +40,10 @@ public class SocksConnection {
destBuilder.append(jingleConnection.getInitiator()); destBuilder.append(jingleConnection.getInitiator());
destBuilder.append(jingleConnection.getResponder()); destBuilder.append(jingleConnection.getResponder());
mDigest.reset(); mDigest.reset();
this.destination = CryptoHelper.bytesToHex(mDigest.digest(destBuilder.toString().getBytes())); this.destination = CryptoHelper.bytesToHex(mDigest
Log.d("xmppService","host="+host+", port="+port+", destination: "+destination); .digest(destBuilder.toString().getBytes()));
Log.d("xmppService", "host=" + host + ", port=" + port
+ ", destination: " + destination);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
} }
@ -52,18 +54,19 @@ public class SocksConnection {
this.socket = new Socket(this.host, this.port); this.socket = new Socket(this.host, this.port);
InputStream is = socket.getInputStream(); InputStream is = socket.getInputStream();
this.outputStream = socket.getOutputStream(); this.outputStream = socket.getOutputStream();
byte[] login = {0x05, 0x01, 0x00}; byte[] login = { 0x05, 0x01, 0x00 };
byte[] expectedReply = {0x05,0x00}; byte[] expectedReply = { 0x05, 0x00 };
byte[] reply = new byte[2]; byte[] reply = new byte[2];
this.outputStream.write(login); this.outputStream.write(login);
is.read(reply); is.read(reply);
if (Arrays.equals(reply, expectedReply)) { if (Arrays.equals(reply, expectedReply)) {
String connect = ""+'\u0005'+'\u0001'+'\u0000'+'\u0003'+'\u0028'+this.destination+'\u0000'+'\u0000'; String connect = "" + '\u0005' + '\u0001' + '\u0000' + '\u0003'
+ '\u0028' + this.destination + '\u0000' + '\u0000';
this.outputStream.write(connect.getBytes()); this.outputStream.write(connect.getBytes());
byte[] result = new byte[2]; byte[] result = new byte[2];
is.read(result); is.read(result);
int status = result[0]; int status = result[0];
return (status==0); return (status == 0);
} else { } else {
socket.close(); socket.close();
return false; return false;
@ -75,32 +78,49 @@ public class SocksConnection {
} }
} }
public void send(File file) { public void send(final JingleFile file, final OnFileTransmitted callback) {
FileInputStream fileInputStream = null; new Thread(new Runnable() {
try {
fileInputStream = new FileInputStream(file);
int count;
byte[] buffer = new byte[8192];
while ((count = fileInputStream.read(buffer)) > 0) {
this.outputStream.write(buffer, 0, count);
}
} catch (FileNotFoundException e) { @Override
// TODO Auto-generated catch block public void run() {
e.printStackTrace(); FileInputStream fileInputStream = null;
} catch (IOException e) { try {
// TODO Auto-generated catch block MessageDigest digest = MessageDigest.getInstance("SHA-1");
e.printStackTrace(); digest.reset();
} finally { fileInputStream = new FileInputStream(file);
try { int count;
if (fileInputStream!=null) { byte[] buffer = new byte[8192];
fileInputStream.close(); while ((count = fileInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, count);
digest.update(buffer, 0, count);
}
outputStream.flush();
file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest()));
if (callback!=null) {
callback.onFileTransmitted(file);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} }).start();
} }
public boolean isProxy() { public boolean isProxy() {
@ -110,4 +130,15 @@ public class SocksConnection {
public String getJid() { public String getJid() {
return this.jid; return this.jid;
} }
public void disconnect() {
if (this.socket!=null) {
try {
this.socket.close();
Log.d("xmppService","cloesd socket with "+this.host);
} catch (IOException e) {
Log.d("xmppService","error closing socket with "+this.host);
}
}
}
} }

View file

@ -1,10 +1,10 @@
package eu.siacs.conversations.xmpp.jingle.stanzas; package eu.siacs.conversations.xmpp.jingle.stanzas;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.jingle.JingleFile;
public class Content extends Element { public class Content extends Element {
private Content(String name) { private Content(String name) {
@ -15,13 +15,12 @@ public class Content extends Element {
super("content"); super("content");
} }
public void offerFile(File actualFile, String hash) { public void offerFile(JingleFile actualFile, String hash) {
Element description = this.addChild("description", "urn:xmpp:jingle:apps:file-transfer:3"); Element description = this.addChild("description", "urn:xmpp:jingle:apps:file-transfer:3");
Element offer = description.addChild("offer"); Element offer = description.addChild("offer");
Element file = offer.addChild("file"); Element file = offer.addChild("file");
file.addChild("size").setContent(""+actualFile.length()); file.addChild("size").setContent(""+actualFile.getSize());
file.addChild("name").setContent(actualFile.getName()); file.addChild("name").setContent(actualFile.getName());
file.addChild("hash","urn:xmpp:hashes:1").setAttribute("algo", "sha-1").setContent(hash);
} }
public void setCandidates(String transportId, List<Element> canditates) { public void setCandidates(String transportId, List<Element> canditates) {

View file

@ -45,6 +45,10 @@ public class JinglePacket extends IqPacket {
return this; return this;
} }
public Reason getReason() {
return this.reason;
}
private void build() { private void build() {
this.children.clear(); this.children.clear();
this.jingle.clearChildren(); this.jingle.clearChildren();