JingleFileTransferConnection.java

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