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