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