JingleConnection.java

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