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.contentName);
598 content.setSenders(this.contentSenders);
599 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL && remoteSupportsOmemoJet) {
600 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": remote announced support for JET");
601 final Element security = new Element("security", Namespace.JINGLE_ENCRYPTED_TRANSPORT);
602 security.setAttribute("name", this.contentName);
603 security.setAttribute("cipher", JET_OMEMO_CIPHER);
604 security.setAttribute("type", AxolotlService.PEP_PREFIX);
605 security.addChild(mXmppAxolotlMessage.toElement());
606 content.addChild(security);
607 }
608 content.setDescription(this.description);
609 try {
610 this.mFileInputStream = new FileInputStream(file);
611 } catch (FileNotFoundException e) {
612 fail(e.getMessage());
613 return;
614 }
615 if (this.initialTransport == IbbTransportInfo.class) {
616 content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
617 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": sending IBB offer");
618 } else {
619 final Collection<JingleCandidate> candidates = getOurCandidates();
620 content.setTransport(new S5BTransportInfo(this.transportId, candidates));
621 Log.d(Config.LOGTAG, String.format("%s: sending S5B offer with %d candidates", id.account.getJid().asBareJid(), candidates.size()));
622 }
623 packet.addJingleContent(content);
624 this.sendJinglePacket(packet, (account, response) -> {
625 if (response.getType() == IqPacket.TYPE.RESULT) {
626 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": other party received offer");
627 if (mJingleStatus == JINGLE_STATUS_OFFERED) {
628 mJingleStatus = JINGLE_STATUS_INITIATED;
629 xmppConnectionService.markMessage(message, Message.STATUS_OFFERED);
630 } else {
631 Log.d(Config.LOGTAG, "received ack for offer when status was " + mJingleStatus);
632 }
633 } else {
634 fail(IqParser.extractErrorMessage(response));
635 }
636 });
637
638 }
639
640 private void sendHash() {
641 final Element checksum = new Element("checksum", description.getVersion().getNamespace());
642 checksum.setAttribute("creator", "initiator");
643 checksum.setAttribute("name", "a-file-offer");
644 Element hash = checksum.addChild("file").addChild("hash", "urn:xmpp:hashes:2");
645 hash.setAttribute("algo", "sha-1").setContent(Base64.encodeToString(file.getSha1Sum(), Base64.NO_WRAP));
646
647 final JinglePacket packet = this.bootstrapPacket(JinglePacket.Action.SESSION_INFO);
648 packet.addJingleChild(checksum);
649 xmppConnectionService.sendIqPacket(id.account, packet, (account, response) -> {
650 if (response.getType() == IqPacket.TYPE.ERROR) {
651 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignoring error response to our session-info (hash transmission)");
652 }
653 });
654 }
655
656 private Collection<JingleCandidate> getOurCandidates() {
657 return Collections2.filter(this.candidates, c -> c != null && c.isOurs());
658 }
659
660 private void sendAccept() {
661 mJingleStatus = JINGLE_STATUS_ACCEPTED;
662 this.mStatus = Transferable.STATUS_DOWNLOADING;
663 this.jingleConnectionManager.updateConversationUi(true);
664 if (initialTransport == S5BTransportInfo.class) {
665 sendAcceptSocks();
666 } else {
667 sendAcceptIbb();
668 }
669 }
670
671 private void sendAcceptSocks() {
672 gatherAndConnectDirectCandidates();
673 this.jingleConnectionManager.getPrimaryCandidate(this.id.account, isInitiator(), (success, candidate) -> {
674 final JinglePacket packet = bootstrapPacket(JinglePacket.Action.SESSION_ACCEPT);
675 final Content content = new Content(contentCreator, contentName);
676 content.setSenders(this.contentSenders);
677 content.setDescription(this.description);
678 if (success && candidate != null && !equalCandidateExists(candidate)) {
679 final JingleSocks5Transport socksConnection = new JingleSocks5Transport(this, candidate);
680 connections.put(candidate.getCid(), socksConnection);
681 socksConnection.connect(new OnTransportConnected() {
682
683 @Override
684 public void failed() {
685 Log.d(Config.LOGTAG, "connection to our own proxy65 candidate failed");
686 content.setTransport(new S5BTransportInfo(transportId, getOurCandidates()));
687 packet.addJingleContent(content);
688 sendJinglePacket(packet);
689 connectNextCandidate();
690 }
691
692 @Override
693 public void established() {
694 Log.d(Config.LOGTAG, "connected to proxy65 candidate");
695 mergeCandidate(candidate);
696 content.setTransport(new S5BTransportInfo(transportId, getOurCandidates()));
697 packet.addJingleContent(content);
698 sendJinglePacket(packet);
699 connectNextCandidate();
700 }
701 });
702 } else {
703 Log.d(Config.LOGTAG, "did not find a proxy65 candidate for ourselves");
704 content.setTransport(new S5BTransportInfo(transportId, getOurCandidates()));
705 packet.addJingleContent(content);
706 sendJinglePacket(packet);
707 connectNextCandidate();
708 }
709 });
710 }
711
712 private void sendAcceptIbb() {
713 this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
714 final JinglePacket packet = bootstrapPacket(JinglePacket.Action.SESSION_ACCEPT);
715 final Content content = new Content(contentCreator, contentName);
716 content.setSenders(this.contentSenders);
717 content.setDescription(this.description);
718 content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
719 packet.addJingleContent(content);
720 this.transport.receive(file, onFileTransmissionStatusChanged);
721 this.sendJinglePacket(packet);
722 }
723
724 private JinglePacket bootstrapPacket(JinglePacket.Action action) {
725 final JinglePacket packet = new JinglePacket(action, this.id.sessionId);
726 packet.setTo(id.with);
727 return packet;
728 }
729
730 private void sendJinglePacket(JinglePacket packet) {
731 xmppConnectionService.sendIqPacket(id.account, packet, responseListener);
732 }
733
734 private void sendJinglePacket(JinglePacket packet, OnIqPacketReceived callback) {
735 xmppConnectionService.sendIqPacket(id.account, packet, callback);
736 }
737
738 private void receiveAccept(JinglePacket packet) {
739 if (responding()) {
740 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order session-accept (we were responding)");
741 respondToIqWithOutOfOrder(packet);
742 return;
743 }
744 if (this.mJingleStatus != JINGLE_STATUS_INITIATED) {
745 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order session-accept");
746 respondToIqWithOutOfOrder(packet);
747 return;
748 }
749 this.mJingleStatus = JINGLE_STATUS_ACCEPTED;
750 xmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
751 final Content content = packet.getJingleContent();
752 final GenericTransportInfo transportInfo = content.getTransport();
753 //TODO we want to fail if transportInfo doesn’t match our intialTransport and/or our id
754 if (transportInfo instanceof S5BTransportInfo) {
755 final S5BTransportInfo s5BTransportInfo = (S5BTransportInfo) transportInfo;
756 respondToIq(packet, true);
757 //TODO calling merge is probably a bug because that might eliminate candidates of the other party and lead to us not sending accept/deny
758 //TODO: we probably just want to call add
759 mergeCandidates(s5BTransportInfo.getCandidates());
760 this.connectNextCandidate();
761 } else if (transportInfo instanceof IbbTransportInfo) {
762 final IbbTransportInfo ibbTransportInfo = (IbbTransportInfo) transportInfo;
763 final int remoteBlockSize = ibbTransportInfo.getBlockSize();
764 if (remoteBlockSize > 0) {
765 this.ibbBlockSize = Math.min(ibbBlockSize, remoteBlockSize);
766 }
767 respondToIq(packet, true);
768 this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
769 this.transport.connect(onIbbTransportConnected);
770 } else {
771 respondToIq(packet, false);
772 }
773 }
774
775 private void receiveTransportInfo(JinglePacket packet) {
776 final Content content = packet.getJingleContent();
777 final GenericTransportInfo transportInfo = content.getTransport();
778 if (transportInfo instanceof S5BTransportInfo) {
779 final S5BTransportInfo s5BTransportInfo = (S5BTransportInfo) transportInfo;
780 if (s5BTransportInfo.hasChild("activated")) {
781 respondToIq(packet, true);
782 if ((this.transport != null) && (this.transport instanceof JingleSocks5Transport)) {
783 onProxyActivated.success();
784 } else {
785 String cid = s5BTransportInfo.findChild("activated").getAttribute("cid");
786 Log.d(Config.LOGTAG, "received proxy activated (" + cid
787 + ")prior to choosing our own transport");
788 JingleSocks5Transport connection = this.connections.get(cid);
789 if (connection != null) {
790 connection.setActivated(true);
791 } else {
792 Log.d(Config.LOGTAG, "activated connection not found");
793 sendSessionTerminate(Reason.FAILED_TRANSPORT);
794 this.fail();
795 }
796 }
797 } else if (s5BTransportInfo.hasChild("proxy-error")) {
798 respondToIq(packet, true);
799 onProxyActivated.failed();
800 } else if (s5BTransportInfo.hasChild("candidate-error")) {
801 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received candidate error");
802 respondToIq(packet, true);
803 this.receivedCandidate = true;
804 if (mJingleStatus == JINGLE_STATUS_ACCEPTED && this.sentCandidate) {
805 this.connect();
806 }
807 } else if (s5BTransportInfo.hasChild("candidate-used")) {
808 String cid = s5BTransportInfo.findChild("candidate-used").getAttribute("cid");
809 if (cid != null) {
810 Log.d(Config.LOGTAG, "candidate used by counterpart:" + cid);
811 JingleCandidate candidate = getCandidate(cid);
812 if (candidate == null) {
813 Log.d(Config.LOGTAG, "could not find candidate with cid=" + cid);
814 respondToIq(packet, false);
815 return;
816 }
817 respondToIq(packet, true);
818 candidate.flagAsUsedByCounterpart();
819 this.receivedCandidate = true;
820 if (mJingleStatus == JINGLE_STATUS_ACCEPTED && this.sentCandidate) {
821 this.connect();
822 } else {
823 Log.d(Config.LOGTAG, "ignoring because file is already in transmission or we haven't sent our candidate yet status=" + mJingleStatus + " sentCandidate=" + sentCandidate);
824 }
825 } else {
826 respondToIq(packet, false);
827 }
828 } else {
829 respondToIq(packet, false);
830 }
831 } else {
832 respondToIq(packet, true);
833 }
834 }
835
836 private void connect() {
837 final JingleSocks5Transport connection = chooseConnection();
838 this.transport = connection;
839 if (connection == null) {
840 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": could not find suitable candidate");
841 this.disconnectSocks5Connections();
842 if (isInitiator()) {
843 this.sendFallbackToIbb();
844 }
845 } else {
846 //TODO at this point we can already close other connections to free some resources
847 final JingleCandidate candidate = connection.getCandidate();
848 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": elected candidate " + candidate.toString());
849 this.mJingleStatus = JINGLE_STATUS_TRANSMITTING;
850 if (connection.needsActivation()) {
851 if (connection.getCandidate().isOurs()) {
852 final String sid;
853 if (description.getVersion() == FileTransferDescription.Version.FT_3) {
854 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": use session ID instead of transport ID to activate proxy");
855 sid = id.sessionId;
856 } else {
857 sid = getTransportId();
858 }
859 Log.d(Config.LOGTAG, "candidate "
860 + connection.getCandidate().getCid()
861 + " was our proxy. going to activate");
862 IqPacket activation = new IqPacket(IqPacket.TYPE.SET);
863 activation.setTo(connection.getCandidate().getJid());
864 activation.query("http://jabber.org/protocol/bytestreams")
865 .setAttribute("sid", sid);
866 activation.query().addChild("activate")
867 .setContent(this.id.with.toEscapedString());
868 xmppConnectionService.sendIqPacket(this.id.account, activation, (account, response) -> {
869 if (response.getType() != IqPacket.TYPE.RESULT) {
870 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": " + response.toString());
871 sendProxyError();
872 onProxyActivated.failed();
873 } else {
874 sendProxyActivated(connection.getCandidate().getCid());
875 onProxyActivated.success();
876 }
877 });
878 } else {
879 Log.d(Config.LOGTAG,
880 "candidate "
881 + connection.getCandidate().getCid()
882 + " was a proxy. waiting for other party to activate");
883 }
884 } else {
885 if (isInitiator()) {
886 Log.d(Config.LOGTAG, "we were initiating. sending file");
887 connection.send(file, onFileTransmissionStatusChanged);
888 } else {
889 Log.d(Config.LOGTAG, "we were responding. receiving file");
890 connection.receive(file, onFileTransmissionStatusChanged);
891 }
892 }
893 }
894 }
895
896 private JingleSocks5Transport chooseConnection() {
897 final List<JingleSocks5Transport> establishedConnections = FluentIterable.from(connections.entrySet())
898 .transform(Entry::getValue)
899 .filter(c -> (c != null && c.isEstablished() && (c.getCandidate().isUsedByCounterpart() || !c.getCandidate().isOurs())))
900 .toSortedList((a, b) -> {
901 final int compare = Integer.compare(b.getCandidate().getPriority(), a.getCandidate().getPriority());
902 if (compare == 0) {
903 if (isInitiator()) {
904 //pick the one we sent a candidate-used for (meaning not ours)
905 return a.getCandidate().isOurs() ? 1 : -1;
906 } else {
907 //pick the one they sent a candidate-used for (meaning ours)
908 return a.getCandidate().isOurs() ? -1 : 1;
909 }
910 }
911 return compare;
912 });
913 return Iterables.getFirst(establishedConnections, null);
914 }
915
916 private void sendSuccess() {
917 sendSessionTerminate(Reason.SUCCESS);
918 this.disconnectSocks5Connections();
919 this.mJingleStatus = JINGLE_STATUS_FINISHED;
920 this.message.setStatus(Message.STATUS_RECEIVED);
921 this.message.setTransferable(null);
922 this.xmppConnectionService.updateMessage(message, false);
923 this.jingleConnectionManager.finishConnection(this);
924 }
925
926 private void sendFallbackToIbb() {
927 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": sending fallback to ibb");
928 final JinglePacket packet = this.bootstrapPacket(JinglePacket.Action.TRANSPORT_REPLACE);
929 final Content content = new Content(this.contentCreator, this.contentName);
930 content.setSenders(this.contentSenders);
931 this.transportId = JingleConnectionManager.nextRandomId();
932 content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
933 packet.addJingleContent(content);
934 this.sendJinglePacket(packet);
935 }
936
937
938 private void receiveFallbackToIbb(final JinglePacket packet, final IbbTransportInfo transportInfo) {
939 if (isInitiator()) {
940 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-replace (we were initiating)");
941 respondToIqWithOutOfOrder(packet);
942 return;
943 }
944 final boolean validState = mJingleStatus == JINGLE_STATUS_ACCEPTED || (proxyActivationFailed && mJingleStatus == JINGLE_STATUS_TRANSMITTING);
945 if (!validState) {
946 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-replace");
947 respondToIqWithOutOfOrder(packet);
948 return;
949 }
950 this.proxyActivationFailed = false; //fallback received; now we no longer need to accept another one;
951 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receiving fallback to ibb");
952 final int remoteBlockSize = transportInfo.getBlockSize();
953 if (remoteBlockSize > 0) {
954 this.ibbBlockSize = Math.min(MAX_IBB_BLOCK_SIZE, remoteBlockSize);
955 } else {
956 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to parse block size in transport-replace");
957 }
958 this.transportId = transportInfo.getTransportId(); //TODO: handle the case where this is null by the remote party
959 this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
960
961 final JinglePacket answer = bootstrapPacket(JinglePacket.Action.TRANSPORT_ACCEPT);
962
963 final Content content = new Content(contentCreator, contentName);
964 content.setSenders(this.contentSenders);
965 content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
966 answer.addJingleContent(content);
967
968 respondToIq(packet, true);
969
970 if (isInitiator()) {
971 this.sendJinglePacket(answer, (account, response) -> {
972 if (response.getType() == IqPacket.TYPE.RESULT) {
973 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + " recipient ACKed our transport-accept. creating ibb");
974 transport.connect(onIbbTransportConnected);
975 }
976 });
977 } else {
978 this.transport.receive(file, onFileTransmissionStatusChanged);
979 this.sendJinglePacket(answer);
980 }
981 }
982
983 private void receiveTransportAccept(JinglePacket packet) {
984 if (responding()) {
985 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-accept (we were responding)");
986 respondToIqWithOutOfOrder(packet);
987 return;
988 }
989 final boolean validState = mJingleStatus == JINGLE_STATUS_ACCEPTED || (proxyActivationFailed && mJingleStatus == JINGLE_STATUS_TRANSMITTING);
990 if (!validState) {
991 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-accept");
992 respondToIqWithOutOfOrder(packet);
993 return;
994 }
995 this.proxyActivationFailed = false; //fallback accepted; now we no longer need to accept another one;
996 final Content content = packet.getJingleContent();
997 final GenericTransportInfo transportInfo = content == null ? null : content.getTransport();
998 if (transportInfo instanceof IbbTransportInfo) {
999 final IbbTransportInfo ibbTransportInfo = (IbbTransportInfo) transportInfo;
1000 final int remoteBlockSize = ibbTransportInfo.getBlockSize();
1001 if (remoteBlockSize > 0) {
1002 this.ibbBlockSize = Math.min(MAX_IBB_BLOCK_SIZE, remoteBlockSize);
1003 }
1004 final String sid = ibbTransportInfo.getTransportId();
1005 this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
1006
1007 if (sid == null || !sid.equals(this.transportId)) {
1008 Log.w(Config.LOGTAG, String.format("%s: sid in transport-accept (%s) did not match our sid (%s) ", id.account.getJid().asBareJid(), sid, transportId));
1009 }
1010 respondToIq(packet, true);
1011 //might be receive instead if we are not initiating
1012 if (isInitiator()) {
1013 this.transport.connect(onIbbTransportConnected);
1014 }
1015 } else {
1016 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received invalid transport-accept");
1017 respondToIq(packet, false);
1018 }
1019 }
1020
1021 private void receiveSuccess() {
1022 if (isInitiator()) {
1023 this.mJingleStatus = JINGLE_STATUS_FINISHED;
1024 this.xmppConnectionService.markMessage(this.message, Message.STATUS_SEND_RECEIVED);
1025 this.disconnectSocks5Connections();
1026 if (this.transport instanceof JingleInBandTransport) {
1027 this.transport.disconnect();
1028 }
1029 this.message.setTransferable(null);
1030 this.jingleConnectionManager.finishConnection(this);
1031 } else {
1032 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session-terminate/success while responding");
1033 }
1034 }
1035
1036 @Override
1037 public void cancel() {
1038 this.cancelled = true;
1039 abort(Reason.CANCEL);
1040 }
1041
1042 private void abort(final Reason reason) {
1043 this.disconnectSocks5Connections();
1044 if (this.transport instanceof JingleInBandTransport) {
1045 this.transport.disconnect();
1046 }
1047 sendSessionTerminate(reason);
1048 this.jingleConnectionManager.finishConnection(this);
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, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : null);
1057 this.message.setTransferable(null);
1058 }
1059 }
1060
1061 private void fail() {
1062 fail(null);
1063 }
1064
1065 private void fail(String errorMessage) {
1066 this.mJingleStatus = JINGLE_STATUS_FAILED;
1067 this.disconnectSocks5Connections();
1068 if (this.transport instanceof JingleInBandTransport) {
1069 this.transport.disconnect();
1070 }
1071 FileBackend.close(mFileInputStream);
1072 FileBackend.close(mFileOutputStream);
1073 if (this.message != null) {
1074 if (responding()) {
1075 this.message.setTransferable(new TransferablePlaceholder(cancelled ? Transferable.STATUS_CANCELLED : Transferable.STATUS_FAILED));
1076 if (this.file != null) {
1077 file.delete();
1078 }
1079 this.jingleConnectionManager.updateConversationUi(true);
1080 } else {
1081 this.xmppConnectionService.markMessage(this.message,
1082 Message.STATUS_SEND_FAILED,
1083 cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage);
1084 this.message.setTransferable(null);
1085 }
1086 }
1087 this.jingleConnectionManager.finishConnection(this);
1088 }
1089
1090 private void sendSessionTerminate(Reason reason) {
1091 final JinglePacket packet = bootstrapPacket(JinglePacket.Action.SESSION_TERMINATE);
1092 packet.setReason(reason, null);
1093 this.sendJinglePacket(packet);
1094 }
1095
1096 private void connectNextCandidate() {
1097 for (JingleCandidate candidate : this.candidates) {
1098 if ((!connections.containsKey(candidate.getCid()) && (!candidate
1099 .isOurs()))) {
1100 this.connectWithCandidate(candidate);
1101 return;
1102 }
1103 }
1104 this.sendCandidateError();
1105 }
1106
1107 private void connectWithCandidate(final JingleCandidate candidate) {
1108 final JingleSocks5Transport socksConnection = new JingleSocks5Transport(
1109 this, candidate);
1110 connections.put(candidate.getCid(), socksConnection);
1111 socksConnection.connect(new OnTransportConnected() {
1112
1113 @Override
1114 public void failed() {
1115 Log.d(Config.LOGTAG,
1116 "connection failed with " + candidate.getHost() + ":"
1117 + candidate.getPort());
1118 connectNextCandidate();
1119 }
1120
1121 @Override
1122 public void established() {
1123 Log.d(Config.LOGTAG,
1124 "established connection with " + candidate.getHost()
1125 + ":" + candidate.getPort());
1126 sendCandidateUsed(candidate.getCid());
1127 }
1128 });
1129 }
1130
1131 private void disconnectSocks5Connections() {
1132 Iterator<Entry<String, JingleSocks5Transport>> it = this.connections
1133 .entrySet().iterator();
1134 while (it.hasNext()) {
1135 Entry<String, JingleSocks5Transport> pairs = it.next();
1136 pairs.getValue().disconnect();
1137 it.remove();
1138 }
1139 }
1140
1141 private void sendProxyActivated(String cid) {
1142 final JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1143 final Content content = new Content(this.contentCreator, this.contentName);
1144 content.setSenders(this.contentSenders);
1145 content.setTransport(new S5BTransportInfo(this.transportId, new Element("activated").setAttribute("cid", cid)));
1146 packet.addJingleContent(content);
1147 this.sendJinglePacket(packet);
1148 }
1149
1150 private void sendProxyError() {
1151 final JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1152 final Content content = new Content(this.contentCreator, this.contentName);
1153 content.setSenders(this.contentSenders);
1154 content.setTransport(new S5BTransportInfo(this.transportId, new Element("proxy-error")));
1155 packet.addJingleContent(content);
1156 this.sendJinglePacket(packet);
1157 }
1158
1159 private void sendCandidateUsed(final String cid) {
1160 JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1161 final Content content = new Content(this.contentCreator, this.contentName);
1162 content.setSenders(this.contentSenders);
1163 content.setTransport(new S5BTransportInfo(this.transportId, new Element("candidate-used").setAttribute("cid", cid)));
1164 packet.addJingleContent(content);
1165 this.sentCandidate = true;
1166 if ((receivedCandidate) && (mJingleStatus == JINGLE_STATUS_ACCEPTED)) {
1167 connect();
1168 }
1169 this.sendJinglePacket(packet);
1170 }
1171
1172 private void sendCandidateError() {
1173 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": sending candidate error");
1174 JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1175 Content content = new Content(this.contentCreator, this.contentName);
1176 content.setSenders(this.contentSenders);
1177 content.setTransport(new S5BTransportInfo(this.transportId, new Element("candidate-error")));
1178 packet.addJingleContent(content);
1179 this.sentCandidate = true;
1180 this.sendJinglePacket(packet);
1181 if (receivedCandidate && mJingleStatus == JINGLE_STATUS_ACCEPTED) {
1182 connect();
1183 }
1184 }
1185
1186 private int getJingleStatus() {
1187 return this.mJingleStatus;
1188 }
1189
1190 private boolean equalCandidateExists(JingleCandidate candidate) {
1191 for (JingleCandidate c : this.candidates) {
1192 if (c.equalValues(candidate)) {
1193 return true;
1194 }
1195 }
1196 return false;
1197 }
1198
1199 private void mergeCandidate(JingleCandidate candidate) {
1200 for (JingleCandidate c : this.candidates) {
1201 if (c.equals(candidate)) {
1202 return;
1203 }
1204 }
1205 this.candidates.add(candidate);
1206 }
1207
1208 private void mergeCandidates(List<JingleCandidate> candidates) {
1209 Collections.sort(candidates, (a, b) -> Integer.compare(b.getPriority(), a.getPriority()));
1210 for (JingleCandidate c : candidates) {
1211 mergeCandidate(c);
1212 }
1213 }
1214
1215 private JingleCandidate getCandidate(String cid) {
1216 for (JingleCandidate c : this.candidates) {
1217 if (c.getCid().equals(cid)) {
1218 return c;
1219 }
1220 }
1221 return null;
1222 }
1223
1224 void updateProgress(int i) {
1225 this.mProgress = i;
1226 jingleConnectionManager.updateConversationUi(false);
1227 }
1228
1229 String getTransportId() {
1230 return this.transportId;
1231 }
1232
1233 FileTransferDescription.Version getFtVersion() {
1234 return this.description.getVersion();
1235 }
1236
1237 public JingleTransport getTransport() {
1238 return this.transport;
1239 }
1240
1241 public boolean start() {
1242 if (id.account.getStatus() == Account.State.ONLINE) {
1243 if (mJingleStatus == JINGLE_STATUS_INITIATED) {
1244 new Thread(this::sendAccept).start();
1245 }
1246 return true;
1247 } else {
1248 return false;
1249 }
1250 }
1251
1252 @Override
1253 public int getStatus() {
1254 return this.mStatus;
1255 }
1256
1257 @Override
1258 public Long getFileSize() {
1259 if (this.file != null) {
1260 return this.file.getExpectedSize();
1261 } else {
1262 return null;
1263 }
1264 }
1265
1266 @Override
1267 public int getProgress() {
1268 return this.mProgress;
1269 }
1270
1271 AbstractConnectionManager getConnectionManager() {
1272 return this.jingleConnectionManager;
1273 }
1274
1275 interface OnProxyActivated {
1276 void success();
1277
1278 void failed();
1279 }
1280}