Guest User

XMPP chat in webforms

a guest
Oct 29th, 2013
951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.90 KB | None | 0 0
  1. public partial class Chat : Page
  2. {
  3.     public TcpClient client = new TcpClient();
  4.     NetworkStream stream;
  5.     private SslStream ssl;
  6.     private string AppId { get; set; }
  7.     public string AppSecret { get; set; }
  8.     public string AppUrl { get; set; }
  9.     public string UserId { get; set; }
  10.     public string AccessToken { get; set; }
  11.     private string _error = string.Empty;//global error string for watch debugging in VS.
  12.  
  13.     public const string FbServer = "chat.facebook.com";
  14.     private const string STREAM_XML = "<stream:stream xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" xmlns=\"jabber:client\" to=\"chat.facebook.com\" xml:lang=\"en\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\">";
  15.     private const string AUTH_XML = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-FACEBOOK-PLATFORM'></auth>";
  16.     private const string CLOSE_XML = "</stream:stream>";
  17.     private const string RESOURCE_XML = "<iq type=\"set\" id=\"3\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>fb_xmpp_script</resource></bind></iq>";
  18.     private const string SESSION_XML = "<iq type=\"set\" id=\"4\" to=\"chat.facebook.com\"><session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/></iq>";
  19.     private const string START_TLS = "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>";
  20.  
  21.     protected void Page_Load(object sender, EventArgs e)
  22. this.AppId = "000000082000090";//TODO get from appsettings.
  23.         //AddAdditionalPermissions("xmpp_login");//TODO handle xmpp_login persmission
  24.         this.AppSecret = "d370c1bfec9be6d9accbdf0117f2c495"; //TODO Get appsecret from appsetting.
  25.         this.AppUrl = "https://fbd.anteckna.nu";
  26.  
  27.         SetUserNameAndAuthToken();
  28.  
  29.         Connect(FbServer);
  30.  
  31.         // initiates auth process (using X-FACEBOOK_PLATFORM)
  32.         InitiateAuthProcess(STREAM_XML);
  33.  
  34.         // starting tls - MANDATORY TO USE OAUTH TOKEN!!!!
  35.         StartTlsConnection(START_TLS);
  36.  
  37.         // gets decoded challenge from server
  38.         var decoded = GetDecodedChallenge(AUTH_XML);
  39.  
  40.         // creates the response and signature
  41.         string response = CreateResponse(decoded);
  42.  
  43.         //send response to server
  44.         SendResponseToServer(response);
  45.  
  46.         SendMessage("test");
  47.  
  48.         // finishes auth process
  49.         FinishAuthProcess();
  50.  
  51.         // we made it!
  52.         string streamresponseEnd = SendWihSsl(CLOSE_XML);
  53.  
  54.     }
  55. public void Connect(string server)
  56.     {
  57.         try
  58.         {
  59.             client.Connect(server, 5222);
  60.             stream = client.GetStream();
  61.         }
  62.         catch (ArgumentNullException e)
  63.         {
  64.             Console.WriteLine("ArgumentNullException: {0}", e);
  65.         }
  66.         catch (SocketException e)
  67.         {
  68.             Console.WriteLine("SocketException: {0}", e);
  69.         }
  70.     }
  71.  
  72. private void InitiateAuthProcess(string streamXml)
  73.     {
  74.         string initiation = Send(streamXml);
  75.         if (!initiation.Contains("X-FACEBOOK-PLATFORM"))
  76.             _error = initiation; //TODO handle error
  77.     }
  78. //Facebook answer
  79. //<?xml version='1.0' ?><stream:stream from='chat.facebook.com' id='1' version='1.0' //xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' xml:lang='en'><stream:features><starttls //xmlns='urn:ietf:params:xml:ns:xmpp-tls'/><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>X-//FACEBOOK-PLATFORM</mechanism><mechanism>PLAIN</mechanism></mechanisms></stream:features>
  80.  
  81. public string Send(string dataToSend)
  82.     {
  83.         Byte[] data = Encoding.UTF8.GetBytes(dataToSend);
  84.         stream.Write(data, 0, data.Length);
  85.         data = new Byte[2048];
  86.         Int32 bytes = stream.Read(data, 0, data.Length);
  87.         string responseData = Encoding.UTF8.GetString(data, 0, bytes);
  88.  
  89.         return responseData;
  90.     }
  91.  
  92. private void StartTlsConnection(string startTls)
  93.     {
  94.         string tlsResult = Send(startTls);
  95.         if (!tlsResult.ToLower().Contains("proceed"))
  96.             _error = tlsResult; //TODO handle error
  97.  
  98.         ssl = new SslStream(client.GetStream(), false,
  99.             new RemoteCertificateValidationCallback(ValidateServerCertificate),
  100.             null);
  101.         try
  102.         {
  103.             ssl.AuthenticateAsClient(FbServer, new X509CertificateCollection(), SslProtocols.Tls, false);
  104.         }
  105.         catch (AuthenticationException ex)
  106.         {
  107.             Console.WriteLine("Exception: {0}", ex.Message);
  108.             if (ex.InnerException != null)
  109.             {
  110.                 Console.WriteLine("Inner exception: {0}", ex.InnerException.Message);
  111.             }
  112.             Console.WriteLine("Authentication failed - closing the connection.");
  113.             client.Close();
  114.             return;
  115.         }
  116.         string initiationSsl = SendWihSsl(STREAM_XML);
  117.         if (!initiationSsl.Contains("X-FACEBOOK-PLATFORM"))
  118.             _error = initiationSsl;//TODO handle error
  119.     }
  120.  
  121. //Response from facebook in tlsResult is:
  122. //<proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>
  123.  
  124. //Response from Facebook in initiationSsl is :
  125. //<?xml version='1.0' ?><stream:stream from='chat.facebook.com' id='1' version='1.0' //xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' xml:lang='en'><stream:features><mechanisms //xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><mechanism>X-FACEBOOK-PLATFORM</mechanism>
  126. //<mechanism>PLAIN</mechanism></mechanisms></stream:features>
  127.  
  128.  
  129. public string SendWihSsl(string dataToSend)
  130.     {
  131.         Byte[] data = System.Text.Encoding.UTF8.GetBytes(dataToSend);
  132.  
  133.         ssl.Write(data, 0, data.Length);
  134.         ssl.Flush();
  135.         data = new Byte[2048];
  136.  
  137.         int myBytesRead = 0;
  138.         StringBuilder myResponseAsSB = new StringBuilder();
  139.         do
  140.         {
  141.             myBytesRead = ssl.Read(data, 0, data.Length);
  142.             myResponseAsSB.Append(System.Text.Encoding.UTF8.GetString(data, 0, myBytesRead));
  143.             if (myResponseAsSB.ToString().IndexOf("</") != -1)
  144.             {
  145.                 break;
  146.             }
  147.         } while (myBytesRead != 0);
  148.  
  149.         return myResponseAsSB.ToString();
  150.     }
  151.  
  152. //reeturn version=1&method=auth.xmpp_login&nonce=234A8DD1234AB6ABSD1234ABC1AB123
  153. private string GetDecodedChallenge(string authXml)
  154.     {
  155.         string sslResponse = SendWihSsl(authXml);
  156.  
  157.         int start = sslResponse.IndexOf("'>") + 2;
  158.         int end = sslResponse.IndexOf("</");
  159.         string challenge = sslResponse.Substring(start, end - start);
  160.         string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(challenge));
  161.         return decoded;
  162.     }
  163.  
  164. private void SendResponseToServer(string response)
  165.     {
  166.         string xml = String.Format("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">{0}</response>", response);
  167.         string response2 = SendWihSsl2(xml);
  168.         if (!response2.ToLower().Contains("success"))
  169.             _error = response2;
  170.     }
  171.  
  172. //After 100seconds I get : <success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>
Add Comment
Please, Sign In to add comment