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.contentSenders, this.contentName);
 581        if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL && remoteSupportsOmemoJet) {
 582            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": remote announced support for JET");
 583            final Element security = new Element("security", Namespace.JINGLE_ENCRYPTED_TRANSPORT);
 584            security.setAttribute("name", this.contentName);
 585            security.setAttribute("cipher", JET_OMEMO_CIPHER);
 586            security.setAttribute("type", AxolotlService.PEP_PREFIX);
 587            security.addChild(mXmppAxolotlMessage.toElement());
 588            content.addChild(security);
 589        }
 590        content.setDescription(this.description);
 591        message.resetFileParams();
 592        try {
 593            this.mFileInputStream = new FileInputStream(file);
 594        } catch (FileNotFoundException e) {
 595            fail(e.getMessage());
 596            return;
 597        }
 598        if (this.initialTransport == IbbTransportInfo.class) {
 599            content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
 600            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": sending IBB offer");
 601        } else {
 602            final Collection<JingleCandidate> candidates = getOurCandidates();
 603            content.setTransport(new S5BTransportInfo(this.transportId, candidates));
 604            Log.d(Config.LOGTAG, String.format("%s: sending S5B offer with %d candidates", id.account.getJid().asBareJid(), candidates.size()));
 605        }
 606        packet.addJingleContent(content);
 607        this.sendJinglePacket(packet, (account, response) -> {
 608            if (response.getType() == IqPacket.TYPE.RESULT) {
 609                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": other party received offer");
 610                if (mJingleStatus == JINGLE_STATUS_OFFERED) {
 611                    mJingleStatus = JINGLE_STATUS_INITIATED;
 612                    xmppConnectionService.markMessage(message, Message.STATUS_OFFERED);
 613                } else {
 614                    Log.d(Config.LOGTAG, "received ack for offer when status was " + mJingleStatus);
 615                }
 616            } else {
 617                fail(IqParser.extractErrorMessage(response));
 618            }
 619        });
 620
 621    }
 622
 623    private void sendHash() {
 624        final Element checksum = new Element("checksum", description.getVersion().getNamespace());
 625        checksum.setAttribute("creator", "initiator");
 626        checksum.setAttribute("name", "a-file-offer");
 627        Element hash = checksum.addChild("file").addChild("hash", "urn:xmpp:hashes:2");
 628        hash.setAttribute("algo", "sha-1").setContent(Base64.encodeToString(file.getSha1Sum(), Base64.NO_WRAP));
 629
 630        final JinglePacket packet = this.bootstrapPacket(JinglePacket.Action.SESSION_INFO);
 631        packet.addJingleChild(checksum);
 632        xmppConnectionService.sendIqPacket(id.account, packet, (account, response) -> {
 633            if (response.getType() == IqPacket.TYPE.ERROR) {
 634                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignoring error response to our session-info (hash transmission)");
 635            }
 636        });
 637    }
 638
 639    private Collection<JingleCandidate> getOurCandidates() {
 640        return Collections2.filter(this.candidates, c -> c != null && c.isOurs());
 641    }
 642
 643    private void sendAccept() {
 644        mJingleStatus = JINGLE_STATUS_ACCEPTED;
 645        this.mStatus = Transferable.STATUS_DOWNLOADING;
 646        this.jingleConnectionManager.updateConversationUi(true);
 647        if (initialTransport == S5BTransportInfo.class) {
 648            sendAcceptSocks();
 649        } else {
 650            sendAcceptIbb();
 651        }
 652    }
 653
 654    private void sendAcceptSocks() {
 655        gatherAndConnectDirectCandidates();
 656        this.jingleConnectionManager.getPrimaryCandidate(this.id.account, isInitiator(), (success, candidate) -> {
 657            final JinglePacket packet = bootstrapPacket(JinglePacket.Action.SESSION_ACCEPT);
 658            final Content content = new Content(contentCreator, contentSenders, contentName);
 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, contentSenders, contentName);
 698        content.setDescription(this.description);
 699        content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
 700        packet.addJingleContent(content);
 701        this.transport.receive(file, onFileTransmissionStatusChanged);
 702        this.sendJinglePacket(packet);
 703    }
 704
 705    private JinglePacket bootstrapPacket(JinglePacket.Action action) {
 706        final JinglePacket packet = new JinglePacket(action, this.id.sessionId);
 707        packet.setTo(id.with);
 708        return packet;
 709    }
 710
 711    private void sendJinglePacket(JinglePacket packet) {
 712        xmppConnectionService.sendIqPacket(id.account, packet, responseListener);
 713    }
 714
 715    private void sendJinglePacket(JinglePacket packet, OnIqPacketReceived callback) {
 716        xmppConnectionService.sendIqPacket(id.account, packet, callback);
 717    }
 718
 719    private void receiveAccept(JinglePacket packet) {
 720        if (responding()) {
 721            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order session-accept (we were responding)");
 722            respondToIqWithOutOfOrder(packet);
 723            return;
 724        }
 725        if (this.mJingleStatus != JINGLE_STATUS_INITIATED) {
 726            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order session-accept");
 727            respondToIqWithOutOfOrder(packet);
 728            return;
 729        }
 730        this.mJingleStatus = JINGLE_STATUS_ACCEPTED;
 731        xmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
 732        final Content content = packet.getJingleContent();
 733        final GenericTransportInfo transportInfo = content.getTransport();
 734        //TODO we want to fail if transportInfo doesn’t match our intialTransport and/or our id
 735        if (transportInfo instanceof S5BTransportInfo) {
 736            final S5BTransportInfo s5BTransportInfo = (S5BTransportInfo) transportInfo;
 737            respondToIq(packet, true);
 738            //TODO calling merge is probably a bug because that might eliminate candidates of the other party and lead to us not sending accept/deny
 739            //TODO: we probably just want to call add
 740            mergeCandidates(s5BTransportInfo.getCandidates());
 741            this.connectNextCandidate();
 742        } else if (transportInfo instanceof IbbTransportInfo) {
 743            final IbbTransportInfo ibbTransportInfo = (IbbTransportInfo) transportInfo;
 744            final int remoteBlockSize = ibbTransportInfo.getBlockSize();
 745            if (remoteBlockSize > 0) {
 746                this.ibbBlockSize = Math.min(ibbBlockSize, remoteBlockSize);
 747            }
 748            respondToIq(packet, true);
 749            this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
 750            this.transport.connect(onIbbTransportConnected);
 751        } else {
 752            respondToIq(packet, false);
 753        }
 754    }
 755
 756    private void receiveTransportInfo(JinglePacket packet) {
 757        final Content content = packet.getJingleContent();
 758        final GenericTransportInfo transportInfo = content.getTransport();
 759        if (transportInfo instanceof S5BTransportInfo) {
 760            final S5BTransportInfo s5BTransportInfo = (S5BTransportInfo) transportInfo;
 761            if (s5BTransportInfo.hasChild("activated")) {
 762                respondToIq(packet, true);
 763                if ((this.transport != null) && (this.transport instanceof JingleSocks5Transport)) {
 764                    onProxyActivated.success();
 765                } else {
 766                    String cid = s5BTransportInfo.findChild("activated").getAttribute("cid");
 767                    Log.d(Config.LOGTAG, "received proxy activated (" + cid
 768                            + ")prior to choosing our own transport");
 769                    JingleSocks5Transport connection = this.connections.get(cid);
 770                    if (connection != null) {
 771                        connection.setActivated(true);
 772                    } else {
 773                        Log.d(Config.LOGTAG, "activated connection not found");
 774                        sendSessionTerminate(Reason.FAILED_TRANSPORT);
 775                        this.fail();
 776                    }
 777                }
 778            } else if (s5BTransportInfo.hasChild("proxy-error")) {
 779                respondToIq(packet, true);
 780                onProxyActivated.failed();
 781            } else if (s5BTransportInfo.hasChild("candidate-error")) {
 782                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received candidate error");
 783                respondToIq(packet, true);
 784                this.receivedCandidate = true;
 785                if (mJingleStatus == JINGLE_STATUS_ACCEPTED && this.sentCandidate) {
 786                    this.connect();
 787                }
 788            } else if (s5BTransportInfo.hasChild("candidate-used")) {
 789                String cid = s5BTransportInfo.findChild("candidate-used").getAttribute("cid");
 790                if (cid != null) {
 791                    Log.d(Config.LOGTAG, "candidate used by counterpart:" + cid);
 792                    JingleCandidate candidate = getCandidate(cid);
 793                    if (candidate == null) {
 794                        Log.d(Config.LOGTAG, "could not find candidate with cid=" + cid);
 795                        respondToIq(packet, false);
 796                        return;
 797                    }
 798                    respondToIq(packet, true);
 799                    candidate.flagAsUsedByCounterpart();
 800                    this.receivedCandidate = true;
 801                    if (mJingleStatus == JINGLE_STATUS_ACCEPTED && this.sentCandidate) {
 802                        this.connect();
 803                    } else {
 804                        Log.d(Config.LOGTAG, "ignoring because file is already in transmission or we haven't sent our candidate yet status=" + mJingleStatus + " sentCandidate=" + sentCandidate);
 805                    }
 806                } else {
 807                    respondToIq(packet, false);
 808                }
 809            } else {
 810                respondToIq(packet, false);
 811            }
 812        } else {
 813            respondToIq(packet, true);
 814        }
 815    }
 816
 817    private void connect() {
 818        final JingleSocks5Transport connection = chooseConnection();
 819        this.transport = connection;
 820        if (connection == null) {
 821            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": could not find suitable candidate");
 822            this.disconnectSocks5Connections();
 823            if (isInitiator()) {
 824                this.sendFallbackToIbb();
 825            }
 826        } else {
 827            //TODO at this point we can already close other connections to free some resources
 828            final JingleCandidate candidate = connection.getCandidate();
 829            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": elected candidate " + candidate.toString());
 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        final List<JingleSocks5Transport> establishedConnections = FluentIterable.from(connections.entrySet())
 879                .transform(Entry::getValue)
 880                .filter(c -> (c != null && c.isEstablished() && (c.getCandidate().isUsedByCounterpart() || !c.getCandidate().isOurs())))
 881                .toSortedList((a, b) -> {
 882                    final int compare = Integer.compare(b.getCandidate().getPriority(), a.getCandidate().getPriority());
 883                    if (compare == 0) {
 884                        if (isInitiator()) {
 885                            //pick the one we sent a candidate-used for (meaning not ours)
 886                            return a.getCandidate().isOurs() ? 1 : -1;
 887                        } else {
 888                            //pick the one they sent a candidate-used for (meaning ours)
 889                            return a.getCandidate().isOurs() ? -1 : 1;
 890                        }
 891                    }
 892                    return compare;
 893                });
 894        return Iterables.getFirst(establishedConnections, null);
 895    }
 896
 897    private void sendSuccess() {
 898        sendSessionTerminate(Reason.SUCCESS);
 899        this.disconnectSocks5Connections();
 900        this.mJingleStatus = JINGLE_STATUS_FINISHED;
 901        this.message.setStatus(Message.STATUS_RECEIVED);
 902        this.message.setTransferable(null);
 903        this.xmppConnectionService.updateMessage(message, false);
 904        this.jingleConnectionManager.finishConnection(this);
 905    }
 906
 907    private void sendFallbackToIbb() {
 908        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": sending fallback to ibb");
 909        final JinglePacket packet = this.bootstrapPacket(JinglePacket.Action.TRANSPORT_REPLACE);
 910        final Content content = new Content(this.contentCreator, this.contentSenders, this.contentName);
 911        this.transportId = JingleConnectionManager.nextRandomId();
 912        content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
 913        packet.addJingleContent(content);
 914        this.sendJinglePacket(packet);
 915    }
 916
 917
 918    private void receiveFallbackToIbb(final JinglePacket packet, final IbbTransportInfo transportInfo) {
 919        if (isInitiator()) {
 920            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-replace (we were initiating)");
 921            respondToIqWithOutOfOrder(packet);
 922            return;
 923        }
 924        final boolean validState = mJingleStatus == JINGLE_STATUS_ACCEPTED || (proxyActivationFailed && mJingleStatus == JINGLE_STATUS_TRANSMITTING);
 925        if (!validState) {
 926            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-replace");
 927            respondToIqWithOutOfOrder(packet);
 928            return;
 929        }
 930        this.proxyActivationFailed = false; //fallback received; now we no longer need to accept another one;
 931        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receiving fallback to ibb");
 932        final int remoteBlockSize = transportInfo.getBlockSize();
 933        if (remoteBlockSize > 0) {
 934            this.ibbBlockSize = Math.min(MAX_IBB_BLOCK_SIZE, remoteBlockSize);
 935        } else {
 936            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to parse block size in transport-replace");
 937        }
 938        this.transportId = transportInfo.getTransportId(); //TODO: handle the case where this is null by the remote party
 939        this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
 940
 941        final JinglePacket answer = bootstrapPacket(JinglePacket.Action.TRANSPORT_ACCEPT);
 942
 943        final Content content = new Content(contentCreator, contentSenders, contentName);
 944        content.setTransport(new IbbTransportInfo(this.transportId, this.ibbBlockSize));
 945        answer.addJingleContent(content);
 946
 947        respondToIq(packet, true);
 948
 949        if (isInitiator()) {
 950            this.sendJinglePacket(answer, (account, response) -> {
 951                if (response.getType() == IqPacket.TYPE.RESULT) {
 952                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + " recipient ACKed our transport-accept. creating ibb");
 953                    transport.connect(onIbbTransportConnected);
 954                }
 955            });
 956        } else {
 957            this.transport.receive(file, onFileTransmissionStatusChanged);
 958            this.sendJinglePacket(answer);
 959        }
 960    }
 961
 962    private void receiveTransportAccept(JinglePacket packet) {
 963        if (responding()) {
 964            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-accept (we were responding)");
 965            respondToIqWithOutOfOrder(packet);
 966            return;
 967        }
 968        final boolean validState = mJingleStatus == JINGLE_STATUS_ACCEPTED || (proxyActivationFailed && mJingleStatus == JINGLE_STATUS_TRANSMITTING);
 969        if (!validState) {
 970            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received out of order transport-accept");
 971            respondToIqWithOutOfOrder(packet);
 972            return;
 973        }
 974        this.proxyActivationFailed = false; //fallback accepted; now we no longer need to accept another one;
 975        final Content content = packet.getJingleContent();
 976        final GenericTransportInfo transportInfo = content == null ? null : content.getTransport();
 977        if (transportInfo instanceof IbbTransportInfo) {
 978            final IbbTransportInfo ibbTransportInfo = (IbbTransportInfo) transportInfo;
 979            final int remoteBlockSize = ibbTransportInfo.getBlockSize();
 980            if (remoteBlockSize > 0) {
 981                this.ibbBlockSize = Math.min(MAX_IBB_BLOCK_SIZE, remoteBlockSize);
 982            }
 983            final String sid = ibbTransportInfo.getTransportId();
 984            this.transport = new JingleInBandTransport(this, this.transportId, this.ibbBlockSize);
 985
 986            if (sid == null || !sid.equals(this.transportId)) {
 987                Log.w(Config.LOGTAG, String.format("%s: sid in transport-accept (%s) did not match our sid (%s) ", id.account.getJid().asBareJid(), sid, transportId));
 988            }
 989            respondToIq(packet, true);
 990            //might be receive instead if we are not initiating
 991            if (isInitiator()) {
 992                this.transport.connect(onIbbTransportConnected);
 993            }
 994        } else {
 995            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received invalid transport-accept");
 996            respondToIq(packet, false);
 997        }
 998    }
 999
1000    private void receiveSuccess() {
1001        if (isInitiator()) {
1002            this.mJingleStatus = JINGLE_STATUS_FINISHED;
1003            this.xmppConnectionService.markMessage(this.message, Message.STATUS_SEND_RECEIVED);
1004            this.disconnectSocks5Connections();
1005            if (this.transport instanceof JingleInBandTransport) {
1006                this.transport.disconnect();
1007            }
1008            this.message.setTransferable(null);
1009            this.jingleConnectionManager.finishConnection(this);
1010        } else {
1011            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session-terminate/success while responding");
1012        }
1013    }
1014
1015    @Override
1016    public void cancel() {
1017        this.cancelled = true;
1018        abort(Reason.CANCEL);
1019    }
1020
1021    private void abort(final Reason reason) {
1022        this.disconnectSocks5Connections();
1023        if (this.transport instanceof JingleInBandTransport) {
1024            this.transport.disconnect();
1025        }
1026        sendSessionTerminate(reason);
1027        this.jingleConnectionManager.finishConnection(this);
1028        if (responding()) {
1029            this.message.setTransferable(new TransferablePlaceholder(cancelled ? Transferable.STATUS_CANCELLED : Transferable.STATUS_FAILED));
1030            if (this.file != null) {
1031                file.delete();
1032            }
1033            this.jingleConnectionManager.updateConversationUi(true);
1034        } else {
1035            this.xmppConnectionService.markMessage(this.message, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : null);
1036            this.message.setTransferable(null);
1037        }
1038    }
1039
1040    private void fail() {
1041        fail(null);
1042    }
1043
1044    private void fail(String errorMessage) {
1045        this.mJingleStatus = JINGLE_STATUS_FAILED;
1046        this.disconnectSocks5Connections();
1047        if (this.transport instanceof JingleInBandTransport) {
1048            this.transport.disconnect();
1049        }
1050        FileBackend.close(mFileInputStream);
1051        FileBackend.close(mFileOutputStream);
1052        if (this.message != null) {
1053            if (responding()) {
1054                this.message.setTransferable(new TransferablePlaceholder(cancelled ? Transferable.STATUS_CANCELLED : Transferable.STATUS_FAILED));
1055                if (this.file != null) {
1056                    file.delete();
1057                }
1058                this.jingleConnectionManager.updateConversationUi(true);
1059            } else {
1060                this.xmppConnectionService.markMessage(this.message,
1061                        Message.STATUS_SEND_FAILED,
1062                        cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage);
1063                this.message.setTransferable(null);
1064            }
1065        }
1066        this.jingleConnectionManager.finishConnection(this);
1067    }
1068
1069    private void sendSessionTerminate(Reason reason) {
1070        final JinglePacket packet = bootstrapPacket(JinglePacket.Action.SESSION_TERMINATE);
1071        packet.setReason(reason, null);
1072        this.sendJinglePacket(packet);
1073    }
1074
1075    private void connectNextCandidate() {
1076        for (JingleCandidate candidate : this.candidates) {
1077            if ((!connections.containsKey(candidate.getCid()) && (!candidate
1078                    .isOurs()))) {
1079                this.connectWithCandidate(candidate);
1080                return;
1081            }
1082        }
1083        this.sendCandidateError();
1084    }
1085
1086    private void connectWithCandidate(final JingleCandidate candidate) {
1087        final JingleSocks5Transport socksConnection = new JingleSocks5Transport(
1088                this, candidate);
1089        connections.put(candidate.getCid(), socksConnection);
1090        socksConnection.connect(new OnTransportConnected() {
1091
1092            @Override
1093            public void failed() {
1094                Log.d(Config.LOGTAG,
1095                        "connection failed with " + candidate.getHost() + ":"
1096                                + candidate.getPort());
1097                connectNextCandidate();
1098            }
1099
1100            @Override
1101            public void established() {
1102                Log.d(Config.LOGTAG,
1103                        "established connection with " + candidate.getHost()
1104                                + ":" + candidate.getPort());
1105                sendCandidateUsed(candidate.getCid());
1106            }
1107        });
1108    }
1109
1110    private void disconnectSocks5Connections() {
1111        Iterator<Entry<String, JingleSocks5Transport>> it = this.connections
1112                .entrySet().iterator();
1113        while (it.hasNext()) {
1114            Entry<String, JingleSocks5Transport> pairs = it.next();
1115            pairs.getValue().disconnect();
1116            it.remove();
1117        }
1118    }
1119
1120    private void sendProxyActivated(String cid) {
1121        final JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1122        final Content content = new Content(this.contentCreator, this.contentSenders, this.contentName);
1123        content.setTransport(new S5BTransportInfo(this.transportId, new Element("activated").setAttribute("cid", cid)));
1124        packet.addJingleContent(content);
1125        this.sendJinglePacket(packet);
1126    }
1127
1128    private void sendProxyError() {
1129        final JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1130        final Content content = new Content(this.contentCreator, this.contentSenders, this.contentName);
1131        content.setTransport(new S5BTransportInfo(this.transportId, new Element("proxy-error")));
1132        packet.addJingleContent(content);
1133        this.sendJinglePacket(packet);
1134    }
1135
1136    private void sendCandidateUsed(final String cid) {
1137        JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1138        final Content content = new Content(this.contentCreator, this.contentSenders, this.contentName);
1139        content.setTransport(new S5BTransportInfo(this.transportId, new Element("candidate-used").setAttribute("cid", cid)));
1140        packet.addJingleContent(content);
1141        this.sentCandidate = true;
1142        if ((receivedCandidate) && (mJingleStatus == JINGLE_STATUS_ACCEPTED)) {
1143            connect();
1144        }
1145        this.sendJinglePacket(packet);
1146    }
1147
1148    private void sendCandidateError() {
1149        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": sending candidate error");
1150        JinglePacket packet = bootstrapPacket(JinglePacket.Action.TRANSPORT_INFO);
1151        Content content = new Content(this.contentCreator, this.contentSenders, this.contentName);
1152        content.setTransport(new S5BTransportInfo(this.transportId, new Element("candidate-error")));
1153        packet.addJingleContent(content);
1154        this.sentCandidate = true;
1155        this.sendJinglePacket(packet);
1156        if (receivedCandidate && mJingleStatus == JINGLE_STATUS_ACCEPTED) {
1157            connect();
1158        }
1159    }
1160
1161    private int getJingleStatus() {
1162        return this.mJingleStatus;
1163    }
1164
1165    private boolean equalCandidateExists(JingleCandidate candidate) {
1166        for (JingleCandidate c : this.candidates) {
1167            if (c.equalValues(candidate)) {
1168                return true;
1169            }
1170        }
1171        return false;
1172    }
1173
1174    private void mergeCandidate(JingleCandidate candidate) {
1175        for (JingleCandidate c : this.candidates) {
1176            if (c.equals(candidate)) {
1177                return;
1178            }
1179        }
1180        this.candidates.add(candidate);
1181    }
1182
1183    private void mergeCandidates(List<JingleCandidate> candidates) {
1184        Collections.sort(candidates, (a, b) -> Integer.compare(b.getPriority(), a.getPriority()));
1185        for (JingleCandidate c : candidates) {
1186            mergeCandidate(c);
1187        }
1188    }
1189
1190    private JingleCandidate getCandidate(String cid) {
1191        for (JingleCandidate c : this.candidates) {
1192            if (c.getCid().equals(cid)) {
1193                return c;
1194            }
1195        }
1196        return null;
1197    }
1198
1199    void updateProgress(int i) {
1200        this.mProgress = i;
1201        jingleConnectionManager.updateConversationUi(false);
1202    }
1203
1204    String getTransportId() {
1205        return this.transportId;
1206    }
1207
1208    FileTransferDescription.Version getFtVersion() {
1209        return this.description.getVersion();
1210    }
1211
1212    public JingleTransport getTransport() {
1213        return this.transport;
1214    }
1215
1216    public boolean start() {
1217        if (id.account.getStatus() == Account.State.ONLINE) {
1218            if (mJingleStatus == JINGLE_STATUS_INITIATED) {
1219                new Thread(this::sendAccept).start();
1220            }
1221            return true;
1222        } else {
1223            return false;
1224        }
1225    }
1226
1227    @Override
1228    public int getStatus() {
1229        return this.mStatus;
1230    }
1231
1232    @Override
1233    public Long getFileSize() {
1234        if (this.file != null) {
1235            return this.file.getExpectedSize();
1236        } else {
1237            return null;
1238        }
1239    }
1240
1241    @Override
1242    public int getProgress() {
1243        return this.mProgress;
1244    }
1245
1246    AbstractConnectionManager getConnectionManager() {
1247        return this.jingleConnectionManager;
1248    }
1249
1250    interface OnProxyActivated {
1251        void success();
1252
1253        void failed();
1254    }
1255}