1package eu.siacs.conversations.xmpp.jingle;
2
3import android.content.Intent;
4import android.net.Uri;
5import android.util.Log;
6import android.util.Pair;
7
8import java.io.FileNotFoundException;
9import java.io.InputStream;
10import java.io.OutputStream;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Iterator;
14import java.util.List;
15import java.util.Locale;
16import java.util.Map.Entry;
17import java.util.concurrent.ConcurrentHashMap;
18
19import eu.siacs.conversations.Config;
20import eu.siacs.conversations.crypto.axolotl.AxolotlService;
21import eu.siacs.conversations.crypto.axolotl.OnMessageCreatedCallback;
22import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
23import eu.siacs.conversations.entities.Account;
24import eu.siacs.conversations.entities.Conversation;
25import eu.siacs.conversations.entities.DownloadableFile;
26import eu.siacs.conversations.entities.Message;
27import eu.siacs.conversations.entities.Transferable;
28import eu.siacs.conversations.entities.TransferablePlaceholder;
29import eu.siacs.conversations.persistance.FileBackend;
30import eu.siacs.conversations.services.AbstractConnectionManager;
31import eu.siacs.conversations.services.XmppConnectionService;
32import eu.siacs.conversations.xml.Element;
33import eu.siacs.conversations.xmpp.OnIqPacketReceived;
34import eu.siacs.conversations.xmpp.jid.Jid;
35import eu.siacs.conversations.xmpp.jingle.stanzas.Content;
36import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
37import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
38import eu.siacs.conversations.xmpp.stanzas.IqPacket;
39
40public class JingleConnection implements Transferable {
41
42 private JingleConnectionManager mJingleConnectionManager;
43 private XmppConnectionService mXmppConnectionService;
44
45 protected static final int JINGLE_STATUS_INITIATED = 0;
46 protected static final int JINGLE_STATUS_ACCEPTED = 1;
47 protected static final int JINGLE_STATUS_FINISHED = 4;
48 protected static final int JINGLE_STATUS_TRANSMITTING = 5;
49 protected static final int JINGLE_STATUS_FAILED = 99;
50
51 private int ibbBlockSize = 8192;
52
53 private int mJingleStatus = -1;
54 private int mStatus = Transferable.STATUS_UNKNOWN;
55 private Message message;
56 private String sessionId;
57 private Account account;
58 private Jid initiator;
59 private Jid responder;
60 private List<JingleCandidate> candidates = new ArrayList<>();
61 private ConcurrentHashMap<String, JingleSocks5Transport> connections = new ConcurrentHashMap<>();
62
63 private String transportId;
64 private Element fileOffer;
65 private DownloadableFile file = null;
66
67 private String contentName;
68 private String contentCreator;
69
70 private int mProgress = 0;
71
72 private boolean receivedCandidate = false;
73 private boolean sentCandidate = false;
74
75 private boolean acceptedAutomatically = false;
76
77 private XmppAxolotlMessage mXmppAxolotlMessage;
78
79 private JingleTransport transport = null;
80
81 private OutputStream mFileOutputStream;
82 private InputStream mFileInputStream;
83
84 private OnIqPacketReceived responseListener = new OnIqPacketReceived() {
85
86 @Override
87 public void onIqPacketReceived(Account account, IqPacket packet) {
88 if (packet.getType() != IqPacket.TYPE.RESULT) {
89 fail();
90 }
91 }
92 };
93
94 final OnFileTransmissionStatusChanged onFileTransmissionSatusChanged = new OnFileTransmissionStatusChanged() {
95
96 @Override
97 public void onFileTransmitted(DownloadableFile file) {
98 if (responder.equals(account.getJid())) {
99 sendSuccess();
100 mXmppConnectionService.getFileBackend().updateFileParams(message);
101 mXmppConnectionService.databaseBackend.createMessage(message);
102 mXmppConnectionService.markMessage(message,Message.STATUS_RECEIVED);
103 if (acceptedAutomatically) {
104 message.markUnread();
105 JingleConnection.this.mXmppConnectionService.getNotificationService().push(message);
106 }
107 } else {
108 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
109 file.delete();
110 }
111 }
112 Log.d(Config.LOGTAG,"successfully transmitted file:" + file.getAbsolutePath()+" ("+file.getSha1Sum()+")");
113 if (message.getEncryption() != Message.ENCRYPTION_PGP) {
114 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
115 intent.setData(Uri.fromFile(file));
116 mXmppConnectionService.sendBroadcast(intent);
117 } else {
118 account.getPgpDecryptionService().add(message);
119 }
120 }
121
122 @Override
123 public void onFileTransferAborted() {
124 JingleConnection.this.sendCancel();
125 JingleConnection.this.fail();
126 }
127 };
128
129 public InputStream getFileInputStream() {
130 return this.mFileInputStream;
131 }
132
133 public OutputStream getFileOutputStream() {
134 return this.mFileOutputStream;
135 }
136
137 private OnProxyActivated onProxyActivated = new OnProxyActivated() {
138
139 @Override
140 public void success() {
141 if (initiator.equals(account.getJid())) {
142 Log.d(Config.LOGTAG, "we were initiating. sending file");
143 transport.send(file, onFileTransmissionSatusChanged);
144 } else {
145 transport.receive(file, onFileTransmissionSatusChanged);
146 Log.d(Config.LOGTAG, "we were responding. receiving file");
147 }
148 }
149
150 @Override
151 public void failed() {
152 Log.d(Config.LOGTAG, "proxy activation failed");
153 }
154 };
155
156 public JingleConnection(JingleConnectionManager mJingleConnectionManager) {
157 this.mJingleConnectionManager = mJingleConnectionManager;
158 this.mXmppConnectionService = mJingleConnectionManager
159 .getXmppConnectionService();
160 }
161
162 public String getSessionId() {
163 return this.sessionId;
164 }
165
166 public Account getAccount() {
167 return this.account;
168 }
169
170 public Jid getCounterPart() {
171 return this.message.getCounterpart();
172 }
173
174 public void deliverPacket(JinglePacket packet) {
175 boolean returnResult = true;
176 if (packet.isAction("session-terminate")) {
177 Reason reason = packet.getReason();
178 if (reason != null) {
179 if (reason.hasChild("cancel")) {
180 this.fail();
181 } else if (reason.hasChild("success")) {
182 this.receiveSuccess();
183 } else {
184 this.fail();
185 }
186 } else {
187 this.fail();
188 }
189 } else if (packet.isAction("session-accept")) {
190 returnResult = receiveAccept(packet);
191 } else if (packet.isAction("transport-info")) {
192 returnResult = receiveTransportInfo(packet);
193 } else if (packet.isAction("transport-replace")) {
194 if (packet.getJingleContent().hasIbbTransport()) {
195 returnResult = this.receiveFallbackToIbb(packet);
196 } else {
197 returnResult = false;
198 Log.d(Config.LOGTAG, "trying to fallback to something unknown"
199 + packet.toString());
200 }
201 } else if (packet.isAction("transport-accept")) {
202 returnResult = this.receiveTransportAccept(packet);
203 } else {
204 Log.d(Config.LOGTAG, "packet arrived in connection. action was "
205 + packet.getAction());
206 returnResult = false;
207 }
208 IqPacket response;
209 if (returnResult) {
210 response = packet.generateResponse(IqPacket.TYPE.RESULT);
211
212 } else {
213 response = packet.generateResponse(IqPacket.TYPE.ERROR);
214 }
215 mXmppConnectionService.sendIqPacket(account,response,null);
216 }
217
218 public void init(final Message message) {
219 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
220 Conversation conversation = message.getConversation();
221 conversation.getAccount().getAxolotlService().prepareKeyTransportMessage(conversation.getContact(), new OnMessageCreatedCallback() {
222 @Override
223 public void run(XmppAxolotlMessage xmppAxolotlMessage) {
224 init(message, xmppAxolotlMessage);
225 }
226 });
227 } else {
228 init(message, null);
229 }
230 }
231
232 private void init(Message message, XmppAxolotlMessage xmppAxolotlMessage) {
233 this.mXmppAxolotlMessage = xmppAxolotlMessage;
234 this.contentCreator = "initiator";
235 this.contentName = this.mJingleConnectionManager.nextRandomId();
236 this.message = message;
237 this.message.setTransferable(this);
238 this.mStatus = Transferable.STATUS_UPLOADING;
239 this.account = message.getConversation().getAccount();
240 this.initiator = this.account.getJid();
241 this.responder = this.message.getCounterpart();
242 this.sessionId = this.mJingleConnectionManager.nextRandomId();
243 if (this.candidates.size() > 0) {
244 this.sendInitRequest();
245 } else {
246 this.mJingleConnectionManager.getPrimaryCandidate(account,
247 new OnPrimaryCandidateFound() {
248
249 @Override
250 public void onPrimaryCandidateFound(boolean success,
251 final JingleCandidate candidate) {
252 if (success) {
253 final JingleSocks5Transport socksConnection = new JingleSocks5Transport(
254 JingleConnection.this, candidate);
255 connections.put(candidate.getCid(),
256 socksConnection);
257 socksConnection
258 .connect(new OnTransportConnected() {
259
260 @Override
261 public void failed() {
262 Log.d(Config.LOGTAG,
263 "connection to our own primary candidete failed");
264 sendInitRequest();
265 }
266
267 @Override
268 public void established() {
269 Log.d(Config.LOGTAG,
270 "succesfully connected to our own primary candidate");
271 mergeCandidate(candidate);
272 sendInitRequest();
273 }
274 });
275 mergeCandidate(candidate);
276 } else {
277 Log.d(Config.LOGTAG, "no primary candidate of our own was found");
278 sendInitRequest();
279 }
280 }
281 });
282 }
283
284 }
285
286 public void init(Account account, JinglePacket packet) {
287 this.mJingleStatus = JINGLE_STATUS_INITIATED;
288 Conversation conversation = this.mXmppConnectionService
289 .findOrCreateConversation(account,
290 packet.getFrom().toBareJid(), false);
291 this.message = new Message(conversation, "", Message.ENCRYPTION_NONE);
292 this.message.setStatus(Message.STATUS_RECEIVED);
293 this.mStatus = Transferable.STATUS_OFFER;
294 this.message.setTransferable(this);
295 final Jid from = packet.getFrom();
296 this.message.setCounterpart(from);
297 this.account = account;
298 this.initiator = packet.getFrom();
299 this.responder = this.account.getJid();
300 this.sessionId = packet.getSessionId();
301 Content content = packet.getJingleContent();
302 this.contentCreator = content.getAttribute("creator");
303 this.contentName = content.getAttribute("name");
304 this.transportId = content.getTransportId();
305 this.mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
306 this.fileOffer = packet.getJingleContent().getFileOffer();
307
308 mXmppConnectionService.sendIqPacket(account,packet.generateResponse(IqPacket.TYPE.RESULT),null);
309
310 if (fileOffer != null) {
311 Element encrypted = fileOffer.findChild("encrypted", AxolotlService.PEP_PREFIX);
312 if (encrypted != null) {
313 this.mXmppAxolotlMessage = XmppAxolotlMessage.fromElement(encrypted, packet.getFrom().toBareJid());
314 }
315 Element fileSize = fileOffer.findChild("size");
316 Element fileNameElement = fileOffer.findChild("name");
317 if (fileNameElement != null) {
318 String[] filename = fileNameElement.getContent()
319 .toLowerCase(Locale.US).toLowerCase().split("\\.");
320 String extension = filename[filename.length - 1];
321 if (Arrays.asList(VALID_IMAGE_EXTENSIONS).contains(extension)) {
322 message.setType(Message.TYPE_IMAGE);
323 message.setRelativeFilePath(message.getUuid()+"."+extension);
324 } else if (Arrays.asList(VALID_CRYPTO_EXTENSIONS).contains(
325 filename[filename.length - 1])) {
326 if (filename.length == 3) {
327 extension = filename[filename.length - 2];
328 if (Arrays.asList(VALID_IMAGE_EXTENSIONS).contains(extension)) {
329 message.setType(Message.TYPE_IMAGE);
330 message.setRelativeFilePath(message.getUuid()+"."+extension);
331 } else {
332 message.setType(Message.TYPE_FILE);
333 }
334 if (filename[filename.length - 1].equals("otr")) {
335 message.setEncryption(Message.ENCRYPTION_OTR);
336 } else {
337 message.setEncryption(Message.ENCRYPTION_PGP);
338 }
339 }
340 } else {
341 message.setType(Message.TYPE_FILE);
342 }
343 if (message.getType() == Message.TYPE_FILE) {
344 String suffix = "";
345 if (!fileNameElement.getContent().isEmpty()) {
346 String parts[] = fileNameElement.getContent().split("/");
347 suffix = parts[parts.length - 1];
348 if (message.getEncryption() == Message.ENCRYPTION_OTR && suffix.endsWith(".otr")) {
349 suffix = suffix.substring(0,suffix.length() - 4);
350 } else if (message.getEncryption() == Message.ENCRYPTION_PGP && (suffix.endsWith(".pgp") || suffix.endsWith(".gpg"))) {
351 suffix = suffix.substring(0,suffix.length() - 4);
352 }
353 }
354 message.setRelativeFilePath(message.getUuid()+"_"+suffix);
355 }
356 long size = Long.parseLong(fileSize.getContent());
357 message.setBody(Long.toString(size));
358 conversation.add(message);
359 mXmppConnectionService.updateConversationUi();
360 if (size < this.mJingleConnectionManager.getAutoAcceptFileSize()) {
361 Log.d(Config.LOGTAG, "auto accepting file from "+ packet.getFrom());
362 this.acceptedAutomatically = true;
363 this.sendAccept();
364 } else {
365 message.markUnread();
366 Log.d(Config.LOGTAG,
367 "not auto accepting new file offer with size: "
368 + size
369 + " allowed size:"
370 + this.mJingleConnectionManager
371 .getAutoAcceptFileSize());
372 this.mXmppConnectionService.getNotificationService().push(message);
373 }
374 this.file = this.mXmppConnectionService.getFileBackend().getFile(message, false);
375 if (mXmppAxolotlMessage != null) {
376 XmppAxolotlMessage.XmppAxolotlKeyTransportMessage transportMessage = account.getAxolotlService().processReceivingKeyTransportMessage(mXmppAxolotlMessage);
377 if (transportMessage != null) {
378 message.setEncryption(Message.ENCRYPTION_AXOLOTL);
379 this.file.setKey(transportMessage.getKey());
380 this.file.setIv(transportMessage.getIv());
381 message.setAxolotlFingerprint(transportMessage.getFingerprint());
382 } else {
383 Log.d(Config.LOGTAG,"could not process KeyTransportMessage");
384 }
385 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
386 byte[] key = conversation.getSymmetricKey();
387 if (key == null) {
388 this.sendCancel();
389 this.fail();
390 return;
391 } else {
392 this.file.setKeyAndIv(key);
393 }
394 }
395 this.mFileOutputStream = AbstractConnectionManager.createOutputStream(this.file,message.getEncryption() == Message.ENCRYPTION_AXOLOTL);
396 if (message.getEncryption() == Message.ENCRYPTION_OTR && Config.REPORT_WRONG_FILESIZE_IN_OTR_JINGLE) {
397 this.file.setExpectedSize((size / 16 + 1) * 16);
398 } else {
399 this.file.setExpectedSize(size);
400 }
401 Log.d(Config.LOGTAG, "receiving file: expecting size of " + this.file.getExpectedSize());
402 } else {
403 this.sendCancel();
404 this.fail();
405 }
406 } else {
407 this.sendCancel();
408 this.fail();
409 }
410 }
411
412 private void sendInitRequest() {
413 JinglePacket packet = this.bootstrapPacket("session-initiate");
414 Content content = new Content(this.contentCreator, this.contentName);
415 if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
416 content.setTransportId(this.transportId);
417 this.file = this.mXmppConnectionService.getFileBackend().getFile(message, false);
418 Pair<InputStream,Integer> pair;
419 try {
420 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
421 Conversation conversation = this.message.getConversation();
422 if (!this.mXmppConnectionService.renewSymmetricKey(conversation)) {
423 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not set symmetric key");
424 cancel();
425 }
426 this.file.setKeyAndIv(conversation.getSymmetricKey());
427 pair = AbstractConnectionManager.createInputStream(this.file, false);
428 this.file.setExpectedSize(pair.second);
429 content.setFileOffer(this.file, true);
430 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
431 this.file.setKey(mXmppAxolotlMessage.getInnerKey());
432 this.file.setIv(mXmppAxolotlMessage.getIV());
433 pair = AbstractConnectionManager.createInputStream(this.file, true);
434 this.file.setExpectedSize(pair.second);
435 content.setFileOffer(this.file, false).addChild(mXmppAxolotlMessage.toElement());
436 } else {
437 pair = AbstractConnectionManager.createInputStream(this.file, false);
438 this.file.setExpectedSize(pair.second);
439 content.setFileOffer(this.file, false);
440 }
441 } catch (FileNotFoundException e) {
442 cancel();
443 return;
444 }
445 this.mFileInputStream = pair.first;
446 this.transportId = this.mJingleConnectionManager.nextRandomId();
447 content.setTransportId(this.transportId);
448 content.socks5transport().setChildren(getCandidatesAsElements());
449 packet.setContent(content);
450 this.sendJinglePacket(packet,new OnIqPacketReceived() {
451
452 @Override
453 public void onIqPacketReceived(Account account, IqPacket packet) {
454 if (packet.getType() == IqPacket.TYPE.RESULT) {
455 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": other party received offer");
456 mJingleStatus = JINGLE_STATUS_INITIATED;
457 mXmppConnectionService.markMessage(message, Message.STATUS_OFFERED);
458 } else {
459 fail();
460 }
461 }
462 });
463
464 }
465 }
466
467 private List<Element> getCandidatesAsElements() {
468 List<Element> elements = new ArrayList<>();
469 for (JingleCandidate c : this.candidates) {
470 if (c.isOurs()) {
471 elements.add(c.toElement());
472 }
473 }
474 return elements;
475 }
476
477 private void sendAccept() {
478 mJingleStatus = JINGLE_STATUS_ACCEPTED;
479 this.mStatus = Transferable.STATUS_DOWNLOADING;
480 mXmppConnectionService.updateConversationUi();
481 this.mJingleConnectionManager.getPrimaryCandidate(this.account, new OnPrimaryCandidateFound() {
482 @Override
483 public void onPrimaryCandidateFound(boolean success, final JingleCandidate candidate) {
484 final JinglePacket packet = bootstrapPacket("session-accept");
485 final Content content = new Content(contentCreator,contentName);
486 content.setFileOffer(fileOffer);
487 content.setTransportId(transportId);
488 if (success && candidate != null && !equalCandidateExists(candidate)) {
489 final JingleSocks5Transport socksConnection = new JingleSocks5Transport(
490 JingleConnection.this,
491 candidate);
492 connections.put(candidate.getCid(), socksConnection);
493 socksConnection.connect(new OnTransportConnected() {
494
495 @Override
496 public void failed() {
497 Log.d(Config.LOGTAG,"connection to our own primary candidate failed");
498 content.socks5transport().setChildren(getCandidatesAsElements());
499 packet.setContent(content);
500 sendJinglePacket(packet);
501 connectNextCandidate();
502 }
503
504 @Override
505 public void established() {
506 Log.d(Config.LOGTAG, "connected to primary candidate");
507 mergeCandidate(candidate);
508 content.socks5transport().setChildren(getCandidatesAsElements());
509 packet.setContent(content);
510 sendJinglePacket(packet);
511 connectNextCandidate();
512 }
513 });
514 } else {
515 Log.d(Config.LOGTAG,"did not find a primary candidate for ourself");
516 content.socks5transport().setChildren(getCandidatesAsElements());
517 packet.setContent(content);
518 sendJinglePacket(packet);
519 connectNextCandidate();
520 }
521 }
522 });
523 }
524
525 private JinglePacket bootstrapPacket(String action) {
526 JinglePacket packet = new JinglePacket();
527 packet.setAction(action);
528 packet.setFrom(account.getJid());
529 packet.setTo(this.message.getCounterpart());
530 packet.setSessionId(this.sessionId);
531 packet.setInitiator(this.initiator);
532 return packet;
533 }
534
535 private void sendJinglePacket(JinglePacket packet) {
536 mXmppConnectionService.sendIqPacket(account,packet,responseListener);
537 }
538
539 private void sendJinglePacket(JinglePacket packet, OnIqPacketReceived callback) {
540 mXmppConnectionService.sendIqPacket(account,packet,callback);
541 }
542
543 private boolean receiveAccept(JinglePacket packet) {
544 Content content = packet.getJingleContent();
545 mergeCandidates(JingleCandidate.parse(content.socks5transport()
546 .getChildren()));
547 this.mJingleStatus = JINGLE_STATUS_ACCEPTED;
548 mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
549 this.connectNextCandidate();
550 return true;
551 }
552
553 private boolean receiveTransportInfo(JinglePacket packet) {
554 Content content = packet.getJingleContent();
555 if (content.hasSocks5Transport()) {
556 if (content.socks5transport().hasChild("activated")) {
557 if ((this.transport != null) && (this.transport instanceof JingleSocks5Transport)) {
558 onProxyActivated.success();
559 } else {
560 String cid = content.socks5transport().findChild("activated").getAttribute("cid");
561 Log.d(Config.LOGTAG, "received proxy activated (" + cid
562 + ")prior to choosing our own transport");
563 JingleSocks5Transport connection = this.connections.get(cid);
564 if (connection != null) {
565 connection.setActivated(true);
566 } else {
567 Log.d(Config.LOGTAG, "activated connection not found");
568 this.sendCancel();
569 this.fail();
570 }
571 }
572 return true;
573 } else if (content.socks5transport().hasChild("proxy-error")) {
574 onProxyActivated.failed();
575 return true;
576 } else if (content.socks5transport().hasChild("candidate-error")) {
577 Log.d(Config.LOGTAG, "received candidate error");
578 this.receivedCandidate = true;
579 if ((mJingleStatus == JINGLE_STATUS_ACCEPTED)
580 && (this.sentCandidate)) {
581 this.connect();
582 }
583 return true;
584 } else if (content.socks5transport().hasChild("candidate-used")) {
585 String cid = content.socks5transport()
586 .findChild("candidate-used").getAttribute("cid");
587 if (cid != null) {
588 Log.d(Config.LOGTAG, "candidate used by counterpart:" + cid);
589 JingleCandidate candidate = getCandidate(cid);
590 candidate.flagAsUsedByCounterpart();
591 this.receivedCandidate = true;
592 if ((mJingleStatus == JINGLE_STATUS_ACCEPTED)
593 && (this.sentCandidate)) {
594 this.connect();
595 } else {
596 Log.d(Config.LOGTAG,
597 "ignoring because file is already in transmission or we havent sent our candidate yet");
598 }
599 return true;
600 } else {
601 return false;
602 }
603 } else {
604 return false;
605 }
606 } else {
607 return true;
608 }
609 }
610
611 private void connect() {
612 final JingleSocks5Transport connection = chooseConnection();
613 this.transport = connection;
614 if (connection == null) {
615 Log.d(Config.LOGTAG, "could not find suitable candidate");
616 this.disconnectSocks5Connections();
617 if (this.initiator.equals(account.getJid())) {
618 this.sendFallbackToIbb();
619 }
620 } else {
621 this.mJingleStatus = JINGLE_STATUS_TRANSMITTING;
622 if (connection.needsActivation()) {
623 if (connection.getCandidate().isOurs()) {
624 Log.d(Config.LOGTAG, "candidate "
625 + connection.getCandidate().getCid()
626 + " was our proxy. going to activate");
627 IqPacket activation = new IqPacket(IqPacket.TYPE.SET);
628 activation.setTo(connection.getCandidate().getJid());
629 activation.query("http://jabber.org/protocol/bytestreams")
630 .setAttribute("sid", this.getSessionId());
631 activation.query().addChild("activate")
632 .setContent(this.getCounterPart().toString());
633 mXmppConnectionService.sendIqPacket(account,activation,
634 new OnIqPacketReceived() {
635
636 @Override
637 public void onIqPacketReceived(Account account,
638 IqPacket packet) {
639 if (packet.getType() != IqPacket.TYPE.RESULT) {
640 onProxyActivated.failed();
641 } else {
642 onProxyActivated.success();
643 sendProxyActivated(connection.getCandidate().getCid());
644 }
645 }
646 });
647 } else {
648 Log.d(Config.LOGTAG,
649 "candidate "
650 + connection.getCandidate().getCid()
651 + " was a proxy. waiting for other party to activate");
652 }
653 } else {
654 if (initiator.equals(account.getJid())) {
655 Log.d(Config.LOGTAG, "we were initiating. sending file");
656 connection.send(file, onFileTransmissionSatusChanged);
657 } else {
658 Log.d(Config.LOGTAG, "we were responding. receiving file");
659 connection.receive(file, onFileTransmissionSatusChanged);
660 }
661 }
662 }
663 }
664
665 private JingleSocks5Transport chooseConnection() {
666 JingleSocks5Transport connection = null;
667 for (Entry<String, JingleSocks5Transport> cursor : connections
668 .entrySet()) {
669 JingleSocks5Transport currentConnection = cursor.getValue();
670 // Log.d(Config.LOGTAG,"comparing candidate: "+currentConnection.getCandidate().toString());
671 if (currentConnection.isEstablished()
672 && (currentConnection.getCandidate().isUsedByCounterpart() || (!currentConnection
673 .getCandidate().isOurs()))) {
674 // Log.d(Config.LOGTAG,"is usable");
675 if (connection == null) {
676 connection = currentConnection;
677 } else {
678 if (connection.getCandidate().getPriority() < currentConnection
679 .getCandidate().getPriority()) {
680 connection = currentConnection;
681 } else if (connection.getCandidate().getPriority() == currentConnection
682 .getCandidate().getPriority()) {
683 // Log.d(Config.LOGTAG,"found two candidates with same priority");
684 if (initiator.equals(account.getJid())) {
685 if (currentConnection.getCandidate().isOurs()) {
686 connection = currentConnection;
687 }
688 } else {
689 if (!currentConnection.getCandidate().isOurs()) {
690 connection = currentConnection;
691 }
692 }
693 }
694 }
695 }
696 }
697 return connection;
698 }
699
700 private void sendSuccess() {
701 JinglePacket packet = bootstrapPacket("session-terminate");
702 Reason reason = new Reason();
703 reason.addChild("success");
704 packet.setReason(reason);
705 this.sendJinglePacket(packet);
706 this.disconnectSocks5Connections();
707 this.mJingleStatus = JINGLE_STATUS_FINISHED;
708 this.message.setStatus(Message.STATUS_RECEIVED);
709 this.message.setTransferable(null);
710 this.mXmppConnectionService.updateMessage(message);
711 this.mJingleConnectionManager.finishConnection(this);
712 }
713
714 private void sendFallbackToIbb() {
715 Log.d(Config.LOGTAG, "sending fallback to ibb");
716 JinglePacket packet = this.bootstrapPacket("transport-replace");
717 Content content = new Content(this.contentCreator, this.contentName);
718 this.transportId = this.mJingleConnectionManager.nextRandomId();
719 content.setTransportId(this.transportId);
720 content.ibbTransport().setAttribute("block-size",
721 Integer.toString(this.ibbBlockSize));
722 packet.setContent(content);
723 this.sendJinglePacket(packet);
724 }
725
726 private boolean receiveFallbackToIbb(JinglePacket packet) {
727 Log.d(Config.LOGTAG, "receiving fallack to ibb");
728 String receivedBlockSize = packet.getJingleContent().ibbTransport()
729 .getAttribute("block-size");
730 if (receivedBlockSize != null) {
731 int bs = Integer.parseInt(receivedBlockSize);
732 if (bs > this.ibbBlockSize) {
733 this.ibbBlockSize = bs;
734 }
735 }
736 this.transportId = packet.getJingleContent().getTransportId();
737 this.transport = new JingleInbandTransport(this, this.transportId, this.ibbBlockSize);
738 this.transport.receive(file, onFileTransmissionSatusChanged);
739 JinglePacket answer = bootstrapPacket("transport-accept");
740 Content content = new Content("initiator", "a-file-offer");
741 content.setTransportId(this.transportId);
742 content.ibbTransport().setAttribute("block-size",this.ibbBlockSize);
743 answer.setContent(content);
744 this.sendJinglePacket(answer);
745 return true;
746 }
747
748 private boolean receiveTransportAccept(JinglePacket packet) {
749 if (packet.getJingleContent().hasIbbTransport()) {
750 String receivedBlockSize = packet.getJingleContent().ibbTransport()
751 .getAttribute("block-size");
752 if (receivedBlockSize != null) {
753 int bs = Integer.parseInt(receivedBlockSize);
754 if (bs > this.ibbBlockSize) {
755 this.ibbBlockSize = bs;
756 }
757 }
758 this.transport = new JingleInbandTransport(this, this.transportId, this.ibbBlockSize);
759 this.transport.connect(new OnTransportConnected() {
760
761 @Override
762 public void failed() {
763 Log.d(Config.LOGTAG, "ibb open failed");
764 }
765
766 @Override
767 public void established() {
768 JingleConnection.this.transport.send(file,
769 onFileTransmissionSatusChanged);
770 }
771 });
772 return true;
773 } else {
774 return false;
775 }
776 }
777
778 private void receiveSuccess() {
779 this.mJingleStatus = JINGLE_STATUS_FINISHED;
780 this.mXmppConnectionService.markMessage(this.message,Message.STATUS_SEND_RECEIVED);
781 this.disconnectSocks5Connections();
782 if (this.transport != null && this.transport instanceof JingleInbandTransport) {
783 this.transport.disconnect();
784 }
785 this.message.setTransferable(null);
786 this.mJingleConnectionManager.finishConnection(this);
787 }
788
789 public void cancel() {
790 this.disconnectSocks5Connections();
791 if (this.transport != null && this.transport instanceof JingleInbandTransport) {
792 this.transport.disconnect();
793 }
794 this.sendCancel();
795 this.mJingleConnectionManager.finishConnection(this);
796 if (this.responder.equals(account.getJid())) {
797 this.message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_FAILED));
798 if (this.file!=null) {
799 file.delete();
800 }
801 this.mXmppConnectionService.updateConversationUi();
802 } else {
803 this.mXmppConnectionService.markMessage(this.message,
804 Message.STATUS_SEND_FAILED);
805 this.message.setTransferable(null);
806 }
807 }
808
809 private void fail() {
810 this.mJingleStatus = JINGLE_STATUS_FAILED;
811 this.disconnectSocks5Connections();
812 if (this.transport != null && this.transport instanceof JingleInbandTransport) {
813 this.transport.disconnect();
814 }
815 FileBackend.close(mFileInputStream);
816 FileBackend.close(mFileOutputStream);
817 if (this.message != null) {
818 if (this.responder.equals(account.getJid())) {
819 this.message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_FAILED));
820 if (this.file!=null) {
821 file.delete();
822 }
823 this.mXmppConnectionService.updateConversationUi();
824 } else {
825 this.mXmppConnectionService.markMessage(this.message,
826 Message.STATUS_SEND_FAILED);
827 this.message.setTransferable(null);
828 }
829 }
830 this.mJingleConnectionManager.finishConnection(this);
831 }
832
833 private void sendCancel() {
834 JinglePacket packet = bootstrapPacket("session-terminate");
835 Reason reason = new Reason();
836 reason.addChild("cancel");
837 packet.setReason(reason);
838 this.sendJinglePacket(packet);
839 }
840
841 private void connectNextCandidate() {
842 for (JingleCandidate candidate : this.candidates) {
843 if ((!connections.containsKey(candidate.getCid()) && (!candidate
844 .isOurs()))) {
845 this.connectWithCandidate(candidate);
846 return;
847 }
848 }
849 this.sendCandidateError();
850 }
851
852 private void connectWithCandidate(final JingleCandidate candidate) {
853 final JingleSocks5Transport socksConnection = new JingleSocks5Transport(
854 this, candidate);
855 connections.put(candidate.getCid(), socksConnection);
856 socksConnection.connect(new OnTransportConnected() {
857
858 @Override
859 public void failed() {
860 Log.d(Config.LOGTAG,
861 "connection failed with " + candidate.getHost() + ":"
862 + candidate.getPort());
863 connectNextCandidate();
864 }
865
866 @Override
867 public void established() {
868 Log.d(Config.LOGTAG,
869 "established connection with " + candidate.getHost()
870 + ":" + candidate.getPort());
871 sendCandidateUsed(candidate.getCid());
872 }
873 });
874 }
875
876 private void disconnectSocks5Connections() {
877 Iterator<Entry<String, JingleSocks5Transport>> it = this.connections
878 .entrySet().iterator();
879 while (it.hasNext()) {
880 Entry<String, JingleSocks5Transport> pairs = it.next();
881 pairs.getValue().disconnect();
882 it.remove();
883 }
884 }
885
886 private void sendProxyActivated(String cid) {
887 JinglePacket packet = bootstrapPacket("transport-info");
888 Content content = new Content(this.contentCreator, this.contentName);
889 content.setTransportId(this.transportId);
890 content.socks5transport().addChild("activated")
891 .setAttribute("cid", cid);
892 packet.setContent(content);
893 this.sendJinglePacket(packet);
894 }
895
896 private void sendCandidateUsed(final String cid) {
897 JinglePacket packet = bootstrapPacket("transport-info");
898 Content content = new Content(this.contentCreator, this.contentName);
899 content.setTransportId(this.transportId);
900 content.socks5transport().addChild("candidate-used")
901 .setAttribute("cid", cid);
902 packet.setContent(content);
903 this.sentCandidate = true;
904 if ((receivedCandidate) && (mJingleStatus == JINGLE_STATUS_ACCEPTED)) {
905 connect();
906 }
907 this.sendJinglePacket(packet);
908 }
909
910 private void sendCandidateError() {
911 JinglePacket packet = bootstrapPacket("transport-info");
912 Content content = new Content(this.contentCreator, this.contentName);
913 content.setTransportId(this.transportId);
914 content.socks5transport().addChild("candidate-error");
915 packet.setContent(content);
916 this.sentCandidate = true;
917 if ((receivedCandidate) && (mJingleStatus == JINGLE_STATUS_ACCEPTED)) {
918 connect();
919 }
920 this.sendJinglePacket(packet);
921 }
922
923 public Jid getInitiator() {
924 return this.initiator;
925 }
926
927 public Jid getResponder() {
928 return this.responder;
929 }
930
931 public int getJingleStatus() {
932 return this.mJingleStatus;
933 }
934
935 private boolean equalCandidateExists(JingleCandidate candidate) {
936 for (JingleCandidate c : this.candidates) {
937 if (c.equalValues(candidate)) {
938 return true;
939 }
940 }
941 return false;
942 }
943
944 private void mergeCandidate(JingleCandidate candidate) {
945 for (JingleCandidate c : this.candidates) {
946 if (c.equals(candidate)) {
947 return;
948 }
949 }
950 this.candidates.add(candidate);
951 }
952
953 private void mergeCandidates(List<JingleCandidate> candidates) {
954 for (JingleCandidate c : candidates) {
955 mergeCandidate(c);
956 }
957 }
958
959 private JingleCandidate getCandidate(String cid) {
960 for (JingleCandidate c : this.candidates) {
961 if (c.getCid().equals(cid)) {
962 return c;
963 }
964 }
965 return null;
966 }
967
968 public void updateProgress(int i) {
969 this.mProgress = i;
970 mXmppConnectionService.updateConversationUi();
971 }
972
973 interface OnProxyActivated {
974 public void success();
975
976 public void failed();
977 }
978
979 public boolean hasTransportId(String sid) {
980 return sid.equals(this.transportId);
981 }
982
983 public JingleTransport getTransport() {
984 return this.transport;
985 }
986
987 public boolean start() {
988 if (account.getStatus() == Account.State.ONLINE) {
989 if (mJingleStatus == JINGLE_STATUS_INITIATED) {
990 new Thread(new Runnable() {
991
992 @Override
993 public void run() {
994 sendAccept();
995 }
996 }).start();
997 }
998 return true;
999 } else {
1000 return false;
1001 }
1002 }
1003
1004 @Override
1005 public int getStatus() {
1006 return this.mStatus;
1007 }
1008
1009 @Override
1010 public long getFileSize() {
1011 if (this.file != null) {
1012 return this.file.getExpectedSize();
1013 } else {
1014 return 0;
1015 }
1016 }
1017
1018 @Override
1019 public int getProgress() {
1020 return this.mProgress;
1021 }
1022
1023 public AbstractConnectionManager getConnectionManager() {
1024 return this.mJingleConnectionManager;
1025 }
1026}