Menu

[r40]: / trunk / WhatsappClient / WhatsAppProtocol / WhatsAppProtocol.cs  Maximize  Restore  History

Download this file

288 lines (250 with data), 9.7 kB

  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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
public class WhatsAppProtocol
{
public enum CONNECTION_STATUS
{
DISCONNECTED,
CONNECTED
}
private AccountInfo accountinfo;
public static bool DEBUG;
private CONNECTION_STATUS loginStatus;
private object messageLock = new object();
private List<ProtocolTreeNode> messageQueue;
private BinTreeNodeReader reader;
private BinTreeNodeWriter writer;
private int timeout = 5000;
public WhatsNetwork whatsNetwork;
public WhatsSendHandler WhatsSendHandler { get; private set; }
public WhatsParser WhatsParser { get; private set; }
public WhatsappAccount Acc;
public static readonly Encoding SYSEncoding = Encoding.UTF8;
private byte[] _encryptionKey;
private byte[] _challengeBytes;
private List<IncompleteMessageException> _incompleteBytes;
public WhatsAppProtocol(WhatsappAccount _Acc)
{
this.messageQueue = new List<ProtocolTreeNode>();
WhatsAppProtocol.DEBUG = false;
string[] dict = DecodeHelper.getDictionary();
this.writer = new BinTreeNodeWriter(dict);
this.reader = new BinTreeNodeReader(dict);
this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
this.whatsNetwork = new WhatsNetwork(WhatsConstants.WhatsAppHost, WhatsConstants.WhatsPort, this.timeout);
this.WhatsParser = new WhatsParser(this.whatsNetwork, this.writer);
this.WhatsSendHandler = this.WhatsParser.WhatsSendHandler;
_incompleteBytes = new List<IncompleteMessageException>();
Acc = _Acc;
}
public void AddMessage(ProtocolTreeNode node)
{
lock (messageLock)
{
this.messageQueue.Add(node);
}
}
public void Connect()
{
this.whatsNetwork.Connect();
}
public void Disconnect()
{
this.whatsNetwork.Connect();
this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
}
public AccountInfo GetAccountInfo()
{
return this.accountinfo;
}
public ProtocolTreeNode[] GetAllMessages()
{
ProtocolTreeNode[] tmpReturn = null;
lock (messageLock)
{
tmpReturn = this.messageQueue.ToArray();
this.messageQueue.Clear();
}
return tmpReturn;
}
public bool HasMessages()
{
if (this.messageQueue == null)
return false;
return this.messageQueue.Count > 0;
}
public void Login()
{
string resource = string.Format(@"{0}-{1}-{2}",
WhatsConstants.IphoneDevice,
WhatsConstants.WhatsAppVer,
WhatsConstants.WhatsPort);
var data = this.writer.StartStream(WhatsConstants.WhatsAppServer, resource);
var feat = this.addFeatures();
ProtocolTreeNode auth = this.addAuth();
this.whatsNetwork.SendData(data);
this.whatsNetwork.SendData(this.writer.Write(feat, false));
this.whatsNetwork.SendData(this.writer.Write(auth, false));
this.PollMessages();
ProtocolTreeNode authResp = this.addAuthResponse_v1_2();
this.whatsNetwork.SendData(this.writer.Write(authResp, false));
int cnt = 0;
{
this.PollMessages();
System.Threading.Thread.Sleep(50);
} while ((cnt++ < 100) &&
(this.loginStatus == CONNECTION_STATUS.DISCONNECTED));
}
public void Message(string to, string txt)
{
var tmpMessage = new FMessage(to, true) { key = { id = TicketManager.GenerateId() }, data = txt };
this.WhatsParser.WhatsSendHandler.SendMessage(tmpMessage);
}
public void MessageImage(string msgid, string to, string url, string file, string size, string icon)
{
// implent
}
public void PollMessages()
{
this.processInboundData(this.whatsNetwork.ReadData());
}
public void Pong(string msgid)
{
this.WhatsParser.WhatsSendHandler.SendPong(msgid);
}
public void RequestLastSeen(string jid)
{
this.WhatsParser.WhatsSendHandler.SendQueryLastOnline(jid);
}
public void sendNickname(string nickname)
{
this.WhatsParser.WhatsSendHandler.SendAvailableForChat(nickname);
}
protected ProtocolTreeNode addAuth()
{
ProtocolTreeNode node = new ProtocolTreeNode("auth",
new KeyValue[] { new KeyValue("xmlns", @"urn:ietf:params:xml:ns:xmpp-sasl"),
new KeyValue("mechanism", "WAUTH-1"),
new KeyValue("user", Acc.FullPhonenumber) });
return node;
}
protected ProtocolTreeNode addAuthResponse_v1_2()
{
while (this._challengeBytes == null)
{
this.PollMessages();
System.Threading.Thread.Sleep(500);
}
Rfc2898DeriveBytes r = new Rfc2898DeriveBytes(Acc.Password, _challengeBytes, 16);
this._encryptionKey = r.GetBytes(20);
this.reader.Encryptionkey = _encryptionKey;
this.writer.Encryptionkey = _encryptionKey;
List<byte> b = new List<byte>();
b.AddRange(WhatsAppProtocol.SYSEncoding.GetBytes(Acc.Phonenumber));
b.AddRange(this._challengeBytes);
b.AddRange(WhatsAppProtocol.SYSEncoding.GetBytes(Func.GetNowUnixTimestamp().ToString()));
byte[] data = b.ToArray();
byte[] response = Encryption.WhatsappEncrypt(_encryptionKey, data, false);
var node = new ProtocolTreeNode("response",
new KeyValue[] { new KeyValue("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl") },
response);
return node;
}
protected ProtocolTreeNode addFeatures()
{
var child = new ProtocolTreeNode("receipt_acks", null);
var childList = new List<ProtocolTreeNode>();
childList.Add(child);
var parent = new ProtocolTreeNode("stream:features", null, childList, null);
return parent;
}
protected void DebugPrint(string debugMsg)
{
if (WhatsAppProtocol.DEBUG && debugMsg.Length > 0)
{
Console.WriteLine(debugMsg);
}
}
protected void processChallenge(ProtocolTreeNode node)
{
_challengeBytes = node.data;
}
protected void processInboundData(byte[] data)
{
try
{
var node = this.reader.nextTree(data);
while (node != null)
{
this.WhatsParser.ParseProtocolNode(node);
if (ProtocolTreeNode.TagEquals(node, "challenge"))
{
this.processChallenge(node);
}
else if (ProtocolTreeNode.TagEquals(node, "success"))
{
this.loginStatus = CONNECTION_STATUS.CONNECTED;
this.accountinfo = new AccountInfo(node.GetAttribute("status"),
node.GetAttribute("kind"),
node.GetAttribute("creation"),
node.GetAttribute("expiration"));
}
else if (ProtocolTreeNode.TagEquals(node, "failure"))
{
this.loginStatus = CONNECTION_STATUS.DISCONNECTED;
}
if (ProtocolTreeNode.TagEquals(node, "message"))
{
this.AddMessage(node);
this.sendMessageReceived(node);
}
if (ProtocolTreeNode.TagEquals(node, "stream:error"))
{
Console.Write(node.NodeString());
}
if (ProtocolTreeNode.TagEquals(node, "iq")
&& node.GetAttribute("type").Equals("get", StringComparison.OrdinalIgnoreCase)
&& ProtocolTreeNode.TagEquals(node.children.First(), "ping"))
{
this.Pong(node.GetAttribute("id"));
}
if (ProtocolTreeNode.TagEquals(node, "Replaced by new connection"))
{
this.Connect();
this.Login();
}
node = this.reader.nextTree();
}
}
catch (IncompleteMessageException e)
{
}
}
protected void sendMessageReceived(ProtocolTreeNode msg)
{
ProtocolTreeNode requestNode = msg.GetChild("request");
if (requestNode == null ||
!requestNode.GetAttribute("xmlns").Equals("urn:xmpp:receipts", StringComparison.OrdinalIgnoreCase))
return;
FMessage tmpMessage = new FMessage(new FMessage.Key(msg.GetAttribute("from"), true, msg.GetAttribute("id")));
this.WhatsParser.WhatsSendHandler.SendMessageReceived(tmpMessage);
}
private string md5(string pass)
{
MD5 md5 = MD5.Create();
byte[] dataMd5 = md5.ComputeHash(WhatsAppProtocol.SYSEncoding.GetBytes(pass));
var sb = new StringBuilder();
for (int i = 0; i < dataMd5.Length; i++)
sb.AppendFormat("{0:x2}", dataMd5[i]);
return sb.ToString();
}
private void PrintInfo(string p)
{
this.DebugPrint(p);
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.