Esempio n. 1
1
        protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension)
        {
            ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] {
                new KeyValue("hash", b64hash),
                new KeyValue("type", type),
                new KeyValue("size", size.ToString())
            });
            string id = TicketManager.GenerateId();
            ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] {
                new KeyValue("id", id),
                new KeyValue("to", WhatsConstants.WhatsAppServer),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "w:m")
            }, media);
            this.uploadResponse = null;
            this.SendNode(node);
            int i = 0;
            while (this.uploadResponse == null && i <= 10)
            {
                i++;
                this.pollMessage();
            }
            if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null)
            {
                WaUploadResponse res = new WaUploadResponse(this.uploadResponse);
                this.uploadResponse = null;
                return res;
            }
            else
            {
                try
                {
                    string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url");
                    this.uploadResponse = null;

                    Uri uri = new Uri(uploadUrl);

                    string hashname = string.Empty;
                    byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash));
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in buff)
                    {
                        sb.Append(b.ToString("X2"));
                    }
                    hashname = String.Format("{0}.{1}", sb.ToString(), extension);

                    string boundary = "zzXXzzYYzzXXzzQQ";

                    sb = new StringBuilder();

                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", to);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n");
                    sb.AppendFormat("{0}\r\n", this.phoneNumber);
                    sb.AppendFormat("--{0}\r\n", boundary);
                    sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname);
                    sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype);
                    string header = sb.ToString();

                    sb = new StringBuilder();
                    sb.AppendFormat("\r\n--{0}--\r\n", boundary);
                    string footer = sb.ToString();

                    long clength = size + header.Length + footer.Length;

                    sb = new StringBuilder();
                    sb.AppendFormat("POST {0}\r\n", uploadUrl);
                    sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary);
                    sb.AppendFormat("Host: {0}\r\n", uri.Host);
                    sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent);
                    sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength);
                    string post = sb.ToString();

                    TcpClient tc = new TcpClient(uri.Host, 443);
                    SslStream ssl = new SslStream(tc.GetStream());
                    try
                    {
                        ssl.AuthenticateAsClient(uri.Host);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    List<byte> buf = new List<byte>();
                    buf.AddRange(Encoding.UTF8.GetBytes(post));
                    buf.AddRange(Encoding.UTF8.GetBytes(header));
                    buf.AddRange(fileData);
                    buf.AddRange(Encoding.UTF8.GetBytes(footer));

                    ssl.Write(buf.ToArray(), 0, buf.ToArray().Length);

                    //moment of truth...
                    buff = new byte[1024];
                    ssl.Read(buff, 0, 1024);

                    string result = Encoding.UTF8.GetString(buff);
                    foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("{"))
                        {
                            string fooo = line.TrimEnd(new char[] { (char)0 });
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            WaUploadResponse resp = jss.Deserialize<WaUploadResponse>(fooo);
                            if (!String.IsNullOrEmpty(resp.url))
                            {
                                return resp;
                            }
                        }
                    }
                }
                catch (Exception)
                { }
            }
            return null;
        }
 public ProtocolTreeNode(string tag, IEnumerable<KeyValue> attributeHash, ProtocolTreeNode children = null)
 {
     this.tag = tag ?? "";
     this.attributeHash = attributeHash ?? new KeyValue[0];
     this.children = children != null ? new ProtocolTreeNode[] { children } : new ProtocolTreeNode[0];
     this.data = new byte[0];
 }
Esempio n. 3
0
 public void AddMessage(ProtocolTreeNode node)
 {
     lock (messageLock)
     {
         this.messageQueue.Add(node);
     }
 }
 protected void fireOnGetMessageAudio(ProtocolTreeNode mediaNode, string from, string id, string fileName, int fileSize, string url, byte[] preview, string name)
 {
     if (this.OnGetMessageAudio != null)
     {
         this.OnGetMessageAudio(mediaNode, from, id, fileName, fileSize, url, preview, name);
     }
 }
 protected void fireOnGetMessage(ProtocolTreeNode messageNode, string from, string id, string name, string message, bool receipt_sent)
 {
     if (this.OnGetMessage != null)
     {
         this.OnGetMessage(messageNode, from, id, name, message, receipt_sent);
     }
 }
Esempio n. 6
0
        void client_OnGetMessage(WhatsAppApi.Helper.ProtocolTreeNode messageNode, string from, string id, string name, string message, bool receipt_sent)
        {
            RosterItem rsRosterItem = Roster.Instance.Get(from);

            if (rsRosterItem == null)
            {
                rsRosterItem = new RosterItem()
                {
                    Jid      = from,
                    Name     = name,
                    Messages = new System.Collections.ObjectModel.ObservableCollection <Message>()
                };
                Roster.Instance.Add(rsRosterItem);

                client.SendGetPhoto(from, "", false);
                client.SendGetStatuses(new string[] { from });
            }

            rsRosterItem.Add(new Message()
            {
                Text        = message,
                Time        = DateTime.Now,
                ID          = id,
                FromJid     = from,
                ToJid       = "",
                MessageType = Enumerations.MessageType.Incoming
            });
        }
        /// <summary>
        /// Parse recieved message
        /// </summary>
        /// <param name="messageNode">TreeNode that contains the recieved message</param>
        public void ParseMessageRecv(ProtocolTreeNode messageNode)
        {
            FMessage.Builder builder = new FMessage.Builder();
            string tmpAttrbId = messageNode.GetAttribute("id");
            string tmpAttrFrom = messageNode.GetAttribute("from");
            string tmpAttrFromName = messageNode.GetAttribute("");
            string tmpAttrFromJid = messageNode.GetAttribute("author") ?? "";
            string tmpAttrType = messageNode.GetAttribute("type");
            string tmpTAttribT = messageNode.GetAttribute("t");

            long result = 0L;
            if (!string.IsNullOrEmpty(tmpTAttribT) && long.TryParse(tmpTAttribT, out result))
            {
                builder.Timestamp(new DateTime?(WhatsConstants.UnixEpoch.AddSeconds((double)result)));
            }

            if ("error".Equals(tmpAttrType))
            {
                TypeError(messageNode, tmpAttrbId, tmpAttrFrom);
            }
            else if ("subject".Equals(tmpAttrType))
            {
                TypeSubject(messageNode, tmpAttrFrom, tmpAttrFromJid, tmpAttrbId, tmpTAttribT);
            }
            else if ("chat".Equals(tmpAttrType))
            {
                TypeChat(messageNode, tmpAttrFrom, tmpAttrbId, builder, tmpAttrFromJid);
            }
            else if ("notification".Equals(tmpAttrType))
            {
                TypeNotification(messageNode, tmpAttrFrom, tmpAttrbId);
            }
        }
Esempio n. 8
0
 public void SendClientConfig(string platform, string lg, string lc)
 {
     string v = TicketCounter.MakeId("config_");
     var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push"), new KeyValue("platform", platform), new KeyValue("lg", lg), new KeyValue("lc", lc) });
     var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", v), new KeyValue("type", "set"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child });
     this.SendNode(node);
 }
Esempio n. 9
0
 public void SendClientConfig(string platform, string lg, string lc, Uri pushUri, bool preview, bool defaultSetting, bool groupsSetting, IEnumerable<GroupSetting> groups, Action onCompleted, Action<int> onError)
 {
     string id = TicketCounter.MakeId("config_");
     var node = new ProtocolTreeNode("iq",
                                 new[]
                                 {
                                     new KeyValue("id", id), new KeyValue("type", "set"),
                                     new KeyValue("to", "") //this.Login.Domain)
                                 },
                                 new ProtocolTreeNode[]
                                 {
                                     new ProtocolTreeNode("config",
                                     new[]
                                         {
                                             new KeyValue("xmlns","urn:xmpp:whatsapp:push"),
                                             new KeyValue("platform", platform),
                                             new KeyValue("lg", lg),
                                             new KeyValue("lc", lc),
                                             new KeyValue("clear", "0"),
                                             new KeyValue("id", pushUri.ToString()),
                                             new KeyValue("preview",preview ? "1" : "0"),
                                             new KeyValue("default",defaultSetting ? "1" : "0"),
                                             new KeyValue("groups",groupsSetting ? "1" : "0")
                                         },
                                     this.ProcessGroupSettings(groups))
                                 });
     this.SendNode(node);
 }
Esempio n. 10
0
 public WaUploadResponse(ProtocolTreeNode node)
 {
     node = node.GetChild("duplicate");
     if (node != null)
     {
         int oSize, oWidth, oHeight, oDuration, oAsampfreq, oAbitrate;
         this.url = node.GetAttribute("url");
         this.mimetype = node.GetAttribute("mimetype");
         Int32.TryParse(node.GetAttribute("size"), out oSize);
         this.filehash = node.GetAttribute("filehash");
         this.type = node.GetAttribute("type");
         Int32.TryParse(node.GetAttribute("width"), out oWidth);
         Int32.TryParse(node.GetAttribute("height"), out oHeight);
         Int32.TryParse(node.GetAttribute("duration"), out oDuration);
         this.acodec = node.GetAttribute("acodec");
         Int32.TryParse(node.GetAttribute("asampfreq"), out oAsampfreq);
         this.asampfmt = node.GetAttribute("asampfmt");
         Int32.TryParse(node.GetAttribute("abitrate"), out oAbitrate);
         this.size = oSize;
         this.width = oWidth;
         this.height = oHeight;
         this.duration = oDuration;
         this.asampfreq = oAsampfreq;
         this.abitrate = oAbitrate;
     }
 }
Esempio n. 11
0
 public WappMessage(ProtocolTreeNode node, string jid)
 {
     ProtocolTreeNode body = node.GetChild("body");
     ProtocolTreeNode media = node.GetChild("media");
     if (node.tag == "message")
     {
         if (node.GetAttribute("type") == "subject")
         {
             Contact c = ContactStore.GetContactByJid(node.GetAttribute("author"));
             this.data = c.ToString() + " changed subject to \"" + Encoding.ASCII.GetString(node.GetChild("body").GetData()) + "\"";
         }
         else
         {
             if (body != null)
             {
                 this.data = Encoding.ASCII.GetString(node.GetChild("body").GetData());
                 this.type = "text";
             }
             else if (media != null)
             {
                 this.type = media.GetAttribute("type");
                 if (media.data != null && media.data.Length > 0)
                 {
                     this.preview = Convert.ToBase64String(media.data);
                 }
                 this.data = media.GetAttribute("url");
             }
         }
         this.from_me = false;
         this.timestamp = DateTime.UtcNow;
         this.jid = jid;
     }
 }
Esempio n. 12
0
 public void SendSync(string[] numbers, SyncMode mode = SyncMode.Delta, SyncContext context = SyncContext.Background, int index = 0, bool last = true)
 {
     List<ProtocolTreeNode> users = new List<ProtocolTreeNode>();
     foreach (string number in numbers)
     {
         string _number = number;
         if (!_number.StartsWith("+", StringComparison.InvariantCulture))
             _number = string.Format("+{0}", number);
         users.Add(new ProtocolTreeNode("user", null, System.Text.Encoding.UTF8.GetBytes(_number)));
     }
     ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[]
     {
         new KeyValue("to", GetJID(this.phoneNumber)),
         new KeyValue("type", "get"),
         new KeyValue("id", TicketCounter.MakeId("sendsync_")),
         new KeyValue("xmlns", "urn:xmpp:whatsapp:sync")
     }, new ProtocolTreeNode("sync", new KeyValue[]
         {
             new KeyValue("mode", mode.ToString().ToLowerInvariant()),
             new KeyValue("context", context.ToString().ToLowerInvariant()),
             new KeyValue("sid", DateTime.Now.ToFileTimeUtc().ToString()),
             new KeyValue("index", index.ToString()),
             new KeyValue("last", last.ToString())
         },
         users.ToArray()
         )
     );
     this.SendNode(node);
 }
        protected ProtocolTreeNode addFeatures()
        {
			ProtocolTreeNode readReceipts = new ProtocolTreeNode ("readreceipts", null,null, null);
			ProtocolTreeNode groups_v2 = new ProtocolTreeNode ("groups_v2", null,null, null);
			ProtocolTreeNode privacy = new ProtocolTreeNode ("privacy", null,null, null);
			ProtocolTreeNode presencev2 = new ProtocolTreeNode ("presence", null,null, null);
			return new ProtocolTreeNode("stream:features", null, new ProtocolTreeNode[] {readReceipts, groups_v2, privacy, presencev2}, null);
        }
Esempio n. 14
0
 public string Write(ProtocolTreeNode node)
 {
     if (node == null)
     {
         this.output += "\x00";
     }
     else
     {
         this.writeInternal(node);
     }
     return this.flushBuffer();
 }
Esempio n. 15
0
 public byte[] Write(ProtocolTreeNode node, bool encrypt = true)
 {
     if (node == null)
     {
         this.buffer.Add(0);
     }
     else
     {
         this.DebugPrint(node.NodeString("SENT: "));
         this.writeInternal(node);
     }
     return this.flushBuffer(encrypt);
 }
Esempio n. 16
0
 public void SendClearDirty(IEnumerable<string> categoryNames)
 {
     string id = TicketCounter.MakeId("clean_dirty_");
     //this.AddIqHandler(id, new FunXMPP.IqResultHandler(null));
     IEnumerable<ProtocolTreeNode> source = from category in categoryNames select new ProtocolTreeNode("category", new[] { new KeyValue("name", category) });
     var child = new ProtocolTreeNode("clean", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:dirty") }, source);
     var node = new ProtocolTreeNode("iq",
                                     new[]
                                         {
                                             new KeyValue("id", id), new KeyValue("type", "set"),
                                             new KeyValue("to", "s.whatsapp.net")
                                         }, child);
     this.whatsNetwork.SendNode(node);
 }
Esempio n. 17
0
 public byte[] Write(ProtocolTreeNode node, bool encrypt = true)
 {
     if (node == null)
     {
         this.buffer.Add(0);
     }
     else
     {
         if (WhatsApp.DEBUG && WhatsApp.DEBUGOutBound)
             this.DebugPrint(node.NodeString("tx "));
         this.writeInternal(node);
     }
     return this.flushBuffer(encrypt);
 }
 /// <summary>
 /// Notify typing picture
 /// </summary>
 /// <param name="tmpChild">Child</param>
 /// <param name="tmpFrom">From?</param>
 private static void TypeNotificationPicture(ProtocolTreeNode tmpChild, string tmpFrom)
 {
     foreach (ProtocolTreeNode item in (tmpChild.GetAllChildren() ?? new ProtocolTreeNode[0]))
     {
         if (ProtocolTreeNode.TagEquals(item, "set"))
         {
             string photoId = item.GetAttribute("id");
             if (photoId != null)
             {
                 WhatsEventHandler.OnPhotoChangedEventHandler(tmpFrom, item.GetAttribute("author"), photoId);
             }
         }
         else if (ProtocolTreeNode.TagEquals(item, "delete"))
         {
             WhatsEventHandler.OnPhotoChangedEventHandler(tmpFrom, item.GetAttribute("author"), null);
         }
     }
 }
Esempio n. 19
0
 public WappMessage(ProtocolTreeNode node, string jid)
 {
     if (node.tag == "message")
     {
         if (node.GetAttribute("type") == "subject")
         {
             Contact c = ContactStore.GetContactByJid(node.GetAttribute("author"));
             this.data = c.ToString() + " changed subject to \"" + Encoding.ASCII.GetString(node.GetChild("body").GetData()) + "\"";
         }
         else
         {
             this.data = Encoding.ASCII.GetString(node.GetChild("body").GetData());
         }
         this.from_me = false;
         this.timestamp = DateTime.UtcNow;
         this.jid = jid;
     }
 }
Esempio n. 20
0
 protected void SendVerbParticipants(string gjid, IEnumerable<string> participants, string id, string inner_tag)
 {
     IEnumerable<ProtocolTreeNode> source = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", jid) });
     var child = new ProtocolTreeNode(inner_tag, null, source);
     var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g"), new KeyValue("to", GetJID(gjid)) }, child);
     this.SendNode(node);
 }
Esempio n. 21
0
 public void SendClose()
 {
     var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") });
     this.SendNode(node);
 }
Esempio n. 22
0
 protected void SendQrSync(byte[] qrkey, byte[] token = null)
 {
     string id = TicketCounter.MakeId("qrsync_");
     List<ProtocolTreeNode> children = new List<ProtocolTreeNode>();
     children.Add(new ProtocolTreeNode("sync", null, qrkey));
     if (token != null)
     {
         children.Add(new ProtocolTreeNode("code", null, token));
     }
     ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] {
         new KeyValue("type", "set"),
         new KeyValue("id", id),
         new KeyValue("xmlns", "w:web")
     }, children.ToArray());
     this.SendNode(node);
 }
Esempio n. 23
0
        protected void SendMessageWithMedia(FMessage message)
        {
            ProtocolTreeNode node;
            if (FMessage.Type.System == message.media_wa_type)
            {
                throw new SystemException("Cannot send system message over the network");
            }

            List<KeyValue> list = new List<KeyValue>(new KeyValue[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:mms"), new KeyValue("type", FMessage.GetMessage_WA_Type_StrValue(message.media_wa_type)) });
            if (FMessage.Type.Location == message.media_wa_type)
            {
                list.AddRange(new KeyValue[] { new KeyValue("latitude", message.latitude.ToString(CultureInfo.InvariantCulture)), new KeyValue("longitude", message.longitude.ToString(CultureInfo.InvariantCulture)) });
                if (message.location_details != null)
                {
                    list.Add(new KeyValue("name", message.location_details));
                }
                if (message.location_url != null)
                {
                    list.Add(new KeyValue("url", message.location_url));
                }
            }
            else if (((FMessage.Type.Contact != message.media_wa_type) && (message.media_name != null)) && ((message.media_url != null) && (message.media_size > 0L)))
            {
                list.AddRange(new KeyValue[] { new KeyValue("file", message.media_name), new KeyValue("size", message.media_size.ToString(CultureInfo.InvariantCulture)), new KeyValue("url", message.media_url) });
                if (message.media_duration_seconds > 0)
                {
                    list.Add(new KeyValue("seconds", message.media_duration_seconds.ToString(CultureInfo.InvariantCulture)));
                }
            }
            if ((FMessage.Type.Contact == message.media_wa_type) && (message.media_name != null))
            {
                node = new ProtocolTreeNode("media", list.ToArray(), new ProtocolTreeNode("vcard", new KeyValue[] { new KeyValue("name", message.media_name) }, WhatsApp.SYSEncoding.GetBytes(message.data)));
            }
            else
            {
                byte[] data = message.binary_data;
                if ((data == null) && !string.IsNullOrEmpty(message.data))
                {
                    try
                    {
                        data = Convert.FromBase64String(message.data);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (data != null)
                {
                    list.Add(new KeyValue("encoding", "raw"));
                }
                node = new ProtocolTreeNode("media", list.ToArray(), null, data);
            }
            this.SendNode(GetMessageNode(message, node));
        }
Esempio n. 24
0
 protected void SendMessageWithBody(FMessage message, bool hidden = false)
 {
     var child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data));
     this.SendNode(GetMessageNode(message, child, hidden));
 }
Esempio n. 25
0
 protected void SendChatState(string to, string type)
 {
     var node = new ProtocolTreeNode("chatstate", new[] { new KeyValue("to", WhatsApp.GetJID(to)) }, new[] {
         new ProtocolTreeNode(type, null)
     });
     this.SendNode(node);
 }
Esempio n. 26
0
        /// <summary>
        /// Generate the keysets for ourself
        /// </summary>
        /// <returns></returns>
        public bool sendSetPreKeys(bool isnew = false)
        {
            uint registrationId = 0;

            if (!isnew)
            {
                registrationId = (uint)this.GetLocalRegistrationId();
            }
            else
            {
                registrationId = libaxolotl.util.KeyHelper.generateRegistrationId(true);
            }
            Random          random          = new Random();
            uint            randomid        = (uint)libaxolotl.util.KeyHelper.getRandomSequence(5000);//65536
            IdentityKeyPair identityKeyPair = libaxolotl.util.KeyHelper.generateIdentityKeyPair();

            byte[] privateKey                  = identityKeyPair.getPrivateKey().serialize();
            byte[] publicKey                   = identityKeyPair.getPublicKey().getPublicKey().serialize();
            IList <PreKeyRecord> preKeys       = libaxolotl.util.KeyHelper.generatePreKeys((uint)random.Next(), 200);
            SignedPreKeyRecord   signedPreKey  = libaxolotl.util.KeyHelper.generateSignedPreKey(identityKeyPair, randomid);
            PreKeyRecord         lastResortKey = libaxolotl.util.KeyHelper.generateLastResortPreKey();

            this.StorePreKeys(preKeys);
            this.StoreLocalData(registrationId, identityKeyPair.getPublicKey().serialize(), identityKeyPair.getPrivateKey().serialize());
            this.StoreSignedPreKey(signedPreKey.getId(), signedPreKey);
            // FOR INTERNAL TESTING ONLY
            //this.InMemoryTestSetup(identityKeyPair, registrationId);


            ProtocolTreeNode[] preKeyNodes = new ProtocolTreeNode[200];
            for (int i = 0; i < 200; i++)
            {
                byte[]           prekeyId  = adjustId(preKeys[i].getId().ToString()).Skip(1).ToArray();
                byte[]           prekey    = preKeys[i].getKeyPair().getPublicKey().serialize().Skip(1).ToArray();
                ProtocolTreeNode NodeId    = new ProtocolTreeNode("id", null, null, prekeyId);
                ProtocolTreeNode NodeValue = new ProtocolTreeNode("value", null, null, prekey);
                preKeyNodes[i] = new ProtocolTreeNode("key", null, new ProtocolTreeNode[] { NodeId, NodeValue }, null);
            }

            ProtocolTreeNode registration = new ProtocolTreeNode("registration", null, null, adjustId(registrationId.ToString()));
            ProtocolTreeNode type         = new ProtocolTreeNode("type", null, null, new byte[] { Curve.DJB_TYPE });
            ProtocolTreeNode list         = new ProtocolTreeNode("list", null, preKeyNodes, null);
            ProtocolTreeNode sid          = new ProtocolTreeNode("id", null, null, adjustId(signedPreKey.getId().ToString(), true));
            ProtocolTreeNode identity     = new ProtocolTreeNode("identity", null, null, identityKeyPair.getPublicKey().getPublicKey().serialize().Skip(1).ToArray());
            ProtocolTreeNode value        = new ProtocolTreeNode("value", null, null, signedPreKey.getKeyPair().getPublicKey().serialize().Skip(1).ToArray());
            ProtocolTreeNode signature    = new ProtocolTreeNode("signature", null, null, signedPreKey.getSignature());
            ProtocolTreeNode secretKey    = new ProtocolTreeNode("skey", null, new ProtocolTreeNode[] { sid, value, signature }, null);

            String id = TicketManager.GenerateId();

            Helper.DebugAdapter.Instance.fireOnPrintDebug(string.Format("axolotl id = {0}", id));

            ProtocolTreeNode Node = new ProtocolTreeNode("iq", new KeyValue[] {
                new KeyValue("id", id),
                new KeyValue("to", "s.whatsapp.net"),
                new KeyValue("type", "set"),
                new KeyValue("xmlns", "encrypt")
            }, new ProtocolTreeNode[] { identity, registration, type, list, secretKey }, null);

            this.SendNode(Node);
            return(true);
        }
Esempio n. 27
0
 protected static ProtocolTreeNode GetMessageNode(FMessage message, ProtocolTreeNode pNode, bool hidden = false)
 {
     return new ProtocolTreeNode("message", new[] {
         new KeyValue("to", message.identifier_key.remote_jid),
         new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"),
         new KeyValue("id", message.identifier_key.id)
     },
     new ProtocolTreeNode[] {
         new ProtocolTreeNode("x", new KeyValue[] { new KeyValue("xmlns", "jabber:x:event") }, new ProtocolTreeNode("server", null)),
         pNode,
         new ProtocolTreeNode("offline", null)
     });
 }
Esempio n. 28
0
 public void SendUnsubscribeMe(string jid)
 {
     var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribe"), new KeyValue("to", jid) });
     this.SendNode(node);
 }
Esempio n. 29
0
        public ProtocolTreeNode nextTree(byte[] pInput = null, bool useDecrypt = true)
        {
            if (pInput != null && pInput.Length > 0)
            {
                this.buffer = new List <byte>();
                this.buffer.AddRange(pInput);
            }

            int firstByte  = this.peekInt8();
            int stanzaFlag = (firstByte & 0xF0) >> 4;
            int stanzaSize = this.peekInt16(1) | ((firstByte & 0x0F) << 16);

            int flags = stanzaFlag;
            int size  = stanzaSize;

            this.readInt24();

            bool isEncrypted = (stanzaFlag & 8) != 0;

            if (isEncrypted)
            {
                if (this.Key != null)
                {
                    var realStanzaSize = stanzaSize - 4;
                    var macOffset      = stanzaSize - 4;
                    var treeData       = this.buffer.ToArray();
                    try
                    {
                        this.Key.DecodeMessage(treeData, macOffset, 0, realStanzaSize);
                    }
                    catch (Exception e)
                    {
                        Helper.DebugAdapter.Instance.fireOnPrintDebug(e);
                    }
                    this.buffer.Clear();
                    this.buffer.AddRange(treeData.Take(realStanzaSize).ToArray());
                }
                else
                {
                    throw new Exception("Received encrypted message, encryption key not set");
                }
            }

            if (stanzaSize > 0)
            {
                /*
                 * if (!this.started)
                 * {
                 *  this.streamStart();
                 * }
                 */

                ProtocolTreeNode node = this.nextTreeInternal();
                if (node != null)
                {
                    this.DebugPrint(node.NodeString("rx "));
                }
                return(node);
            }

            return(null);
        }
Esempio n. 30
0
 public void SendSync(string[] numbers, string mode = "full", string context = "registration", int index = 0, bool last = true)
 {
     List<ProtocolTreeNode> users = new List<ProtocolTreeNode>();
     foreach (string number in numbers)
     {
         users.Add(new ProtocolTreeNode("user", null, System.Text.Encoding.UTF8.GetBytes(number)));
     }
     ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[]
     {
         new KeyValue("to", GetJID(this.phoneNumber)),
         new KeyValue("type", "get"),
         new KeyValue("id", TicketCounter.MakeId("sendsync_")),
         new KeyValue("xmlns", "urn:xmpp:whatsapp:sync")
     }, new ProtocolTreeNode("sync", new KeyValue[]
         {
             new KeyValue("mode", mode),
             new KeyValue("context", context),
             new KeyValue("sid", DateTime.Now.ToFileTimeUtc().ToString()),
             new KeyValue("index", index.ToString()),
             new KeyValue("last", last.ToString())
         },
         users.ToArray()
         )
     );
     this.SendNode(node);
 }
Esempio n. 31
0
 public void SendSubjectReceived(string to, string id)
 {
     var child = new ProtocolTreeNode("received", new[] { new KeyValue("xmlns", "urn:xmpp:receipts") });
     var node = GetSubjectMessage(to, id, child);
     this.SendNode(node);
 }
Esempio n. 32
0
 public static bool TagEquals(ProtocolTreeNode node, string _string)
 {
     return(((node != null) && (node._Tag != null)) && node._Tag.Equals(_string, StringComparison.OrdinalIgnoreCase));
 }
Esempio n. 33
0
 protected static ProtocolTreeNode GetSubjectMessage(string to, string id, ProtocolTreeNode child)
 {
     return new ProtocolTreeNode("message", new[] { new KeyValue("to", to), new KeyValue("type", "subject"), new KeyValue("id", id) }, child);
 }
Esempio n. 34
0
 public void SendCreateGroupChat(string subject)
 {
     string id = TicketCounter.MakeId("create_group_");
     var child = new ProtocolTreeNode("group", new[] { new KeyValue("action", "create"), new KeyValue("subject", subject) });
     var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g"), new KeyValue("to", "g.us") }, new ProtocolTreeNode[] { child });
     this.SendNode(node);
 }
Esempio n. 35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public ProtocolTreeNode processEncryptedNode(ProtocolTreeNode node)
        {
            string from    = node.GetAttribute("from");
            string author  = string.Empty;
            string version = string.Empty;
            string encType = string.Empty;

            byte[]           encMsg  = null;
            ProtocolTreeNode rtnNode = null;

            if (from.IndexOf("s.whatsapp.net", 0) > -1)
            {
                author  = ExtractNumber(node.GetAttribute("from"));
                version = node.GetAttribute("v");
                encType = node.GetChild("enc").GetAttribute("type");
                encMsg  = node.GetChild("enc").GetData();

                if (!ContainsSession(new AxolotlAddress(author, 1)))
                {
                    //we don't have the session to decrypt, save it in pending and process it later
                    addPendingNode(node);
                    Helper.DebugAdapter.Instance.fireOnPrintDebug("info : Requesting cipher keys from " + author);
                    sendGetCipherKeysFromUser(author);
                }
                else
                {
                    //decrypt the message with the session
                    if (node.GetChild("enc").GetAttribute("count") == "")
                    {
                        setRetryCounter(node.GetAttribute("id"), 1);
                    }
                    if (version == "2")
                    {
                        if (!v2Jids.Contains(author))
                        {
                            v2Jids.Add(author);
                        }
                    }

                    object plaintext = decryptMessage(from, encMsg, encType, node.GetAttribute("id"), node.GetAttribute("t"));

                    if (plaintext.GetType() == typeof(bool) && false == (bool)plaintext)
                    {
                        sendRetry(node, from, node.GetAttribute("id"), node.GetAttribute("t"));
                        Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Couldn't decrypt message id {0} from {1}. Retrying.", node.GetAttribute("id"), author));
                        return(node); // could not decrypt
                    }

                    // success now lets clear all setting and return node
                    if (retryCounters.ContainsKey(node.GetAttribute("id")))
                    {
                        retryCounters.Remove(node.GetAttribute("id"));
                    }
                    if (retryNodes.ContainsKey(node.GetAttribute("id")))
                    {
                        retryNodes.Remove(node.GetAttribute("id"));
                    }

                    switch (node.GetAttribute("type"))
                    {
                    case "text":
                        //Convert to list.
                        List <ProtocolTreeNode> children      = node.children.ToList();
                        List <KeyValue>         attributeHash = node.attributeHash.ToList();
                        children.Add(new ProtocolTreeNode("body", null, null, (byte[])plaintext));
                        rtnNode = new ProtocolTreeNode(node.tag, attributeHash.ToArray(), children.ToArray(), node.data);
                        break;

                    case "media":
                        // NOT IMPLEMENTED YET
                        break;
                    }

                    Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Decrypted message with {0} id from {1}", node.GetAttribute("id"), author));
                    return(rtnNode);
                }
            }
            return(node);
        }