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