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