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