JingleFileTransferConnection.java

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