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, final String serverMessageId, final long timestamp) {
375        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
376        switch (message.getName()) {
377            case "propose":
378                receivePropose(from, serverMessageId, timestamp);
379                break;
380            case "proceed":
381                receiveProceed(from, serverMessageId, timestamp);
382                break;
383            case "retract":
384                receiveRetract(from, serverMessageId, timestamp);
385                break;
386            case "reject":
387                receiveReject(from, serverMessageId, timestamp);
388                break;
389            case "accept":
390                receiveAccept(from, serverMessageId, timestamp);
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(final Jid from, final String serverMsgId, final long timestamp) {
407        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
408        if (originatedFromMyself) {
409            if (transition(State.ACCEPTED)) {
410                if (serverMsgId != null) {
411                    this.message.setServerMsgId(serverMsgId);
412                }
413                this.message.setTime(timestamp);
414                this.message.setCarbon(true); //indicate that call was accepted on other device
415                this.writeLogMessageSuccess(0);
416                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
417                this.jingleConnectionManager.finishConnection(this);
418            } else {
419                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to transition to accept because already in state=" + this.state);
420            }
421        } else {
422            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ignoring 'accept' from " + from);
423        }
424    }
425
426    private void receiveReject(Jid from, String serverMsgId, long timestamp) {
427        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
428        //reject from another one of my clients
429        if (originatedFromMyself) {
430            if (transition(State.REJECTED)) {
431                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
432                this.jingleConnectionManager.finishConnection(this);
433                if (serverMsgId != null) {
434                    this.message.setServerMsgId(serverMsgId);
435                }
436                this.message.setTime(timestamp);
437                this.message.setCarbon(true); //indicate that call was rejected on other device
438                writeLogMessageMissed();
439            } else {
440                Log.d(Config.LOGTAG, "not able to transition into REJECTED because already in " + this.state);
441            }
442        } else {
443            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring reject from " + from + " for session with " + id.with);
444        }
445    }
446
447    private void receivePropose(final Jid from, final String serverMsgId, final long timestamp) {
448        final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
449        if (originatedFromMyself) {
450            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
451        } else if (transition(State.PROPOSED)) {
452            if (serverMsgId != null) {
453                this.message.setServerMsgId(serverMsgId);
454            }
455            this.message.setTime(timestamp);
456            startRinging();
457        } else {
458            Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
459        }
460    }
461
462    private void startRinging() {
463        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
464        xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
465    }
466
467    private void receiveProceed(final Jid from, final String serverMsgId, final long timestamp) {
468        if (from.equals(id.with)) {
469            if (isInitiator()) {
470                if (transition(State.PROCEED)) {
471                    if (serverMsgId != null) {
472                        this.message.setServerMsgId(serverMsgId);
473                    }
474                    this.message.setTime(timestamp);
475                    this.sendSessionInitiate(State.SESSION_INITIALIZED_PRE_APPROVED);
476                } else {
477                    Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
478                }
479            } else {
480                Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
481            }
482        } else if (from.asBareJid().equals(id.account.getJid().asBareJid())) {
483            if (transition(State.ACCEPTED)) {
484                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": moved session with " + id.with + " into state accepted after received carbon copied procced");
485                this.xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
486                this.jingleConnectionManager.finishConnection(this);
487            }
488        } else {
489            Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
490        }
491    }
492
493    private void receiveRetract(final Jid from, final String serverMsgId, final long timestamp) {
494        if (from.equals(id.with)) {
495            if (transition(State.RETRACTED)) {
496                xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
497                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
498                if (serverMsgId != null) {
499                    this.message.setServerMsgId(serverMsgId);
500                }
501                this.message.setTime(timestamp);
502                writeLogMessageMissed();
503                jingleConnectionManager.finishConnection(this);
504            } else {
505                Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
506            }
507        } else {
508            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
509        }
510    }
511
512    private void sendSessionInitiate(final State targetState) {
513        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
514        discoverIceServers(iceServers -> {
515            try {
516                setupWebRTC(iceServers);
517            } catch (WebRTCWrapper.InitializationException e) {
518                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to initialize webrtc");
519                transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
520                return;
521            }
522            try {
523                org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
524                final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
525                Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
526                final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
527                sendSessionInitiate(rtpContentMap, targetState);
528                this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
529            } catch (final Exception e) {
530                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to sendSessionInitiate", e);
531                webRTCWrapper.close();
532                if (isInState(targetState)) {
533                    sendSessionTerminate(Reason.FAILED_APPLICATION);
534                } else {
535                    transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
536                }
537            }
538        });
539    }
540
541    private void sendSessionInitiate(RtpContentMap rtpContentMap, final State targetState) {
542        this.initiatorRtpContentMap = rtpContentMap;
543        this.transitionOrThrow(targetState);
544        final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
545        Log.d(Config.LOGTAG, sessionInitiate.toString());
546        send(sessionInitiate);
547    }
548
549    private void sendSessionTerminate(final Reason reason) {
550        sendSessionTerminate(reason, null);
551    }
552
553    private void sendSessionTerminate(final Reason reason, final String text) {
554        final State target = reasonToState(reason);
555        transitionOrThrow(target);
556        writeLogMessage(target);
557        final JinglePacket jinglePacket = new JinglePacket(JinglePacket.Action.SESSION_TERMINATE, id.sessionId);
558        jinglePacket.setReason(reason, text);
559        send(jinglePacket);
560        Log.d(Config.LOGTAG, jinglePacket.toString());
561        jingleConnectionManager.finishConnection(this);
562    }
563
564    private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
565        final RtpContentMap transportInfo;
566        try {
567            final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
568            transportInfo = rtpContentMap.transportInfo(contentName, candidate);
569        } catch (Exception e) {
570            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
571            return;
572        }
573        final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
574        Log.d(Config.LOGTAG, jinglePacket.toString());
575        send(jinglePacket);
576    }
577
578    private void send(final JinglePacket jinglePacket) {
579        jinglePacket.setTo(id.with);
580        xmppConnectionService.sendIqPacket(id.account, jinglePacket, (account, response) -> {
581            if (response.getType() == IqPacket.TYPE.ERROR) {
582                final String errorCondition = response.getErrorCondition();
583                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ-error from " + response.getFrom() + " in RTP session. " + errorCondition);
584                this.webRTCWrapper.close();
585                final State target;
586                if (Arrays.asList(
587                        "service-unavailable",
588                        "recipient-unavailable",
589                        "remote-server-not-found",
590                        "remote-server-timeout"
591                ).contains(errorCondition)) {
592                    target = State.TERMINATED_CONNECTIVITY_ERROR;
593                } else {
594                    target = State.TERMINATED_APPLICATION_FAILURE;
595                }
596                if (transition(target)) {
597                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminated session with " + id.with);
598                } else {
599                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not transitioning because already at state=" + this.state);
600                }
601
602            } else if (response.getType() == IqPacket.TYPE.TIMEOUT) {
603                this.webRTCWrapper.close();
604                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received IQ timeout in RTP session with " + id.with + ". terminating with connectivity error");
605                transition(State.TERMINATED_CONNECTIVITY_ERROR);
606                this.jingleConnectionManager.finishConnection(this);
607            }
608        });
609    }
610
611    private void terminateWithOutOfOrder(final JinglePacket jinglePacket) {
612        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": terminating session with out-of-order");
613        webRTCWrapper.close();
614        transitionOrThrow(State.TERMINATED_APPLICATION_FAILURE);
615        respondWithOutOfOrder(jinglePacket);
616        jingleConnectionManager.finishConnection(this);
617    }
618
619    private void respondWithOutOfOrder(final JinglePacket jinglePacket) {
620        jingleConnectionManager.respondWithJingleError(id.account, jinglePacket, "out-of-order", "unexpected-request", "wait");
621    }
622
623    private void respondOk(final JinglePacket jinglePacket) {
624        xmppConnectionService.sendIqPacket(id.account, jinglePacket.generateResponse(IqPacket.TYPE.RESULT), null);
625    }
626
627    public RtpEndUserState getEndUserState() {
628        switch (this.state) {
629            case PROPOSED:
630            case SESSION_INITIALIZED:
631                if (isInitiator()) {
632                    return RtpEndUserState.RINGING;
633                } else {
634                    return RtpEndUserState.INCOMING_CALL;
635                }
636            case PROCEED:
637                if (isInitiator()) {
638                    return RtpEndUserState.RINGING;
639                } else {
640                    return RtpEndUserState.ACCEPTING_CALL;
641                }
642            case SESSION_INITIALIZED_PRE_APPROVED:
643                if (isInitiator()) {
644                    return RtpEndUserState.RINGING;
645                } else {
646                    return RtpEndUserState.CONNECTING;
647                }
648            case SESSION_ACCEPTED:
649                final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
650                if (state == PeerConnection.PeerConnectionState.CONNECTED) {
651                    return RtpEndUserState.CONNECTED;
652                } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
653                    return RtpEndUserState.CONNECTING;
654                } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
655                    return RtpEndUserState.ENDING_CALL;
656                } else if (state == PeerConnection.PeerConnectionState.FAILED) {
657                    return RtpEndUserState.CONNECTIVITY_ERROR;
658                } else {
659                    return RtpEndUserState.ENDING_CALL;
660                }
661            case REJECTED:
662            case TERMINATED_DECLINED_OR_BUSY:
663                if (isInitiator()) {
664                    return RtpEndUserState.DECLINED_OR_BUSY;
665                } else {
666                    return RtpEndUserState.ENDED;
667                }
668            case TERMINATED_SUCCESS:
669            case ACCEPTED:
670            case RETRACTED:
671            case TERMINATED_CANCEL_OR_TIMEOUT:
672                return RtpEndUserState.ENDED;
673            case TERMINATED_CONNECTIVITY_ERROR:
674                return RtpEndUserState.CONNECTIVITY_ERROR;
675            case TERMINATED_APPLICATION_FAILURE:
676                return RtpEndUserState.APPLICATION_ERROR;
677        }
678        throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
679    }
680
681
682    public void acceptCall() {
683        switch (this.state) {
684            case PROPOSED:
685                acceptCallFromProposed();
686                break;
687            case SESSION_INITIALIZED:
688                acceptCallFromSessionInitialized();
689                break;
690            default:
691                throw new IllegalStateException("Can not accept call from " + this.state);
692        }
693    }
694
695    public void rejectCall() {
696        switch (this.state) {
697            case PROPOSED:
698                rejectCallFromProposed();
699                break;
700            case SESSION_INITIALIZED:
701                rejectCallFromSessionInitiate();
702                break;
703            default:
704                throw new IllegalStateException("Can not reject call from " + this.state);
705        }
706    }
707
708    public void endCall() {
709        if (isInState(State.PROPOSED) && !isInitiator()) {
710            rejectCallFromProposed();
711            return;
712        }
713        if (isInState(State.PROCEED)) {
714            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": ending call while in state PROCEED just means ending the connection");
715            webRTCWrapper.close();
716            jingleConnectionManager.finishConnection(this);
717            transitionOrThrow(State.TERMINATED_SUCCESS); //arguably this wasn't success; but not a real failure either
718            return;
719        }
720        if (isInitiator() && isInState(State.SESSION_INITIALIZED, State.SESSION_INITIALIZED_PRE_APPROVED)) {
721            webRTCWrapper.close();
722            sendSessionTerminate(Reason.CANCEL);
723            return;
724        }
725        if (isInState(State.SESSION_INITIALIZED)) {
726            rejectCallFromSessionInitiate();
727            return;
728        }
729        if (isInState(State.SESSION_INITIALIZED_PRE_APPROVED, State.SESSION_ACCEPTED)) {
730            webRTCWrapper.close();
731            sendSessionTerminate(Reason.SUCCESS);
732            return;
733        }
734        if (isInState(State.TERMINATED_APPLICATION_FAILURE, State.TERMINATED_CONNECTIVITY_ERROR, State.TERMINATED_DECLINED_OR_BUSY)) {
735            Log.d(Config.LOGTAG, "ignoring request to end call because already in state " + this.state);
736            return;
737        }
738        throw new IllegalStateException("called 'endCall' while in state " + this.state + ". isInitiator=" + isInitiator());
739    }
740
741    private void setupWebRTC(final List<PeerConnection.IceServer> iceServers) throws WebRTCWrapper.InitializationException {
742        this.webRTCWrapper.setup(this.xmppConnectionService);
743        this.webRTCWrapper.initializePeerConnection(iceServers);
744    }
745
746    private void acceptCallFromProposed() {
747        transitionOrThrow(State.PROCEED);
748        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
749        this.sendJingleMessage("accept", id.account.getJid().asBareJid());
750        this.sendJingleMessage("proceed");
751    }
752
753    private void rejectCallFromProposed() {
754        transitionOrThrow(State.REJECTED);
755        writeLogMessageMissed();
756        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
757        this.sendJingleMessage("reject");
758        jingleConnectionManager.finishConnection(this);
759    }
760
761    private void rejectCallFromSessionInitiate() {
762        webRTCWrapper.close();
763        sendSessionTerminate(Reason.DECLINE);
764        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
765    }
766
767    private void sendJingleMessage(final String action) {
768        sendJingleMessage(action, id.with);
769    }
770
771    private void sendJingleMessage(final String action, final Jid to) {
772        final MessagePacket messagePacket = new MessagePacket();
773        if ("proceed".equals(action)) {
774            messagePacket.setId(JINGLE_MESSAGE_PROCEED_ID_PREFIX + id.sessionId);
775        }
776        messagePacket.setType(MessagePacket.TYPE_CHAT); //we want to carbon copy those
777        messagePacket.setTo(to);
778        messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
779        Log.d(Config.LOGTAG, messagePacket.toString());
780        xmppConnectionService.sendMessagePacket(id.account, messagePacket);
781    }
782
783    private void acceptCallFromSessionInitialized() {
784        xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
785        sendSessionAccept();
786    }
787
788    private synchronized boolean isInState(State... state) {
789        return Arrays.asList(state).contains(this.state);
790    }
791
792    private synchronized boolean transition(final State target) {
793        final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
794        if (validTransitions != null && validTransitions.contains(target)) {
795            this.state = target;
796            Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
797            updateEndUserState();
798            updateOngoingCallNotification();
799            return true;
800        } else {
801            return false;
802        }
803    }
804
805    public void transitionOrThrow(final State target) {
806        if (!transition(target)) {
807            throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
808        }
809    }
810
811    @Override
812    public void onIceCandidate(final IceCandidate iceCandidate) {
813        final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
814        Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
815        sendTransportInfo(iceCandidate.sdpMid, candidate);
816    }
817
818    @Override
819    public void onConnectionChange(final PeerConnection.PeerConnectionState newState) {
820        Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
821        updateEndUserState();
822        if (newState == PeerConnection.PeerConnectionState.CONNECTED && this.rtpConnectionStarted == 0) {
823            this.rtpConnectionStarted = SystemClock.elapsedRealtime();
824        }
825        if (newState == PeerConnection.PeerConnectionState.FAILED) {
826            if (TERMINATED.contains(this.state)) {
827                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": not sending session-terminate after connectivity error because session is already in state " + this.state);
828                return;
829            }
830            sendSessionTerminate(Reason.CONNECTIVITY_ERROR);
831        }
832    }
833
834    private void updateEndUserState() {
835        xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
836    }
837
838    private void updateOngoingCallNotification() {
839        if (STATES_SHOWING_ONGOING_CALL.contains(this.state)) {
840            xmppConnectionService.setOngoingCall(id);
841        } else {
842            xmppConnectionService.removeOngoingCall(id);
843        }
844    }
845
846    private void discoverIceServers(final OnIceServersDiscovered onIceServersDiscovered) {
847        if (id.account.getXmppConnection().getFeatures().extendedServiceDiscovery()) {
848            final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
849            request.setTo(Jid.of(id.account.getJid().getDomain()));
850            request.addChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
851            xmppConnectionService.sendIqPacket(id.account, request, (account, response) -> {
852                ImmutableList.Builder<PeerConnection.IceServer> listBuilder = new ImmutableList.Builder<>();
853                if (response.getType() == IqPacket.TYPE.RESULT) {
854                    final Element services = response.findChild("services", Namespace.EXTERNAL_SERVICE_DISCOVERY);
855                    final List<Element> children = services == null ? Collections.emptyList() : services.getChildren();
856                    for (final Element child : children) {
857                        if ("service".equals(child.getName())) {
858                            final String type = child.getAttribute("type");
859                            final String host = child.getAttribute("host");
860                            final String sport = child.getAttribute("port");
861                            final Integer port = sport == null ? null : Ints.tryParse(sport);
862                            final String transport = child.getAttribute("transport");
863                            final String username = child.getAttribute("username");
864                            final String password = child.getAttribute("password");
865                            if (Strings.isNullOrEmpty(host) || port == null) {
866                                continue;
867                            }
868                            if (port < 0 || port > 65535) {
869                                continue;
870                            }
871                            if (Arrays.asList("stun", "turn").contains(type) || Arrays.asList("udp", "tcp").contains(transport)) {
872                                //TODO wrap ipv6 addresses
873                                PeerConnection.IceServer.Builder iceServerBuilder = PeerConnection.IceServer.builder(String.format("%s:%s:%s?transport=%s", type, host, port, transport));
874                                if (username != null && password != null) {
875                                    iceServerBuilder.setUsername(username);
876                                    iceServerBuilder.setPassword(password);
877                                } else if (Arrays.asList("turn", "turns").contains(type)) {
878                                    //The WebRTC spec requires throwing an InvalidAccessError when username (from libwebrtc source coder)
879                                    //https://chromium.googlesource.com/external/webrtc/+/master/pc/ice_server_parsing.cc
880                                    Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": skipping " + type + "/" + transport + " without username and password");
881                                    continue;
882                                }
883                                final PeerConnection.IceServer iceServer = iceServerBuilder.createIceServer();
884                                Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": discovered ICE Server: " + iceServer);
885                                listBuilder.add(iceServer);
886                            }
887                        }
888                    }
889                }
890                List<PeerConnection.IceServer> iceServers = listBuilder.build();
891                if (iceServers.size() == 0) {
892                    Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no ICE server found " + response);
893                }
894                onIceServersDiscovered.onIceServersDiscovered(iceServers);
895            });
896        } else {
897            Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": has no external service discovery");
898            onIceServersDiscovered.onIceServersDiscovered(Collections.emptyList());
899        }
900    }
901
902    private void writeLogMessage(final State state) {
903        final long started = this.rtpConnectionStarted;
904        long duration = started <= 0 ? 0 : SystemClock.elapsedRealtime() - started;
905        if (state == State.TERMINATED_SUCCESS || (state == State.TERMINATED_CONNECTIVITY_ERROR && duration > 0)) {
906            writeLogMessageSuccess(duration);
907        } else {
908            writeLogMessageMissed();
909        }
910    }
911
912    private void writeLogMessageSuccess(final long duration) {
913        this.message.setBody(new RtpSessionStatus(true, duration).toString());
914        this.writeMessage();
915    }
916
917    private void writeLogMessageMissed() {
918        this.message.setBody(new RtpSessionStatus(false,0).toString());
919        this.writeMessage();
920    }
921
922    private void writeMessage() {
923        final Conversational conversational = message.getConversation();
924        if (conversational instanceof Conversation) {
925            ((Conversation) conversational).add(this.message);
926            xmppConnectionService.databaseBackend.createMessage(message);
927            xmppConnectionService.updateConversationUi();
928        } else {
929            throw new IllegalStateException("Somehow the conversation in a message was a stub");
930        }
931    }
932
933    public State getState() {
934        return this.state;
935    }
936
937    private interface OnIceServersDiscovered {
938        void onIceServersDiscovered(List<PeerConnection.IceServer> iceServers);
939    }
940}