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