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