JingleFileTransferConnection.java

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