JingleConnection.java

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