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            final String path = fileOffer.findChildContent("name");
 418            if (path != null) {
 419                AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(path);
 420                if (VALID_IMAGE_EXTENSIONS.contains(extension.main)) {
 421                    message.setType(Message.TYPE_IMAGE);
 422                    message.setRelativeFilePath(message.getUuid() + "." + extension.main);
 423                } else if (VALID_CRYPTO_EXTENSIONS.contains(extension.main)) {
 424                    if (VALID_IMAGE_EXTENSIONS.contains(extension.secondary)) {
 425                        message.setType(Message.TYPE_IMAGE);
 426                        message.setRelativeFilePath(message.getUuid() + "." + extension.main);
 427                    } else {
 428                        message.setType(Message.TYPE_FILE);
 429                        message.setRelativeFilePath(message.getUuid() + (extension.secondary != null ? ("." + extension.secondary) : ""));
 430                    }
 431                    message.setEncryption(Message.ENCRYPTION_PGP);
 432                } else {
 433                    message.setType(Message.TYPE_FILE);
 434                    message.setRelativeFilePath(message.getUuid() + (extension.main != null ? ("." + extension.main) : ""));
 435                }
 436                long size = parseLong(fileSize, 0);
 437                message.setBody(Long.toString(size));
 438                conversation.add(message);
 439                mJingleConnectionManager.updateConversationUi(true);
 440                this.file = this.mXmppConnectionService.getFileBackend().getFile(message, false);
 441                if (mXmppAxolotlMessage != null) {
 442                    XmppAxolotlMessage.XmppAxolotlKeyTransportMessage transportMessage = account.getAxolotlService().processReceivingKeyTransportMessage(mXmppAxolotlMessage, false);
 443                    if (transportMessage != null) {
 444                        message.setEncryption(Message.ENCRYPTION_AXOLOTL);
 445                        this.file.setKey(transportMessage.getKey());
 446                        this.file.setIv(transportMessage.getIv());
 447                        message.setFingerprint(transportMessage.getFingerprint());
 448                    } else {
 449                        Log.d(Config.LOGTAG, "could not process KeyTransportMessage");
 450                    }
 451                }
 452                message.resetFileParams();
 453                this.file.setExpectedSize(size);
 454                if (mJingleConnectionManager.hasStoragePermission()
 455                        && size < this.mJingleConnectionManager.getAutoAcceptFileSize()
 456                        && mXmppConnectionService.isDataSaverDisabled()) {
 457                    Log.d(Config.LOGTAG, "auto accepting file from " + packet.getFrom());
 458                    this.acceptedAutomatically = true;
 459                    this.sendAccept();
 460                } else {
 461                    message.markUnread();
 462                    Log.d(Config.LOGTAG,
 463                            "not auto accepting new file offer with size: "
 464                                    + size
 465                                    + " allowed size:"
 466                                    + this.mJingleConnectionManager
 467                                    .getAutoAcceptFileSize());
 468                    this.mXmppConnectionService.getNotificationService().push(message);
 469                }
 470                Log.d(Config.LOGTAG, "receiving file: expecting size of " + this.file.getExpectedSize());
 471            } else {
 472                this.sendCancel();
 473                this.fail();
 474            }
 475        } else {
 476            this.sendCancel();
 477            this.fail();
 478        }
 479    }
 480
 481    private static long parseLong(final Element element, final long l) {
 482        final String input = element == null ? null : element.getContent();
 483        if (input == null) {
 484            return l;
 485        }
 486        try {
 487            return Long.parseLong(input);
 488        } catch (Exception e) {
 489            return l;
 490        }
 491    }
 492
 493    private void sendInitRequest() {
 494        JinglePacket packet = this.bootstrapPacket("session-initiate");
 495        Content content = new Content(this.contentCreator, this.contentName);
 496        if (message.isFileOrImage()) {
 497            content.setTransportId(this.transportId);
 498            this.file = this.mXmppConnectionService.getFileBackend().getFile(message, false);
 499            if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
 500                this.file.setKey(mXmppAxolotlMessage.getInnerKey());
 501                this.file.setIv(mXmppAxolotlMessage.getIV());
 502                this.file.setExpectedSize(file.getSize() + 16);
 503                content.setFileOffer(this.file, false, this.ftVersion).addChild(mXmppAxolotlMessage.toElement());
 504            } else {
 505                this.file.setExpectedSize(file.getSize());
 506                content.setFileOffer(this.file, false, this.ftVersion);
 507            }
 508            message.resetFileParams();
 509            try {
 510                this.mFileInputStream = new FileInputStream(file);
 511            } catch (FileNotFoundException e) {
 512                abort();
 513                return;
 514            }
 515            content.setTransportId(this.transportId);
 516            if (this.initialTransport == Transport.IBB) {
 517                content.ibbTransport().setAttribute("block-size", Integer.toString(this.ibbBlockSize));
 518            } else {
 519                content.socks5transport().setChildren(getCandidatesAsElements());
 520            }
 521            packet.setContent(content);
 522            this.sendJinglePacket(packet, (account, response) -> {
 523                if (response.getType() == IqPacket.TYPE.RESULT) {
 524                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": other party received offer");
 525                    if (mJingleStatus == JINGLE_STATUS_OFFERED) {
 526                        mJingleStatus = JINGLE_STATUS_INITIATED;
 527                        mXmppConnectionService.markMessage(message, Message.STATUS_OFFERED);
 528                    } else {
 529                        Log.d(Config.LOGTAG, "received ack for offer when status was " + mJingleStatus);
 530                    }
 531                } else {
 532                    fail(IqParser.extractErrorMessage(response));
 533                }
 534            });
 535
 536        }
 537    }
 538
 539    private void sendHash() {
 540        JinglePacket packet = this.bootstrapPacket("session-info");
 541        packet.addChecksum(file.getSha1Sum(), ftVersion.getNamespace());
 542        this.sendJinglePacket(packet);
 543    }
 544
 545    private List<Element> getCandidatesAsElements() {
 546        List<Element> elements = new ArrayList<>();
 547        for (JingleCandidate c : this.candidates) {
 548            if (c.isOurs()) {
 549                elements.add(c.toElement());
 550            }
 551        }
 552        return elements;
 553    }
 554
 555    private void sendAccept() {
 556        mJingleStatus = JINGLE_STATUS_ACCEPTED;
 557        this.mStatus = Transferable.STATUS_DOWNLOADING;
 558        this.mJingleConnectionManager.updateConversationUi(true);
 559        if (initialTransport == Transport.SOCKS) {
 560            sendAcceptSocks();
 561        } else {
 562            sendAcceptIbb();
 563        }
 564    }
 565
 566    private void sendAcceptSocks() {
 567        this.mJingleConnectionManager.getPrimaryCandidate(this.account, (success, candidate) -> {
 568            final JinglePacket packet = bootstrapPacket("session-accept");
 569            final Content content = new Content(contentCreator, contentName);
 570            content.setFileOffer(fileOffer, ftVersion);
 571            content.setTransportId(transportId);
 572            if (success && candidate != null && !equalCandidateExists(candidate)) {
 573                final JingleSocks5Transport socksConnection = new JingleSocks5Transport(this, candidate);
 574                connections.put(candidate.getCid(), socksConnection);
 575                socksConnection.connect(new OnTransportConnected() {
 576
 577                    @Override
 578                    public void failed() {
 579                        Log.d(Config.LOGTAG, "connection to our own primary candidate failed");
 580                        content.socks5transport().setChildren(getCandidatesAsElements());
 581                        packet.setContent(content);
 582                        sendJinglePacket(packet);
 583                        connectNextCandidate();
 584                    }
 585
 586                    @Override
 587                    public void established() {
 588                        Log.d(Config.LOGTAG, "connected to primary candidate");
 589                        mergeCandidate(candidate);
 590                        content.socks5transport().setChildren(getCandidatesAsElements());
 591                        packet.setContent(content);
 592                        sendJinglePacket(packet);
 593                        connectNextCandidate();
 594                    }
 595                });
 596            } else {
 597                Log.d(Config.LOGTAG, "did not find a primary candidate for ourself");
 598                content.socks5transport().setChildren(getCandidatesAsElements());
 599                packet.setContent(content);
 600                sendJinglePacket(packet);
 601                connectNextCandidate();
 602            }
 603        });
 604    }
 605
 606    private void sendAcceptIbb() {
 607        this.transport = new JingleInbandTransport(this, this.transportId, this.ibbBlockSize);
 608        final JinglePacket packet = bootstrapPacket("session-accept");
 609        final Content content = new Content(contentCreator, contentName);
 610        content.setFileOffer(fileOffer, ftVersion);
 611        content.setTransportId(transportId);
 612        content.ibbTransport().setAttribute("block-size", this.ibbBlockSize);
 613        packet.setContent(content);
 614        this.transport.receive(file, onFileTransmissionStatusChanged);
 615        this.sendJinglePacket(packet);
 616    }
 617
 618    private JinglePacket bootstrapPacket(String action) {
 619        JinglePacket packet = new JinglePacket();
 620        packet.setAction(action);
 621        packet.setFrom(account.getJid());
 622        packet.setTo(this.message.getCounterpart());
 623        packet.setSessionId(this.sessionId);
 624        packet.setInitiator(this.initiator);
 625        return packet;
 626    }
 627
 628    private void sendJinglePacket(JinglePacket packet) {
 629        mXmppConnectionService.sendIqPacket(account, packet, responseListener);
 630    }
 631
 632    private void sendJinglePacket(JinglePacket packet, OnIqPacketReceived callback) {
 633        mXmppConnectionService.sendIqPacket(account, packet, callback);
 634    }
 635
 636    private boolean receiveAccept(JinglePacket packet) {
 637        if (this.mJingleStatus != JINGLE_STATUS_INITIATED) {
 638            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": received out of order session-accept");
 639            return false;
 640        }
 641        this.mJingleStatus = JINGLE_STATUS_ACCEPTED;
 642        mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
 643        Content content = packet.getJingleContent();
 644        if (content.hasSocks5Transport()) {
 645            mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
 646            this.connectNextCandidate();
 647            return true;
 648        } else if (content.hasIbbTransport()) {
 649            String receivedBlockSize = packet.getJingleContent().ibbTransport().getAttribute("block-size");
 650            if (receivedBlockSize != null) {
 651                int bs = Integer.parseInt(receivedBlockSize);
 652                if (bs > this.ibbBlockSize) {
 653                    this.ibbBlockSize = bs;
 654                }
 655            }
 656            this.transport = new JingleInbandTransport(this, this.transportId, this.ibbBlockSize);
 657            this.transport.connect(onIbbTransportConnected);
 658            return true;
 659        } else {
 660            return false;
 661        }
 662    }
 663
 664    private boolean receiveTransportInfo(JinglePacket packet) {
 665        Content content = packet.getJingleContent();
 666        if (content.hasSocks5Transport()) {
 667            if (content.socks5transport().hasChild("activated")) {
 668                if ((this.transport != null) && (this.transport instanceof JingleSocks5Transport)) {
 669                    onProxyActivated.success();
 670                } else {
 671                    String cid = content.socks5transport().findChild("activated").getAttribute("cid");
 672                    Log.d(Config.LOGTAG, "received proxy activated (" + cid
 673                            + ")prior to choosing our own transport");
 674                    JingleSocks5Transport connection = this.connections.get(cid);
 675                    if (connection != null) {
 676                        connection.setActivated(true);
 677                    } else {
 678                        Log.d(Config.LOGTAG, "activated connection not found");
 679                        this.sendCancel();
 680                        this.fail();
 681                    }
 682                }
 683                return true;
 684            } else if (content.socks5transport().hasChild("proxy-error")) {
 685                onProxyActivated.failed();
 686                return true;
 687            } else if (content.socks5transport().hasChild("candidate-error")) {
 688                Log.d(Config.LOGTAG, "received candidate error");
 689                this.receivedCandidate = true;
 690                if (mJingleStatus == JINGLE_STATUS_ACCEPTED && this.sentCandidate) {
 691                    this.connect();
 692                }
 693                return true;
 694            } else if (content.socks5transport().hasChild("candidate-used")) {
 695                String cid = content.socks5transport().findChild("candidate-used").getAttribute("cid");
 696                if (cid != null) {
 697                    Log.d(Config.LOGTAG, "candidate used by counterpart:" + cid);
 698                    JingleCandidate candidate = getCandidate(cid);
 699                    if (candidate == null) {
 700                        Log.d(Config.LOGTAG, "could not find candidate with cid=" + cid);
 701                        return false;
 702                    }
 703                    candidate.flagAsUsedByCounterpart();
 704                    this.receivedCandidate = true;
 705                    if (mJingleStatus == JINGLE_STATUS_ACCEPTED && this.sentCandidate) {
 706                        this.connect();
 707                    } else {
 708                        Log.d(Config.LOGTAG, "ignoring because file is already in transmission or we haven't sent our candidate yet status=" + mJingleStatus + " sentCandidate=" + sentCandidate);
 709                    }
 710                    return true;
 711                } else {
 712                    return false;
 713                }
 714            } else {
 715                return false;
 716            }
 717        } else {
 718            return true;
 719        }
 720    }
 721
 722    private void connect() {
 723        final JingleSocks5Transport connection = chooseConnection();
 724        this.transport = connection;
 725        if (connection == null) {
 726            Log.d(Config.LOGTAG, "could not find suitable candidate");
 727            this.disconnectSocks5Connections();
 728            if (initiating()) {
 729                this.sendFallbackToIbb();
 730            }
 731        } else {
 732            this.mJingleStatus = JINGLE_STATUS_TRANSMITTING;
 733            if (connection.needsActivation()) {
 734                if (connection.getCandidate().isOurs()) {
 735                    final String sid;
 736                    if (ftVersion == Content.Version.FT_3) {
 737                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": use session ID instead of transport ID to activate proxy");
 738                        sid = getSessionId();
 739                    } else {
 740                        sid = getTransportId();
 741                    }
 742                    Log.d(Config.LOGTAG, "candidate "
 743                            + connection.getCandidate().getCid()
 744                            + " was our proxy. going to activate");
 745                    IqPacket activation = new IqPacket(IqPacket.TYPE.SET);
 746                    activation.setTo(connection.getCandidate().getJid());
 747                    activation.query("http://jabber.org/protocol/bytestreams")
 748                            .setAttribute("sid", sid);
 749                    activation.query().addChild("activate")
 750                            .setContent(this.getCounterPart().toString());
 751                    mXmppConnectionService.sendIqPacket(account, activation, (account, response) -> {
 752                        if (response.getType() != IqPacket.TYPE.RESULT) {
 753                            onProxyActivated.failed();
 754                        } else {
 755                            onProxyActivated.success();
 756                            sendProxyActivated(connection.getCandidate().getCid());
 757                        }
 758                    });
 759                } else {
 760                    Log.d(Config.LOGTAG,
 761                            "candidate "
 762                                    + connection.getCandidate().getCid()
 763                                    + " was a proxy. waiting for other party to activate");
 764                }
 765            } else {
 766                if (initiating()) {
 767                    Log.d(Config.LOGTAG, "we were initiating. sending file");
 768                    connection.send(file, onFileTransmissionStatusChanged);
 769                } else {
 770                    Log.d(Config.LOGTAG, "we were responding. receiving file");
 771                    connection.receive(file, onFileTransmissionStatusChanged);
 772                }
 773            }
 774        }
 775    }
 776
 777    private JingleSocks5Transport chooseConnection() {
 778        JingleSocks5Transport connection = null;
 779        for (Entry<String, JingleSocks5Transport> cursor : connections
 780                .entrySet()) {
 781            JingleSocks5Transport currentConnection = cursor.getValue();
 782            // Log.d(Config.LOGTAG,"comparing candidate: "+currentConnection.getCandidate().toString());
 783            if (currentConnection.isEstablished()
 784                    && (currentConnection.getCandidate().isUsedByCounterpart() || (!currentConnection
 785                    .getCandidate().isOurs()))) {
 786                // Log.d(Config.LOGTAG,"is usable");
 787                if (connection == null) {
 788                    connection = currentConnection;
 789                } else {
 790                    if (connection.getCandidate().getPriority() < currentConnection
 791                            .getCandidate().getPriority()) {
 792                        connection = currentConnection;
 793                    } else if (connection.getCandidate().getPriority() == currentConnection
 794                            .getCandidate().getPriority()) {
 795                        // Log.d(Config.LOGTAG,"found two candidates with same priority");
 796                        if (initiating()) {
 797                            if (currentConnection.getCandidate().isOurs()) {
 798                                connection = currentConnection;
 799                            }
 800                        } else {
 801                            if (!currentConnection.getCandidate().isOurs()) {
 802                                connection = currentConnection;
 803                            }
 804                        }
 805                    }
 806                }
 807            }
 808        }
 809        return connection;
 810    }
 811
 812    private void sendSuccess() {
 813        JinglePacket packet = bootstrapPacket("session-terminate");
 814        Reason reason = new Reason();
 815        reason.addChild("success");
 816        packet.setReason(reason);
 817        this.sendJinglePacket(packet);
 818        this.disconnectSocks5Connections();
 819        this.mJingleStatus = JINGLE_STATUS_FINISHED;
 820        this.message.setStatus(Message.STATUS_RECEIVED);
 821        this.message.setTransferable(null);
 822        this.mXmppConnectionService.updateMessage(message, false);
 823        this.mJingleConnectionManager.finishConnection(this);
 824    }
 825
 826    private void sendFallbackToIbb() {
 827        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending fallback to ibb");
 828        JinglePacket packet = this.bootstrapPacket("transport-replace");
 829        Content content = new Content(this.contentCreator, this.contentName);
 830        this.transportId = this.mJingleConnectionManager.nextRandomId();
 831        content.setTransportId(this.transportId);
 832        content.ibbTransport().setAttribute("block-size",
 833                Integer.toString(this.ibbBlockSize));
 834        packet.setContent(content);
 835        this.sendJinglePacket(packet);
 836    }
 837
 838
 839    private boolean receiveFallbackToIbb(JinglePacket packet) {
 840        Log.d(Config.LOGTAG, "receiving fallack to ibb");
 841        final String receivedBlockSize = packet.getJingleContent().ibbTransport().getAttribute("block-size");
 842        if (receivedBlockSize != null) {
 843            final int bs = Integer.parseInt(receivedBlockSize);
 844            if (bs < this.ibbBlockSize) {
 845                this.ibbBlockSize = bs;
 846            }
 847        }
 848        this.transportId = packet.getJingleContent().getTransportId();
 849        this.transport = new JingleInbandTransport(this, this.transportId, this.ibbBlockSize);
 850
 851        final JinglePacket answer = bootstrapPacket("transport-accept");
 852
 853        final Content content = new Content(contentCreator, contentName);
 854        content.setFileOffer(fileOffer, ftVersion);
 855        content.ibbTransport().setAttribute("block-size", this.ibbBlockSize);
 856        answer.setContent(content);
 857
 858
 859        if (initiating()) {
 860            this.sendJinglePacket(answer, (account, response) -> {
 861                if (response.getType() == IqPacket.TYPE.RESULT) {
 862                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + " recipient ACKed our transport-accept. creating ibb");
 863                    transport.connect(onIbbTransportConnected);
 864                }
 865            });
 866        } else {
 867            this.transport.receive(file, onFileTransmissionStatusChanged);
 868            this.sendJinglePacket(answer);
 869        }
 870        return true;
 871    }
 872
 873    private boolean receiveTransportAccept(JinglePacket packet) {
 874        if (packet.getJingleContent().hasIbbTransport()) {
 875            String receivedBlockSize = packet.getJingleContent().ibbTransport()
 876                    .getAttribute("block-size");
 877            if (receivedBlockSize != null) {
 878                int bs = Integer.parseInt(receivedBlockSize);
 879                if (bs > this.ibbBlockSize) {
 880                    this.ibbBlockSize = bs;
 881                }
 882            }
 883            this.transport = new JingleInbandTransport(this, this.transportId, this.ibbBlockSize);
 884
 885            //might be receive instead if we are not initiating
 886            if (initiating()) {
 887                this.transport.connect(onIbbTransportConnected);
 888            } else {
 889                this.transport.receive(file, onFileTransmissionStatusChanged);
 890            }
 891            return true;
 892        } else {
 893            return false;
 894        }
 895    }
 896
 897    private void receiveSuccess() {
 898        if (initiating()) {
 899            this.mJingleStatus = JINGLE_STATUS_FINISHED;
 900            this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_RECEIVED);
 901            this.disconnectSocks5Connections();
 902            if (this.transport instanceof JingleInbandTransport) {
 903                this.transport.disconnect();
 904            }
 905            this.message.setTransferable(null);
 906            this.mJingleConnectionManager.finishConnection(this);
 907        } else {
 908            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received session-terminate/success while responding");
 909        }
 910    }
 911
 912    @Override
 913    public void cancel() {
 914        this.cancelled = true;
 915        abort();
 916    }
 917
 918    public void abort() {
 919        this.disconnectSocks5Connections();
 920        if (this.transport instanceof JingleInbandTransport) {
 921            this.transport.disconnect();
 922        }
 923        this.sendCancel();
 924        this.mJingleConnectionManager.finishConnection(this);
 925        if (responding()) {
 926            this.message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_FAILED));
 927            if (this.file != null) {
 928                file.delete();
 929            }
 930            this.mJingleConnectionManager.updateConversationUi(true);
 931        } else {
 932            this.mXmppConnectionService.markMessage(this.message, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : null);
 933            this.message.setTransferable(null);
 934        }
 935    }
 936
 937    private void fail() {
 938        fail(null);
 939    }
 940
 941    private void fail(String errorMessage) {
 942        this.mJingleStatus = JINGLE_STATUS_FAILED;
 943        this.disconnectSocks5Connections();
 944        if (this.transport instanceof JingleInbandTransport) {
 945            this.transport.disconnect();
 946        }
 947        FileBackend.close(mFileInputStream);
 948        FileBackend.close(mFileOutputStream);
 949        if (this.message != null) {
 950            if (responding()) {
 951                this.message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_FAILED));
 952                if (this.file != null) {
 953                    file.delete();
 954                }
 955                this.mJingleConnectionManager.updateConversationUi(true);
 956            } else {
 957                this.mXmppConnectionService.markMessage(this.message,
 958                        Message.STATUS_SEND_FAILED,
 959                        cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage);
 960                this.message.setTransferable(null);
 961            }
 962        }
 963        this.mJingleConnectionManager.finishConnection(this);
 964    }
 965
 966    private void sendCancel() {
 967        JinglePacket packet = bootstrapPacket("session-terminate");
 968        Reason reason = new Reason();
 969        reason.addChild("cancel");
 970        packet.setReason(reason);
 971        this.sendJinglePacket(packet);
 972    }
 973
 974    private void connectNextCandidate() {
 975        for (JingleCandidate candidate : this.candidates) {
 976            if ((!connections.containsKey(candidate.getCid()) && (!candidate
 977                    .isOurs()))) {
 978                this.connectWithCandidate(candidate);
 979                return;
 980            }
 981        }
 982        this.sendCandidateError();
 983    }
 984
 985    private void connectWithCandidate(final JingleCandidate candidate) {
 986        final JingleSocks5Transport socksConnection = new JingleSocks5Transport(
 987                this, candidate);
 988        connections.put(candidate.getCid(), socksConnection);
 989        socksConnection.connect(new OnTransportConnected() {
 990
 991            @Override
 992            public void failed() {
 993                Log.d(Config.LOGTAG,
 994                        "connection failed with " + candidate.getHost() + ":"
 995                                + candidate.getPort());
 996                connectNextCandidate();
 997            }
 998
 999            @Override
1000            public void established() {
1001                Log.d(Config.LOGTAG,
1002                        "established connection with " + candidate.getHost()
1003                                + ":" + candidate.getPort());
1004                sendCandidateUsed(candidate.getCid());
1005            }
1006        });
1007    }
1008
1009    private void disconnectSocks5Connections() {
1010        Iterator<Entry<String, JingleSocks5Transport>> it = this.connections
1011                .entrySet().iterator();
1012        while (it.hasNext()) {
1013            Entry<String, JingleSocks5Transport> pairs = it.next();
1014            pairs.getValue().disconnect();
1015            it.remove();
1016        }
1017    }
1018
1019    private void sendProxyActivated(String cid) {
1020        JinglePacket packet = bootstrapPacket("transport-info");
1021        Content content = new Content(this.contentCreator, this.contentName);
1022        content.setTransportId(this.transportId);
1023        content.socks5transport().addChild("activated").setAttribute("cid", cid);
1024        packet.setContent(content);
1025        this.sendJinglePacket(packet);
1026    }
1027
1028    private void sendCandidateUsed(final String cid) {
1029        JinglePacket packet = bootstrapPacket("transport-info");
1030        Content content = new Content(this.contentCreator, this.contentName);
1031        content.setTransportId(this.transportId);
1032        content.socks5transport().addChild("candidate-used").setAttribute("cid", cid);
1033        packet.setContent(content);
1034        this.sentCandidate = true;
1035        if ((receivedCandidate) && (mJingleStatus == JINGLE_STATUS_ACCEPTED)) {
1036            connect();
1037        }
1038        this.sendJinglePacket(packet);
1039    }
1040
1041    private void sendCandidateError() {
1042        Log.d(Config.LOGTAG, "sending candidate error");
1043        JinglePacket packet = bootstrapPacket("transport-info");
1044        Content content = new Content(this.contentCreator, this.contentName);
1045        content.setTransportId(this.transportId);
1046        content.socks5transport().addChild("candidate-error");
1047        packet.setContent(content);
1048        this.sentCandidate = true;
1049        this.sendJinglePacket(packet);
1050        if (receivedCandidate && mJingleStatus == JINGLE_STATUS_ACCEPTED) {
1051            connect();
1052        }
1053    }
1054
1055    public int getJingleStatus() {
1056        return this.mJingleStatus;
1057    }
1058
1059    private boolean equalCandidateExists(JingleCandidate candidate) {
1060        for (JingleCandidate c : this.candidates) {
1061            if (c.equalValues(candidate)) {
1062                return true;
1063            }
1064        }
1065        return false;
1066    }
1067
1068    private void mergeCandidate(JingleCandidate candidate) {
1069        for (JingleCandidate c : this.candidates) {
1070            if (c.equals(candidate)) {
1071                return;
1072            }
1073        }
1074        this.candidates.add(candidate);
1075    }
1076
1077    private void mergeCandidates(List<JingleCandidate> candidates) {
1078        for (JingleCandidate c : candidates) {
1079            mergeCandidate(c);
1080        }
1081    }
1082
1083    private JingleCandidate getCandidate(String cid) {
1084        for (JingleCandidate c : this.candidates) {
1085            if (c.getCid().equals(cid)) {
1086                return c;
1087            }
1088        }
1089        return null;
1090    }
1091
1092    void updateProgress(int i) {
1093        this.mProgress = i;
1094        mJingleConnectionManager.updateConversationUi(false);
1095    }
1096
1097    public String getTransportId() {
1098        return this.transportId;
1099    }
1100
1101    public Content.Version getFtVersion() {
1102        return this.ftVersion;
1103    }
1104
1105    public boolean hasTransportId(String sid) {
1106        return sid.equals(this.transportId);
1107    }
1108
1109    public JingleTransport getTransport() {
1110        return this.transport;
1111    }
1112
1113    public boolean start() {
1114        if (account.getStatus() == Account.State.ONLINE) {
1115            if (mJingleStatus == JINGLE_STATUS_INITIATED) {
1116                new Thread(this::sendAccept).start();
1117            }
1118            return true;
1119        } else {
1120            return false;
1121        }
1122    }
1123
1124    @Override
1125    public int getStatus() {
1126        return this.mStatus;
1127    }
1128
1129    @Override
1130    public long getFileSize() {
1131        if (this.file != null) {
1132            return this.file.getExpectedSize();
1133        } else {
1134            return 0;
1135        }
1136    }
1137
1138    @Override
1139    public int getProgress() {
1140        return this.mProgress;
1141    }
1142
1143    public AbstractConnectionManager getConnectionManager() {
1144        return this.mJingleConnectionManager;
1145    }
1146
1147    interface OnProxyActivated {
1148        void success();
1149
1150        void failed();
1151    }
1152}