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