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