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