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