sipsorcery-mono /sipsorcery-xmpp/SIPSorcery.XMPP/XMPPPhoneSession.cs

Language C# Lines 269
MD5 Hash 3b99c5693a7d3b7c6c0a3c36bc406982
Repository https://github.com/thecc4re/sipsorcery-mono.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//-----------------------------------------------------------------------------
// Filename: XMPPPhoneSession.cs
//
// Description: Represents the an XMPP session that operates on top of an authenticated
// XMPP stream and that negotiates a voice call.
// 
// History:
// 13 Dec 2010	Aaron Clauson	Created.
//
// License: 
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2010 Aaron Clauson (aaron@sipsorcery.com), Hobart, Tasmania, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that 
// the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following 
// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery. 
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific 
// prior written permission. 
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using SIPSorcery.Net;
using SIPSorcery.Sys;
using log4net;

namespace SIPSorcery.XMPP
{
    public class XMPPPhoneSession
    {
        private static ILog logger = AppState.logger;

        private static XNamespace m_sessionNS = XMPPStream.GOOGLE_SESSION_NAMESPACE;
        private static XNamespace m_phoneNS = XMPPStream.GOOGLE_PHONE_SESSION_NAMESPACE;
        private static XNamespace m_transportNS = XMPPStream.TRANSPORT_NAMESPACE;
        protected static XNamespace JabberClientNS = XMPPStream.JABBER_NAMESPACE;

        private string m_destination;
        private SDP m_sdp;
        private string m_jid;
        private XMPPAuthenticatedStream m_xmppStream;
        private string m_sessionID;

        // IQ id's.
        private string m_descriptionID;

        // Call response.
        private string m_remoteIPAddress;
        private int m_remotePort;
        private string m_remoteUsername;
        private string m_remotePassword;
        private List<XElement> m_payloads;

        public Action<SDP> Accepted;
        public Action Rejected;
        public Action Hungup;

        public XMPPPhoneSession(string jid, XMPPAuthenticatedStream xmppStream)
        {
            m_sessionID = Crypto.GetRandomString(6);
            m_jid = jid;
            m_xmppStream = xmppStream;
            m_xmppStream.RegisterSession(m_sessionID, OnIQRequest);
        }

        public void PlaceCall(string destination, SDP sdp)
        {
            m_destination = destination;
            m_sdp = sdp;

            XElement descriptionElement = SDPToJingle.GetDescription(m_sdp);

            m_descriptionID = Crypto.GetRandomString(6);

            XElement callElement = new XElement(JabberClientNS + "iq",
                                    new XAttribute("from", m_jid),
                                    new XAttribute("id", m_descriptionID),
                                    new XAttribute("to", m_destination),
                                    new XAttribute("type", "set"),
                                    new XElement(m_sessionNS + "session",
                                        new XAttribute("type", "initiate"),
                                        new XAttribute("id", m_sessionID),
                                        new XAttribute("initiator", m_jid),
                                        descriptionElement
                                        //new XElement(m_transportNS + "transport")
                                        ));

            logger.Debug("XMPPPhoneSession sending iq with session description.");
            m_xmppStream.WriteElement(callElement, OnIQResponse);
        }

        private void SendCandidates()
        {
            XElement candidatesElement = SDPToJingle.GetCandidates(m_sdp);

            string candidateIqID = Crypto.GetRandomString(6);

            XElement candElement = new XElement(JabberClientNS + "iq",
                                    new XAttribute("from", m_jid),
                                    new XAttribute("id", candidateIqID),
                                    new XAttribute("to", m_destination),
                                    new XAttribute("type", "set"),
                                    new XElement(m_sessionNS + "session",
                                        new XAttribute("type", "candidates"),
                                        new XAttribute("id", m_sessionID),
                                        new XAttribute("initiator", m_jid),
                                        candidatesElement));

            logger.Debug("XMPPPhoneSession sending iq with session candidate.");

            m_xmppStream.WriteElement(candElement, OnIQResponse);
        }

        public void RetargetCallMedia(string ipAddress, int port)
        {
            XElement candidateElement = SDPToJingle.GetCandidate(ipAddress, port);

            string candidateIqID = Crypto.GetRandomString(6);

            XElement candElement = new XElement(JabberClientNS + "iq",
                                    new XAttribute("from", m_jid),
                                    new XAttribute("id", candidateIqID),
                                    new XAttribute("to", m_destination),
                                    new XAttribute("type", "set"),
                                    new XElement(m_sessionNS + "session",
                                        new XAttribute("type", "candidates"),
                                        new XAttribute("id", m_sessionID),
                                        new XAttribute("initiator", m_jid),
                                        candidateElement));

            m_xmppStream.WriteElement(candElement, OnIQResponse);
        }

        public void TerminateCall()
        {
            string iqID = Crypto.GetRandomString(6);

            XElement cancelElement = new XElement(JabberClientNS + "iq",
                                    new XAttribute("from", m_jid),
                                    new XAttribute("id", iqID),
                                    new XAttribute("to", m_destination),
                                    new XAttribute("type", "set"),
                                    new XElement(m_sessionNS + "session",
                                        new XAttribute("type", "terminate"),
                                        new XAttribute("id", m_sessionID),
                                        new XAttribute("initiator", m_jid)));

            logger.Debug("XMPPPhoneSession sending iq to terminate session.");

            m_xmppStream.WriteElement(cancelElement, OnIQResponse);
        }

        /// <summary>
        /// Handler method for receiving responses to iq stanzas initiated by us.
        /// </summary>
        /// <param name="id">The id of the original iq request.</param>
        /// <param name="iq">The iq response stanza.</param>
        public void OnIQResponse(string id, XElement iq)
        {
            //Console.WriteLine("IQ received result for ID " + id + " => " + iq.ToString());
            // Send ok.
            //XAttribute sessionType = iq.Element(m_sessionNS + "session").Attribute("type");
            XAttribute iqType = iq.Attribute("type");

            logger.Debug("XMPPPhoneSession iq response, type=" + iqType.Value + ".");

            if (iqType.Value == "result")
            {
                string iqID = iq.Attribute("id").Value;

                if (iqID == m_descriptionID)
                {
                    SendCandidates();
                }
            }
            else if (iqType.Value == "error")
            {
                int errorCode = 0;
                Int32.TryParse(iq.Element(JabberClientNS + "error").Attribute("code").Value, out errorCode);

                if (errorCode >= 300 && errorCode <= 399)
                {
                    // Redirect.
                    string redirect = iq.Element(JabberClientNS + "error").Element(m_sessionNS + "redirect").Value;
                    m_destination = redirect.Replace("xmpp:", String.Empty);
                    PlaceCall(m_destination, m_sdp);
                }
                else
                {
                    Rejected();
                }
            }
        }

        /// <summary>
        /// Handler method for receiving iq requests from the remote server.
        /// </summary>
        /// <param name="iq">The iq stanza request received.</param>
        public void OnIQRequest(XElement iq)
        {
            logger.Debug("XMPPPhoneSession iq request, type=" + iq.Attribute("type").Value + ".");

            if (iq.Element(m_sessionNS + "session") != null)
            {
                XAttribute sessionType = iq.Element(m_sessionNS + "session").Attribute("type");

                if (sessionType != null)
                {
                    if (sessionType.Value == "candidates")
                    {
                        logger.Debug("XMPPPhoneSession session candidates stanza was received.");

                        XElement candidate = (from cand in iq.Descendants(m_sessionNS + "session").Descendants(m_sessionNS + "candidate")
                                              where cand.Attribute("protocol").Value == "udp"
                                              select cand).First();

                        m_remoteIPAddress = candidate.Attribute("address").Value;
                        Int32.TryParse(candidate.Attribute("port").Value, out m_remotePort);
                        m_remoteUsername = candidate.Attribute("username").Value;
                        m_remotePassword = candidate.Attribute("password").Value;
                    }
                    else if (sessionType.Value == "accept")
                    {
                        logger.Debug("XMPPPhoneSession session accept stanza was received.");

                        m_payloads = (from pl in iq.Descendants(m_sessionNS + "session").Descendants(m_phoneNS + "description")
                                          .Descendants(m_phoneNS + "payload-type")
                                      select pl).ToList();

                        Accepted(SDPToJingle.GetSDP(m_remoteIPAddress, m_remotePort, m_remoteUsername, m_remotePassword, m_payloads));
                    }
                    else if (sessionType.Value == "terminate")
                    {
                        logger.Debug("XMPPPhoneSession session terminate stanza was received.");

                        Hungup();
                    }
                }
                else
                {
                    logger.Warn("XMPPPhoneSession session element was received with a missing type attribute.");
                    logger.Warn(iq.ToString());
                }
            }
            else
            {
                logger.Warn("XMPPPhoneSession an iq element was received with no session element.");
                logger.Warn(iq.ToString());
            }
        }
    }
}
Back to Top