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