JingleRtpConnection.java

  1package eu.siacs.conversations.xmpp.jingle;
  2
  3import android.os.SystemClock;
  4import android.util.Log;
  5
  6import com.google.common.base.Strings;
  7import com.google.common.collect.ImmutableList;
  8import com.google.common.collect.ImmutableMap;
  9import com.google.common.primitives.Ints;
 10
 11import org.webrtc.IceCandidate;
 12import org.webrtc.PeerConnection;
 13
 14import java.util.ArrayDeque;
 15import java.util.Arrays;
 16import java.util.Collection;
 17import java.util.Collections;
 18import java.util.List;
 19import java.util.Map;
 20
 21import eu.siacs.conversations.Config;
 22import eu.siacs.conversations.entities.Conversation;
 23import eu.siacs.conversations.entities.Conversational;
 24import eu.siacs.conversations.entities.Message;
 25import eu.siacs.conversations.entities.RtpSessionStatus;
 26import eu.siacs.conversations.xml.Element;
 27import eu.siacs.conversations.xml.Namespace;
 28import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
 29import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
 30import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
 31import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
 32import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 33import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 34import rocks.xmpp.addr.Jid;
 35
 36public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
 37
 38    public static final List<State> STATES_SHOWING_ONGOING_CALL = Arrays.asList(
 39            State.PROCEED,
 40            State.SESSION_INITIALIZED,
 41            State.SESSION_INITIALIZED_PRE_APPROVED,
 42            State.SESSION_ACCEPTED
 43    );
 44
 45    private static final List<State> TERMINATED = Arrays.asList(
 46            State.TERMINATED_DECLINED_OR_BUSY,
 47            State.TERMINATED_CONNECTIVITY_ERROR,
 48            State.TERMINATED_CANCEL_OR_TIMEOUT,
 49            State.TERMINATED_APPLICATION_FAILURE
 50    );
 51
 52    private static final Map<State, Collection<State>> VALID_TRANSITIONS;
 53
 54    static {
 55        final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
 56        transitionBuilder.put(State.NULL, ImmutableList.of(
 57                State.PROPOSED,
 58                State.SESSION_INITIALIZED,
 59                State.TERMINATED_APPLICATION_FAILURE
 60        ));
 61        transitionBuilder.put(State.PROPOSED, ImmutableList.of(
 62                State.ACCEPTED,
 63                State.PROCEED,
 64                State.REJECTED,
 65                State.RETRACTED,
 66                State.TERMINATED_APPLICATION_FAILURE
 67        ));
 68        transitionBuilder.put(State.PROCEED, ImmutableList.of(
 69                State.SESSION_INITIALIZED_PRE_APPROVED,
 70                State.TERMINATED_SUCCESS,
 71                State.TERMINATED_APPLICATION_FAILURE,
 72                State.TERMINATED_CONNECTIVITY_ERROR //at this state used for error bounces of the proceed message
 73        ));
 74        transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(
 75                State.SESSION_ACCEPTED,
 76                State.TERMINATED_SUCCESS,
 77                State.TERMINATED_DECLINED_OR_BUSY,
 78                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 79                State.TERMINATED_CANCEL_OR_TIMEOUT,
 80                State.TERMINATED_APPLICATION_FAILURE
 81        ));
 82        transitionBuilder.put(State.SESSION_INITIALIZED_PRE_APPROVED, ImmutableList.of(
 83                State.SESSION_ACCEPTED,
 84                State.TERMINATED_SUCCESS,
 85                State.TERMINATED_DECLINED_OR_BUSY,
 86                State.TERMINATED_CONNECTIVITY_ERROR,  //at this state used for IQ errors and IQ timeouts
 87                State.TERMINATED_CANCEL_OR_TIMEOUT,
 88                State.TERMINATED_APPLICATION_FAILURE
 89        ));
 90        transitionBuilder.put(State.SESSION_ACCEPTED, ImmutableList.of(
 91                State.TERMINATED_SUCCESS,
 92                State.TERMINATED_DECLINED_OR_BUSY,
 93                State.TERMINATED_CONNECTIVITY_ERROR,
 94                State.TERMINATED_CANCEL_OR_TIMEOUT,
 95                State.TERMINATED_APPLICATION_FAILURE
 96        ));
 97        VALID_TRANSITIONS = transitionBuilder.build();
 98    }
 99
100    private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
101    private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
102    private final Message message;
103    private State state = State.NULL;
104    private RtpContentMap initiatorRtpContentMap;
105    private RtpContentMap responderRtpContentMap;
106    private long rtpConnectionStarted = 0; //time of 'connected'
107
108
109    JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
110        super(jingleConnectionManager, id, initiator);
111        final Conversation conversation = jingleConnectionManager.getXmppConnectionService().findOrCreateConversation(
112                id.account,
113                id.with.asBareJid(),
114                false,
115                false
116        );
117        this.message = new Message(
118                conversation,
119                isInitiator() ? Message.STATUS_SEND : Message.STATUS_RECEIVED,
120                Message.TYPE_RTP_SESSION,
121                id.sessionId
122        );
123    }
124
125    private static State reasonToState(Reason reason) {
126        switch (reason) {
127            case SUCCESS:
128                return State.TERMINATED_SUCCESS;
129            case DECLINE:
130            case BUSY:
131                return State.TERMINATED_DECLINED_OR_BUSY;
132            case CANCEL:
133            case TIMEOUT:
134                return State.TERMINATED_CANCEL_OR_TIMEOUT;
135            case FAILED_APPLICATION:
136                return State.TERMINATED_APPLICATION_FAILURE;
137            default:
138                return State.TERMINATED_CONNECTIVITY_ERROR;
139        }
140    }
141
142    @Override
143    void deliverPacket(final JinglePacket jinglePacket) {
144        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
145        switch (jinglePacket.getAction()) {
146            case SESSION_INITIATE:
147                receiveSessionInitiate(jinglePacket);
148                break;
149            case TRANSPORT_INFO:
150                receiveTransportInfo(jinglePacket);
151                break;
152            case SESSION_ACCEPT:
153                receiveSessionAccept(jinglePacket);
154                break;
155            case SESSION_TERMINATE:
156                receiveSessionTerminate(jinglePacket);
157                break;
158            default:
159                respondOk(jinglePacket);
160                Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
161                break;
162        }
163    }
164
165    private void receiveSessionTerminate(final JinglePacket jinglePacket) {
166        respondOk(jinglePacket);
167        final JinglePacket.ReasonWrapper wrapper = jinglePacket.getReason();
168        final State previous = this.state;
169        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received session terminate reason=" + wrapper.reason + "(" + Strings.nullToEmpty(wrapper.text) + ") while in state " + previous);
170        if (TERMINATED.contains(previous)) {
171            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring session terminate because already in " + previous);
172            return;
173        }
174        webRTCWrapper.close();
175        final State target = reasonToState(wrapper.reason);
176        transitionOrThrow(target);
177        writeLogMessage(target);
178        if (previous == State.PROPOSED || previous == State.SESSION_INITIALIZED) {
179            xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
180        }
181        jingleConnectionManager.finishConnection(this);
182    }
183
184    private void receiveTransportInfo(final JinglePacket jinglePacket) {
185        if (isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
186            respondOk(jinglePacket);
187            final RtpContentMap contentMap;
188            try {
189                contentMap = RtpContentMap.of(jinglePacket);
190            } catch (IllegalArgumentException | NullPointerException e) {
191                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents; ignoring", e);
192                return;
193            }
194            final RtpContentMap rtpContentMap = isInitiator() ? this.responderRtpContentMap : this.initiatorRtpContentMap;
195            final Group originalGroup = rtpContentMap != null ? rtpContentMap.group : null;
196            final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
197            if (identificationTags.size() == 0) {
198                Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
199            }
200            for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
201                final String ufrag = content.getValue().transport.getAttribute("ufrag");
202                for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
203                    final String sdp = candidate.toSdpAttribute(ufrag);
204                    final String sdpMid = content.getKey();
205                    final int mLineIndex = identificationTags.indexOf(sdpMid);
206                    final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
207                    if (isInState(State.SESSION_ACCEPTED)) {
208                        Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
209                        this.webRTCWrapper.addIceCandidate(iceCandidate);
210                    } else {
211                        this.pendingIceCandidates.offer(iceCandidate);
212                        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": put ICE candidate on backlog");
213                    }
214                }
215            }
216        } else {
217            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
218            terminateWithOutOfOrder(jinglePacket);
219        }
220    }
221
222    private void receiveSessionInitiate(final JinglePacket jinglePacket) {
223        if (isInitiator()) {
224            Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
225            terminateWithOutOfOrder(jinglePacket);
226            return;
227        }
228        final RtpContentMap contentMap;
229        try {
230            contentMap = RtpContentMap.of(jinglePacket);
231            contentMap.requireContentDescriptions();
232            contentMap.requireDTLSFingerprint();
233        } catch (final IllegalArgumentException | IllegalStateException | NullPointerException e) {
234            respondOk(jinglePacket);
235            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
236            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
237            return;
238        }
239        Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
240        final State target;
241        if (this.state == State.PROCEED) {
242            target = State.SESSION_INITIALIZED_PRE_APPROVED;
243        } else {
244            target = State.SESSION_INITIALIZED;
245        }
246        if (transition(target)) {
247            respondOk(jinglePacket);
248            this.initiatorRtpContentMap = contentMap;
249            if (target == State.SESSION_INITIALIZED_PRE_APPROVED) {
250                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": automatically accepting session-initiate");
251                sendSessionAccept();
252            } else {
253                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received not pre-approved session-initiate. start ringing");
254                startRinging();
255            }
256        } else {
257            Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
258            terminateWithOutOfOrder(jinglePacket);
259        }
260    }
261
262    private void receiveSessionAccept(final JinglePacket jinglePacket) {
263        if (!isInitiator()) {
264            Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
265            terminateWithOutOfOrder(jinglePacket);
266            return;
267        }
268        final RtpContentMap contentMap;
269        try {
270            contentMap = RtpContentMap.of(jinglePacket);
271            contentMap.requireContentDescriptions();
272            contentMap.requireDTLSFingerprint();
273        } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
274            respondOk(jinglePacket);
275            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents in session-accept", e);
276            webRTCWrapper.close();
277            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
278            return;
279        }
280        Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
281        if (transition(State.SESSION_ACCEPTED)) {
282            respondOk(jinglePacket);
283            receiveSessionAccept(contentMap);
284        } else {
285            Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
286            respondOk(jinglePacket);
287        }
288    }
289
290    private void receiveSessionAccept(final RtpContentMap contentMap) {
291        this.responderRtpContentMap = contentMap;
292        final SessionDescription sessionDescription;
293        try {
294            sessionDescription = SessionDescription.of(contentMap);
295        } catch (final IllegalArgumentException | NullPointerException e) {
296            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-accept to SDP", e);
297            webRTCWrapper.close();
298            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
299            return;
300        }
301        org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
302                org.webrtc.SessionDescription.Type.ANSWER,
303                sessionDescription.toString()
304        );
305        try {
306            this.webRTCWrapper.setRemoteDescription(answer).get();
307        } catch (Exception e) {
308            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to set remote description after receiving session-accept", e);
309            webRTCWrapper.close();
310            sendSessionTerminate(Reason.FAILED_APPLICATION);
311        }
312    }
313
314    private void sendSessionAccept() {
315        final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
316        if (rtpContentMap == null) {
317            throw new IllegalStateException("initiator RTP Content Map has not been set");
318        }
319        final SessionDescription offer;
320        try {
321            offer = SessionDescription.of(rtpContentMap);
322        } catch (final IllegalArgumentException | NullPointerException e) {
323            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable convert offer from session-initiate to SDP", e);
324            webRTCWrapper.close();
325            sendSessionTerminate(Reason.FAILED_APPLICATION, e.getMessage());
326            return;
327        }
328        sendSessionAccept(offer);
329    }
330
331    private void sendSessionAccept(SessionDescription offer) {
332        discoverIceServers(iceServers -> {
333            try {
334                setupWebRTC(iceServers);
335            } catch (WebRTCWrapper.InitializationException e) {
336                sendSessionTerminate(Reason.FAILED_APPLICATION);
337                return;
338            }
339            final org.webrtc.SessionDescription sdp = new org.webrtc.SessionDescription(
340                    org.webrtc.SessionDescription.Type.OFFER,
341                    offer.toString()
342            );
343            try {
344                this.webRTCWrapper.setRemoteDescription(sdp).get();
345                addIceCandidatesFromBlackLog();
346                org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
347                final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
348                final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
349                sendSessionAccept(respondingRtpContentMap);
350                this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
351            } catch (Exception e) {
352                Log.d(Config.LOGTAG, "unable to send session accept", e);
353
354            }
355        });
356    }
357
358    private void addIceCandidatesFromBlackLog() {
359        while (!this.pendingIceCandidates.isEmpty()) {
360            final IceCandidate iceCandidate = this.pendingIceCandidates.poll();
361            this.webRTCWrapper.addIceCandidate(iceCandidate);
362            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": added ICE candidate from back log " + iceCandidate);
363        }
364    }
365
366    private void sendSessionAccept(final RtpContentMap rtpContentMap) {
367        this.responderRtpContentMap = rtpContentMap;
368        this.transitionOrThrow(State.SESSION_ACCEPTED);
369        final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
370        Log.d(Config.LOGTAG, sessionAccept.toString());
371        send(sessionAccept);
372    }
373
374    void deliveryMessage(final Jid from, final Element message) {
375        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
376        switch (message.getName()) {
377            case "propose":
378                receivePropose(from, message);
379                break;
380            case "proceed":
381                receiveProceed(from, message);
382                break;
383            case "retract":
384                receiveRetract(from, message);
385                break;
386            case "reject":
387                receiveReject(from, message);
388                break;
389            case "accept":
390                receiveAccept(from, message);
391                break;
392            default:
393                break;
394        }
395    }
396
397    void deliverFailedProceed() {
398        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": receive message error for proceed message");
399        if (transition(State.TERMINATED_CONNECTIVITY_ERROR)) {
400            webRTCWrapper.close();
401            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into connectivity error");
402            this.jingleConnectionManager.finishConnection(this);
403        }
404    }
405
406    private void receiveAccept(Jid from, Element message) {
407        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
408        if (originatedFromMyself) {
409            if (transition(State.ACCEPTED)) {
410                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
411                this.jingleConnectionManager.finishConnection(this);
412            } else {
413                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
414            }
415        } else {
416            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
417        }
418    }
419
420    private void receiveReject(Jid from, Element message) {
421        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
422        //reject from another one of my clients
423        if (originatedFromMyself) {
424            if (transition(State.REJECTED)) {
425                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
426                this.jingleConnectionManager.finishConnection(this);
427            } else {
428                Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
429            }
430        } else {
431            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
432        }
433    }
434
435    private void receivePropose(final Jid from, final Element propose) {
436        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
437        //TODO we can use initiator logic here
438        if (originatedFromMyself) {
439            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
440        } else if (transition(State.PROPOSED)) {
441            startRinging();
442        } else {
443            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
444        }
445    }
446
447    private void startRinging() {
448        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
449        xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
450    }
451
452    private void receiveProceed(final Jid from, final Element proceed) {
453        if (from.equals(id.with)) {
454            if (isInitiator()) {
455                if (transition(State.PROCEED)) {
456                    this.sendSessionInitiate(State.SESSION_INITIALIZED_PRE_APPROVED);
457                } else {
458                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
459                }
460            } else {
461                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
462            }
463        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
464            if (transition(State.ACCEPTED)) {
465                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
466                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
467                this.jingleConnectionManager.finishConnection(this);
468            }
469        } else {
470            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
471        }
472    }
473
474    private void receiveRetract(final Jid from, final Element retract) {
475        if (from.equals(id.with)) {
476            if (transition(State.RETRACTED)) {
477                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
478                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
479                writeLogMessageMissed();
480                jingleConnectionManager.finishConnection(this);
481            } else {
482                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
483            }
484        } else {
485            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
486        }
487    }
488
489    private void sendSessionInitiate(final State targetState) {
490        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
491        discoverIceServers(iceServers -> {
492            try {
493                setupWebRTC(iceServers);
494            } catch (WebRTCWrapper.InitializationException e) {
495                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize webrtc");
496                transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
497                return;
498            }
499            try {
500                org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
501                final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
502                Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
503                final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
504                sendSessionInitiate(rtpContentMap, targetState);
505                this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
506            } catch (final Exception e) {
507                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", e);
508                webRTCWrapper.close();
509                if (isInState(targetState)) {
510                    sendSessionTerminate(Reason.FAILED_APPLICATION);
511                } else {
512                    transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
513                }
514            }
515        });
516    }
517
518    private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
519        this.initiatorRtpContentMap = rtpContentMap;
520        this.transitionOrThrow(targetState);
521        final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
522        Log.d(Config.LOGTAG, sessionInitiate.toString());
523        send(sessionInitiate);
524    }
525
526    private void sendSessionTerminate(final Reason reason) {
527        sendSessionTerminate(reason, null);
528    }
529
530    private void sendSessionTerminate(final Reason reason, final String text) {
531        final State target = reasonToState(reason);
532        transitionOrThrow(target);
533        writeLogMessage(target);
534        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
535        jinglePacket.setReason(reason, text);
536        send(jinglePacket);
537        Log.d(Config.LOGTAG, jinglePacket.toString());
538        jingleConnectionManager.finishConnection(this);
539    }
540
541    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
542        final RtpContentMap transportInfo;
543        try {
544            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
545            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
546        } catch (Exception e) {
547            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
548            return;
549        }
550        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
551        Log.d(Config.LOGTAG, jinglePacket.toString());
552        send(jinglePacket);
553    }
554
555    private void send(final JinglePacket jinglePacket) {
556        jinglePacket.setTo(id.with);
557        xmppConnectionService.sendIqPacket(id.account, jinglePacket, (account, response) -> {
558            if (response.getType() == IqPacket.TYPE.ERROR) {
559                final String errorCondition = response.getErrorCondition();
560                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
561                this.webRTCWrapper.close();
562                final State target;
563                if (Arrays.asList(
564                        "service-unavailable",
565                        "recipient-unavailable",
566                        "remote-server-not-found",
567                        "remote-server-timeout"
568                ).contains(errorCondition)) {
569                    target = State.TERMINATED_CONNECTIVITY_ERROR;
570                } else {
571                    target = State.TERMINATED_APPLICATION_FAILURE;
572                }
573                if (transition(target)) {
574                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminated session with " + id.with);
575                } else {
576                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not transitioning because already at state=" + this.state);
577                }
578
579            } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
580                this.webRTCWrapper.close();
581                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
582                transition(State.TERMINATED_CONNECTIVITY_ERROR);
583                this.jingleConnectionManager.finishConnection(this);
584            }
585        });
586    }
587
588    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
589        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
590        webRTCWrapper.close();
591        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
592        respondWithOutOfOrder(jinglePacket);
593        jingleConnectionManager.finishConnection(this);
594    }
595
596    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
597        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
598    }
599
600    private void respondOk(final JinglePacket jinglePacket) {
601        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
602    }
603
604    public RtpEndUserState getEndUserState() {
605        switch (this.state) {
606            case PROPOSED:
607            case SESSION_INITIALIZED:
608                if (isInitiator()) {
609                    return RtpEndUserState.RINGING;
610                } else {
611                    return RtpEndUserState.INCOMING_CALL;
612                }
613            case PROCEED:
614                if (isInitiator()) {
615                    return RtpEndUserState.RINGING;
616                } else {
617                    return RtpEndUserState.ACCEPTING_CALL;
618                }
619            case SESSION_INITIALIZED_PRE_APPROVED:
620                if (isInitiator()) {
621                    return RtpEndUserState.RINGING;
622                } else {
623                    return RtpEndUserState.CONNECTING;
624                }
625            case SESSION_ACCEPTED:
626                final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
627                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
628                    return RtpEndUserState.CONNECTED;
629                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
630                    return RtpEndUserState.CONNECTING;
631                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
632                    return RtpEndUserState.ENDING_CALL;
633                } else if (state == PeerConnection.PeerConnectionState.FAILED) {
634                    return RtpEndUserState.CONNECTIVITY_ERROR;
635                } else {
636                    return RtpEndUserState.ENDING_CALL;
637                }
638            case REJECTED:
639            case TERMINATED_DECLINED_OR_BUSY:
640                if (isInitiator()) {
641                    return RtpEndUserState.DECLINED_OR_BUSY;
642                } else {
643                    return RtpEndUserState.ENDED;
644                }
645            case TERMINATED_SUCCESS:
646            case ACCEPTED:
647            case RETRACTED:
648            case TERMINATED_CANCEL_OR_TIMEOUT:
649                return RtpEndUserState.ENDED;
650            case TERMINATED_CONNECTIVITY_ERROR:
651                return RtpEndUserState.CONNECTIVITY_ERROR;
652            case TERMINATED_APPLICATION_FAILURE:
653                return RtpEndUserState.APPLICATION_ERROR;
654        }
655        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
656    }
657
658
659    public void acceptCall() {
660        switch (this.state) {
661            case PROPOSED:
662                acceptCallFromProposed();
663                break;
664            case SESSION_INITIALIZED:
665                acceptCallFromSessionInitialized();
666                break;
667            default:
668                throw new IllegalStateException("Can not accept call from " + this.state);
669        }
670    }
671
672    public void rejectCall() {
673        switch (this.state) {
674            case PROPOSED:
675                rejectCallFromProposed();
676                break;
677            case SESSION_INITIALIZED:
678                rejectCallFromSessionInitiate();
679                break;
680            default:
681                throw new IllegalStateException("Can not reject call from " + this.state);
682        }
683    }
684
685    public void endCall() {
686        if (isInState(State.PROPOSED) && !isInitiator()) {
687            rejectCallFromProposed();
688            return;
689        }
690        if (isInState(State.PROCEED)) {
691            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
692            webRTCWrapper.close();
693            jingleConnectionManager.finishConnection(this);
694            transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
695            return;
696        }
697        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
698            webRTCWrapper.close();
699            sendSessionTerminate(Reason.CANCEL);
700            return;
701        }
702        if (isInState(State.SESSION_INITIALIZED)) {
703            rejectCallFromSessionInitiate();
704            return;
705        }
706        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
707            webRTCWrapper.close();
708            sendSessionTerminate(Reason.SUCCESS);
709            return;
710        }
711        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
712            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
713            return;
714        }
715        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
716    }
717
718    private void setupWebRTC(final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
719        this.webRTCWrapper.setup(this.xmppConnectionService);
720        this.webRTCWrapper.initializePeerConnection(iceServers);
721    }
722
723    private void acceptCallFromProposed() {
724        transitionOrThrow(State.PROCEED);
725        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
726        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
727        this.sendJingleMessage("proceed");
728    }
729
730    private void rejectCallFromProposed() {
731        transitionOrThrow(State.REJECTED);
732        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
733        this.sendJingleMessage("reject");
734        jingleConnectionManager.finishConnection(this);
735    }
736
737    private void rejectCallFromSessionInitiate() {
738        webRTCWrapper.close();
739        sendSessionTerminate(Reason.DECLINE);
740        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
741    }
742
743    private void sendJingleMessage(final String action) {
744        sendJingleMessage(action, id.with);
745    }
746
747    private void sendJingleMessage(final String action, final Jid to) {
748        final MessagePacket messagePacket = new MessagePacket();
749        if ("proceed".equals(action)) {
750            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
751        }
752        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
753        messagePacket.setTo(to);
754        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
755        Log.d(Config.LOGTAG, messagePacket.toString());
756        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
757    }
758
759    private void acceptCallFromSessionInitialized() {
760        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
761        sendSessionAccept();
762    }
763
764    private synchronized boolean isInState(State... state) {
765        return Arrays.asList(state).contains(this.state);
766    }
767
768    private synchronized boolean transition(final State target) {
769        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
770        if (validTransitions != null && validTransitions.contains(target)) {
771            this.state = target;
772            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
773            updateEndUserState();
774            updateOngoingCallNotification();
775            return true;
776        } else {
777            return false;
778        }
779    }
780
781    public void transitionOrThrow(final State target) {
782        if (!transition(target)) {
783            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
784        }
785    }
786
787    @Override
788    public void onIceCandidate(final IceCandidate iceCandidate) {
789        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
790        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
791        sendTransportInfo(iceCandidate.sdpMid, candidate);
792    }
793
794    @Override
795    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
796        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
797        updateEndUserState();
798        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
799            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
800        }
801        if (newState == PeerConnection.PeerConnectionState.FAILED) {
802            if (TERMINATED.contains(this.state)) {
803                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
804                return;
805            }
806            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
807        }
808    }
809
810    private void updateEndUserState() {
811        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
812    }
813
814    private void updateOngoingCallNotification() {
815        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
816            xmppConnectionService.setOngoingCall(id);
817        } else {
818            xmppConnectionService.removeOngoingCall(id);
819        }
820    }
821
822    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
823        if (id.account.getXmppConnection().getFeatures().extendedServiceDiscovery()) {
824            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
825            request.setTo(Jid.of(id.account.getJid().getDomain()));
826            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
827            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
828                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
829                if (response.getType() == IqPacket.TYPE.RESULT) {
830                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
831                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
832                    for (final Element child : children) {
833                        if ("service".equals(child.getName())) {
834                            final String type = child.getAttribute("type");
835                            final String host = child.getAttribute("host");
836                            final String sport = child.getAttribute("port");
837                            final Integer port = sport == null ? null : Ints.tryParse(sport);
838                            final String transport = child.getAttribute("transport");
839                            final String username = child.getAttribute("username");
840                            final String password = child.getAttribute("password");
841                            if (Strings.isNullOrEmpty(host) || port == null) {
842                                continue;
843                            }
844                            if (port < 0 || port > 65535) {
845                                continue;
846                            }
847                            if (Arrays.asList("stun", "turn").contains(type) || Arrays.asList("udp", "tcp").contains(transport)) {
848                                //TODO wrap ipv6 addresses
849                                PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
850                                if (username != null && password != null) {
851                                    iceServerBuilder.setUsername(username);
852                                    iceServerBuilder.setPassword(password);
853                                } else if (Arrays.asList("turn", "turns").contains(type)) {
854                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
855                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
856                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
857                                    continue;
858                                }
859                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
860                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
861                                listBuilder.add(iceServer);
862                            }
863                        }
864                    }
865                }
866                List<PeerConnection.IceServer> iceServers = listBuilder.build();
867                if (iceServers.size() == 0) {
868                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
869                }
870                onIceServersDiscovered.onIceServersDiscovered(iceServers);
871            });
872        } else {
873            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
874            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
875        }
876    }
877
878    private void writeLogMessage(final State state) {
879        final long started = this.rtpConnectionStarted;
880        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
881        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
882            writeLogMessageSuccess(duration);
883        } else {
884            writeLogMessageMissed();
885        }
886    }
887
888    private void writeLogMessageSuccess(final long duration) {
889        this.message.setBody(new RtpSessionStatus(true, duration).toString());
890        this.writeMessage();
891    }
892
893    private void writeLogMessageMissed() {
894        this.message.setBody(new RtpSessionStatus(false,0).toString());
895        this.writeMessage();
896    }
897
898    private void writeMessage() {
899        final Conversational conversational = message.getConversation();
900        if (conversational instanceof Conversation) {
901            ((Conversation) conversational).add(this.message);
902            xmppConnectionService.databaseBackend.createMessage(message);
903            xmppConnectionService.updateConversationUi();
904        } else {
905            throw new IllegalStateException("Somehow the conversation in a message was a stub");
906        }
907    }
908
909    public State getState() {
910        return this.state;
911    }
912
913    private interface OnIceServersDiscovered {
914        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
915    }
916}