Skip to content
This repository has been archived by the owner on Feb 16, 2019. It is now read-only.

Commit

Permalink
Further Stream Management development
Browse files Browse the repository at this point in the history
  • Loading branch information
coder2000 committed Jan 7, 2017
1 parent e6153d7 commit 2aa53bf
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 44 deletions.
28 changes: 14 additions & 14 deletions ubiety/Common/SASL/MD5Processor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public override Tag Step(Tag tag)
switch (tag.Name)
{
case "success":
Tag succ = tag;
var succ = tag;
PopulateDirectives(succ);

return succ;
Expand All @@ -81,7 +81,7 @@ public override Tag Step(Tag tag)
return tag;
}

Tag chall = tag;
var chall = tag;
PopulateDirectives(chall);
var res = TagRegistry.GetTag<GenericTag>("response", Namespaces.Sasl);
if (this["rspauth"] != null) return res;
Expand All @@ -93,7 +93,7 @@ public override Tag Step(Tag tag)

private void PopulateDirectives(Tag tag)
{
MatchCollection col = _csv.Matches(_enc.GetString(tag.Bytes));
var col = _csv.Matches(_enc.GetString(tag.Bytes));
foreach (Match m in col)
{
this[m.Groups["tag"].Value] = m.Groups["data"].Value;
Expand Down Expand Up @@ -134,15 +134,15 @@ private byte[] GenerateResponse()
sb.Append(",");
sb.Append("charset=");
sb.Append(this["charset"]);
string temp = sb.ToString();
var temp = sb.ToString();
return _enc.GetBytes(temp);
}

private void GenerateResponseHash()
{
var ae = new ASCIIEncoding();

long v = NextInt64();
var v = NextInt64();

// Create cnonce value using a random number, username and password
var sb = new StringBuilder();
Expand All @@ -165,7 +165,7 @@ private void GenerateResponseHash()
sb.Append(this["realm"]);
sb.Append(":");
sb.Append(Password);
byte[] h1 = _md5.ComputeHash(ae.GetBytes(sb.ToString()));
var h1 = _md5.ComputeHash(ae.GetBytes(sb.ToString()));

// Create the rest of A1 as stated in the RFC.
sb.Remove(0, sb.Length);
Expand All @@ -180,12 +180,12 @@ private void GenerateResponseHash()
sb.Append(this["authzid"]);
}

string a1 = sb.ToString();
var a1 = sb.ToString();

// Combine H1 and A1 into final A1
var ms = new MemoryStream();
ms.Write(h1, 0, 16);
byte[] temp = ae.GetBytes(a1);
var temp = ae.GetBytes(a1);
ms.Write(temp, 0, temp.Length);
ms.Seek(0, SeekOrigin.Begin);
h1 = _md5.ComputeHash(ms);
Expand All @@ -198,12 +198,12 @@ private void GenerateResponseHash()
{
sb.Append(":00000000000000000000000000000000");
}
string a2 = sb.ToString();
byte[] h2 = _md5.ComputeHash(ae.GetBytes(a2));
var a2 = sb.ToString();
var h2 = _md5.ComputeHash(ae.GetBytes(a2));

// Make A1 and A2 hex strings
string p1 = HexString(h1).ToLower();
string p2 = HexString(h2).ToLower();
var p1 = HexString(h1).ToLower();
var p2 = HexString(h2).ToLower();

// Combine all portions into the final response hex string
sb.Remove(0, sb.Length);
Expand All @@ -219,8 +219,8 @@ private void GenerateResponseHash()
sb.Append(":");
sb.Append(p2);

string a3 = sb.ToString();
byte[] h3 = _md5.ComputeHash(ae.GetBytes(a3));
var a3 = sb.ToString();
var h3 = _md5.ComputeHash(ae.GetBytes(a3));
_responseHash = HexString(h3).ToLower();
}

Expand Down
2 changes: 1 addition & 1 deletion ubiety/Common/SASL/SASLProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public virtual Tag Initialize(string id, string password)
protected string HexString(IEnumerable<byte> buff)
{
var sb = new StringBuilder();
foreach (byte b in buff)
foreach (var b in buff)
{
sb.Append(b.ToString("x2"));
}
Expand Down
38 changes: 19 additions & 19 deletions ubiety/Common/SASL/SCRAMProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,23 +76,23 @@ public override Tag Step(Tag tag)
case "challenge":
{
_serverFirst = tag.Bytes;
string response = _utf.GetString(tag.Bytes);
var response = _utf.GetString(tag.Bytes);

// Split challenge into pieces
string[] tokens = response.Split(',');
var tokens = response.Split(',');

_snonce = tokens[0].Substring(2);
// Ensure that the first length of nonce is the same nonce we sent.
string r = _snonce.Substring(0, _nonce.Length);
var r = _snonce.Substring(0, _nonce.Length);
if (0 != string.CompareOrdinal(r, _nonce))
{
throw new Exception("Error in authenticating server nonce.");
}

string a = tokens[1].Substring(2);
var a = tokens[1].Substring(2);
_salt = Convert.FromBase64String(a);

string i = tokens[2].Substring(2);
var i = tokens[2].Substring(2);
_i = int.Parse(i);

var final = new StringBuilder();
Expand All @@ -114,8 +114,8 @@ public override Tag Step(Tag tag)

case "success":
{
string response = _utf.GetString(tag.Bytes);
byte[] signature = Convert.FromBase64String(response.Substring(2));
var response = _utf.GetString(tag.Bytes);
var signature = Convert.FromBase64String(response.Substring(2));
return _utf.GetString(signature) == _utf.GetString(_serverSignature) ? tag : null;
}
case "failure":
Expand All @@ -130,17 +130,17 @@ private void CalculateProofs()
var hmac = new HMACSHA1();
SHA1 hash = new SHA1CryptoServiceProvider();

byte[] saltedPassword = Hi();
var saltedPassword = Hi();

// Calculate Client Key
hmac.Key = saltedPassword;
byte[] clientKey = hmac.ComputeHash(_utf.GetBytes("Client Key"));
var clientKey = hmac.ComputeHash(_utf.GetBytes("Client Key"));

// Calculate Server Key
byte[] serverKey = hmac.ComputeHash(_utf.GetBytes("Server Key"));
var serverKey = hmac.ComputeHash(_utf.GetBytes("Server Key"));

// Calculate Stored Key
byte[] storedKey = hash.ComputeHash(clientKey);
var storedKey = hash.ComputeHash(clientKey);

var a = new StringBuilder();
a.Append(_clientFirst);
Expand All @@ -149,19 +149,19 @@ private void CalculateProofs()
a.Append(",");
a.Append(_clientFinal);

byte[] auth = _utf.GetBytes(a.ToString());
var auth = _utf.GetBytes(a.ToString());

// Calculate Client Signature
hmac.Key = storedKey;
byte[] signature = hmac.ComputeHash(auth);
var signature = hmac.ComputeHash(auth);

// Calculate Server Signature
hmac.Key = serverKey;
_serverSignature = hmac.ComputeHash(auth);

// Calculate Client Proof
var proof = new byte[20];
for (int i = 0; i < signature.Length; ++i)
for (var i = 0; i < signature.Length; ++i)
{
proof[i] = (byte) (clientKey[i] ^ signature[i]);
}
Expand All @@ -172,7 +172,7 @@ private void CalculateProofs()
private byte[] Hi()
{
var prev = new byte[20];
byte[] password = _utf.GetBytes(Stringprep.SASLPrep(Password));
var password = _utf.GetBytes(Stringprep.SASLPrep(Password));

// Add 1 to the end of salt with most significat octet first
var key = new byte[_salt.Length + 4];
Expand All @@ -183,13 +183,13 @@ private byte[] Hi()

// Compute initial hash
var hmac = new HMACSHA1(password);
byte[] result = hmac.ComputeHash(key);
var result = hmac.ComputeHash(key);
Array.Copy(result, prev, result.Length);

for (int i = 1; i < _i; ++i)
for (var i = 1; i < _i; ++i)
{
byte[] temp = hmac.ComputeHash(prev);
for (int j = 0; j < temp.Length; ++j)
var temp = hmac.ComputeHash(prev);
for (var j = 0; j < temp.Length; ++j)
{
result[j] ^= temp[j];
}
Expand Down
6 changes: 3 additions & 3 deletions ubiety/Common/Tag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ protected string GetNextId()
/// <summary>
/// Implicit cast of a tag to a string.
/// </summary>
/// <param name="one">Tag to cast to string</param>
/// <param name="tag">Tag to cast to string</param>
/// <returns>String version of the tag</returns>
public static implicit operator string(Tag one)
public static implicit operator string(Tag tag)
{
return one.ToString();
return tag.ToString();
}

/// <summary>
Expand Down
3 changes: 1 addition & 2 deletions ubiety/States/DisconnectedState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@ public void Execute(Tag data = null)
{
if (data != null)
{
// TODO - Bubble the error message out
var tag = ((Stream) data).Error;

ProtocolState.Events.Error(this, ErrorType.XmlError, ErrorSeverity.Fatal, tag);
}
else
{
Expand Down
File renamed without changes.
29 changes: 29 additions & 0 deletions ubiety/States/ProtocolState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
//Temple Place, Suite 330, Boston, MA 02111-1307 USA

using System;
using System.Collections.Generic;
using Ubiety.Common;
using Ubiety.Common.Roster;
using Ubiety.Common.Sasl;
using Ubiety.Core;
using Ubiety.Core.Iq;
using Ubiety.Infrastructure;
using Ubiety.Net;

Expand All @@ -39,6 +42,16 @@ static ProtocolState()
Events.OnNewTag += EventsOnOnNewTag;
Events.OnConnect += EventsOnOnConnect;
Events.OnDisconnect += EventsOnOnDisconnect;
Events.OnSend += EventsOnOnSend;
}

private static void EventsOnOnSend(object sender, TagEventArgs tagEventArgs)
{
if (!StreamManagementAvailable) return;
if (tagEventArgs.Tag is GenericTag || tagEventArgs.Tag is Iq)
{
UnacknowlegedStanzas.Enqueue(tagEventArgs.Tag);
}
}

/// <value>
Expand Down Expand Up @@ -66,13 +79,26 @@ static ProtocolState()
/// </summary>
public static bool Compressed { get; set; }

/// <summary>
///
/// </summary>
public static string Algorithm { get; set; }

/// <summary>
///
/// </summary>
public static bool StreamManagementAvailable { get; set; }

/// <summary>
///
/// </summary>
public static int StanzaCount { get; set; }

/// <summary>
///
/// </summary>
public static Queue<Tag> UnacknowlegedStanzas { get; set; }

/// <summary>
/// The current static settings instance
/// </summary>
Expand All @@ -83,6 +109,9 @@ static ProtocolState()
/// </summary>
public static XmppEvents Events { get; }

/// <summary>
///
/// </summary>
public static IRosterManager RosterManager { get; set; }

private static void EventsOnOnDisconnect(object sender, EventArgs eventArgs)
Expand Down
25 changes: 24 additions & 1 deletion ubiety/States/RunningState.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// RunningState.cs
//
//Ubiety XMPP Library Copyright (C) 2009, 2015 Dieter Lunn
//Ubiety XMPP Library Copyright (C) 2009, 2015, 2017 Dieter Lunn
//
//This library is free software; you can redistribute it and/or modify it under
//the terms of the GNU Lesser General Public License as published by the Free
Expand All @@ -15,8 +15,11 @@
//with this library; if not, write to the Free Software Foundation, Inc., 59
//Temple Place, Suite 330, Boston, MA 02111-1307 USA

using System.Xml;
using Ubiety.Common;
using Ubiety.Common.Roster;
using Ubiety.Core.SM;
using Ubiety.Registries;

namespace Ubiety.States
{
Expand All @@ -29,6 +32,26 @@ public class RunningState : IState
/// <param name="data"></param>
public void Execute(Tag data = null)
{
if (data is R)
{
var ack = TagRegistry.GetTag<A>(new XmlQualifiedName("a", Namespaces.StreamManagementV3));
ack.H = ProtocolState.StanzaCount;
ProtocolState.Socket.Write(ack);
}
else if (data is A)
{
var ack = (A) data;
var handled = ack.H;
var delta = handled - ProtocolState.StanzaCount;

for (var i = 0; i < delta; i++)
{
if (ProtocolState.UnacknowlegedStanzas.Count == 0) continue;

var ackStanza = ProtocolState.UnacknowlegedStanzas.Dequeue();
}
}

if (ProtocolState.RosterManager == null)
{
ProtocolState.RosterManager = new DefaultRosterManager();
Expand Down
1 change: 1 addition & 0 deletions ubiety/States/ServerFeaturesState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ public void Execute(Tag data = null)

if (f.SM != null)
{
Log.Debug("Stream Management Available");
ProtocolState.StreamManagementAvailable = true;
}
}
Expand Down
7 changes: 5 additions & 2 deletions ubiety/States/SessionState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
//with this library; if not, write to the Free Software Foundation, Inc., 59
//Temple Place, Suite 330, Boston, MA 02111-1307 USA

using Serilog;
using Ubiety.Common;
using Ubiety.Core;
using Ubiety.Core.Iq;
Expand Down Expand Up @@ -45,12 +46,14 @@ public void Execute(Tag data = null)
}
else
{
var p = TagRegistry.GetTag<GenericTag>("presence", Namespaces.Client);
ProtocolState.Socket.Write(p);
//var p = TagRegistry.GetTag<GenericTag>("presence", Namespaces.Client);
//ProtocolState.Socket.Write(p);

if (ProtocolState.StreamManagementAvailable)
{
Log.Debug("Intiating Stream Management");
ProtocolState.State = new StreamManagementState();
ProtocolState.State.Execute();
}
else
{
Expand Down
Loading

0 comments on commit 2aa53bf

Please sign in to comment.