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