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