Example #1
0
        void newReqReceived(Package receivedPackage, int friendNum)
        {
            string mcontentCache = "";

            if (mPackageCache.ContainsKey(receivedPackage.uuid))
            {
                mcontentCache = mPackageCache[receivedPackage.uuid].content;
            }
            mcontentCache += receivedPackage.content;
            // check if this is a response
            if (mPendingReqList.ContainsKey(receivedPackage.uuid))
            {
                mPendingReqList[receivedPackage.uuid](JsonConvert.DeserializeObject <ToxResponse>(mcontentCache));
                mPendingReqList.Remove(receivedPackage.uuid);
                return;
            }

            ToxRequest newReq = JsonConvert.DeserializeObject <ToxRequest>(mcontentCache);

            Task.Factory.StartNew(async() =>
            {
                // send response to http server
                Console.WriteLine("new Req: " + JsonConvert.SerializeObject(newReq));
                ToxResponse mRes = await RequestProxy.sendRequest(this, newReq);
                sendResponse(mRes, tox.GetFriendPublicKey(friendNum));
            });
        }
Example #2
0
        public Task <ToxResponse> sendRequest(ToxId toxid, ToxRequest req, out bool status)
        {
            if (toxid.ToString() == tox.Id.ToString())
            {
                // request was sent to itself
                status = true;
                return(RequestProxy.sendRequest(this, req));
            }

            string reqContent = JsonConvert.SerializeObject(req);
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            for (int i = 0; i < packageNum; i++)
            {
                string mcontent = "";
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = reqContent.Substring(i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = reqContent.Substring(i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsg(toxid, JsonConvert.SerializeObject(new Package
                {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                }));
                if (!res)
                {
                    status = false;
                    return(Task.Factory.StartNew <ToxResponse>(() => {
                        return null;
                    }));
                }
            }
            status = res;
            bool        isResponseReceived = false;
            ToxResponse mRes = null;

            if (res)
            {
                mPendingReqList.Add(req.uuid, (response) => {
                    isResponseReceived = true;
                    mRes = response;
                });
            }
            return(Task.Factory.StartNew(() =>
            {
                while (!isResponseReceived)
                {
                    Thread.Sleep(10);
                }
                return mRes;
            }));
        }
Example #3
0
 private void sendRequestLocal(ToxRequest req)
 {
     // 把变量保存至本地
     lock (messageQueueLock)
     {
         messageQueue.Enqueue(req);
     }
 }
Example #4
0
 private void sendRequestLocal(ToxRequest req)
 {
     // 把变量保存至本地
     lock (messageQueueLock)
     {
         Utils.Log("Event: sendRequestLocal " + req.uuid);
         messageQueue.Enqueue(req);
     }
 }
Example #5
0
        private void newReqReceived(Package receivedPackage)
        {
            Utils.Utils.Log("Event: newReqReceived reqId: " + receivedPackage.uuid);
            byte[] mcontentCache = new byte[receivedPackage.totalSize];
            lock (mPackageCacheLock)
            {
                if (mPackageCache.ContainsKey(receivedPackage.uuid))
                {
                    mcontentCache = mPackageCache[receivedPackage.uuid];
                    mPackageCache.Remove(receivedPackage.uuid);
                }
            }
            receivedPackage.content.CopyTo(mcontentCache, receivedPackage.startIndex);
            // check if this is a response
            lock (mPendingReqLock)
            {
                if (mPendingReqList.ContainsKey(receivedPackage.uuid))
                {
                    Utils.Utils.Log("Event: newResponse Received reqId: " + receivedPackage.uuid);
                    mPendingReqList[receivedPackage.uuid](ToxResponse.fromBytes(mcontentCache));
                    mPendingReqList.Remove(receivedPackage.uuid);
                    return;
                }
            }
            ToxRequest newReq = ToxRequest.fromBytes(mcontentCache);

            if (newReq.method == "")
            {
                Console.WriteLine("this happends, this is an ugly hack");
                return;
            }

            if (newReq == null)
            {
                Utils.Utils.Log("Event: Invalid Request Data: receivedPackage " + receivedPackage.uuid);
                return;
            }
            Utils.Utils.Log("Event: Start callbacks reqId: " + newReq.uuid);
            Utils.Utils.Log("Event: Begin Process MessageID: " + newReq.uuid);
            if (newReq.url == "/msg")
            {
                Utils.Utils.Log("Event: Message toNodeID: " + newReq.toNodeId + ", totoxid:" + newReq.toToxId);
            }
            lock (reqListnerLock)
            {
                if (reqCallbacks.Keys.Contains(newReq.toNodeId))
                {
                    reqCallbacks[newReq.toNodeId](newReq);
                }
            }
            Utils.Utils.Log("Event: End callbacks");
        }
Example #6
0
        public void sendRequestNoReplay(ToxId toxid, ToxRequest req, out bool status)
        {
            status = true;

            try
            {
                if (toxid.ToString() == tox.Id.ToString())
                {
                    // request was sent to itself
                    status = true;
                }
            }
            catch (ObjectDisposedException)
            {
                status = false;
                return;
            }


            byte[] reqContent = req.getBytes();
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            for (int i = 0; i < packageNum; i++)
            {
                byte[] mcontent = null;
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsg(toxid, new Package
                {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                    totalSize    = (uint)reqContent.Length,
                    startIndex   = (uint)(i * MAX_MSG_LENGTH),
                }.toBytes());
                if (!res)
                {
                    status = false;
                }
            }
        }
Example #7
0
        void newReqReceived(Package receivedPackage)
        {
            byte[] mcontentCache = new byte[receivedPackage.totalSize];
            if (mPackageCache.ContainsKey(receivedPackage.uuid))
            {
                mcontentCache = mPackageCache [receivedPackage.uuid];
                mPackageCache.Remove(receivedPackage.uuid);
            }
            receivedPackage.content.CopyTo(mcontentCache, receivedPackage.startIndex);
            // check if this is a response
            lock (mPendingReqLock) {
                if (mPendingReqList.ContainsKey(receivedPackage.uuid))
                {
                    mPendingReqList [receivedPackage.uuid] (ToxResponse.fromBytes(mcontentCache));
                    mPendingReqList.Remove(receivedPackage.uuid);
                    return;
                }
            }
            ToxRequest newReq = ToxRequest.fromBytes(mcontentCache);

            if (newReq == null)
            {
                Utils.Utils.LogUtils("Event: Invalid Request Data: receivedPackage " + receivedPackage.uuid);
                return;
            }
            List <Action <ToxRequest> > tempReqList;

            lock (reqListnerLock) {
                tempReqList = new List <Action <ToxRequest> > (reqCallbacks);
            }
            Utils.Utils.LogUtils("Event: Start callbacks");
            foreach (var cb in tempReqList)
            {
                Utils.Utils.LogUtils("Event: Begin Process MessageID: " + newReq.uuid);
                if (newReq.url == "/msg")
                {
                    Utils.Utils.LogUtils("Event: Message toNodeID: " + newReq.toNodeId + ", totoxid:" + newReq.toToxId);
                }
                cb(newReq);
            }
            Utils.Utils.LogUtils("Event: End callbacks");
        }
Example #8
0
        public void newReqListener(ToxRequest req)
        {
            Utils.LogUtils("Event: newReqListener  MessageID: " + req.uuid);
            if (req.toNodeId == clientId && req.url == "/msg" && req.fromNodeId != serverId)
            {
                // message arrived before connection callback resolved
                serverId = req.fromNodeId;
            }

            if (req.toNodeId == clientId && req.fromNodeId == serverId && req.url == "/msg")
            {
                Utils.LogUtils("Event: Received Message, ClientId: " + clientId + ", MessageId: " + req.uuid);
                msgHandler(req.content);
            }
            if (req.toNodeId == clientId && req.fromNodeId == serverId && req.url == "/close")
            {
                Utils.LogUtils("Event: Received Close, ClientId: " + clientId + ", MessageId: " + req.uuid);
                closeHandler();
                Close();
            }
        }
Example #9
0
        public static async Task <ToxResponse> sendRequest(Skynet host, ToxRequest req)
        {
            // if req is not send to local node
            if (host.tox.Id.ToString() != req.toToxId)
            {
                bool mResStatus = false;
                return(await host.sendRequest(new ToxId(req.toToxId), req, out mResStatus));
            }

            string baseUrl = "http://localhost:" + host.httpPort + "/";
            var    request = (HttpWebRequest)WebRequest.Create(baseUrl + "api/" + req.url);

            request.Headers.Add("Uuid", req.uuid);
            request.Headers.Add("From-Node-Id", req.fromNodeId);
            request.Headers.Add("From-Tox-Id", req.fromToxId);
            request.Headers.Add("To-Node-Id", req.toNodeId);
            request.Headers.Add("To-Tox-Id", req.toToxId);
            request.Headers.Add("Skynet-Time", req.time + "");
            request.Method      = req.method.ToUpper();
            request.ContentType = "application/json";

            List <string> allowedMethods = new List <string> {
                "POST", "PUT", "PATCH"
            };

            if (allowedMethods.Any(x => x == req.method.ToUpper()))
            {
                // only the above methods are allowed to add body data
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(req.content);
                }
            }
            var response = await request.GetResponseAsync();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            return(req.createResponse(responseString));
        }
Example #10
0
        public Task <ToxResponse> sendRequest(ToxId toxid, ToxRequest req, out bool status, int timeout = 200)
        {
            try
            {
                if (toxid.ToString() == tox.Id.ToString())
                {
                    // request was sent to itself
                    status = true;
                    return(RequestProxy.sendRequest(this, req));
                }
            }
            catch (ObjectDisposedException)
            {
                status = false;
                return(Task.Factory.StartNew <ToxResponse>(() =>
                {
                    return null;
                }, TaskCreationOptions.LongRunning));
            }

            byte[] reqContent = req.getBytes();
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            ToxResponse mRes    = null;
            object      reslock = new object();
            bool        resFlag = false;

            lock (mPendingReqLock)
            {
                mPendingReqList.Add(req.uuid, (response) =>
                {
                    mRes = response;
                    lock (reslock)
                    {
                        resFlag = true;
                        Utils.Utils.Log("Event: Callback called, ReqId: " + req.uuid);
                        Monitor.PulseAll(reslock);
                        Utils.Utils.Log("Event: Pulse Lock, ReqId: " + req.uuid);
                    }
                });
            }

            for (int i = 0; i < packageNum; i++)
            {
                byte[] mcontent;
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsgDebug(toxid, new Package
                {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                    totalSize    = (uint)reqContent.Length,
                    startIndex   = (uint)(i * MAX_MSG_LENGTH),
                }, timeout);

                if (!res)
                {
                    status = false;
                    return(Task.Factory.StartNew <ToxResponse>(() =>
                    {
                        lock (mPendingReqLock)
                        {
                            mPendingReqList.Remove(req.uuid);
                        }
                        return null;
                    }, TaskCreationOptions.LongRunning));
                }
            }
            status = res;

            Utils.Utils.Log("Event: return async, ReqId: " + req.uuid);

            return(Task.Factory.StartNew(() =>
            {
                Task.Run(() =>
                {
                    // timeout count thread
                    int timeoutCount = 0;
                    while (timeoutCount < timeout * 1000)
                    {
                        Thread.Sleep(1);
                        timeoutCount += 1;
                        lock (mPendingReqLock)
                        {
                            if (!mPendingReqList.Keys.Contains(req.uuid))
                            {
                                // already received response
                                return;
                            }
                        }
                    }
                    Console.WriteLine(Utils.Utils.UnixTimeNow() + " Timeout Happends ReqId: " + req.uuid);
                    lock (mPendingReqLock)
                    {
                        if (mPendingReqList.Keys.Contains(req.uuid))
                        {
                            mRes = null;
                            mPendingReqList.Remove(req.uuid);
                            lock (reslock)
                            {
                                resFlag = true;
                                Utils.Utils.Log("Event: Callback Timeout, ReqId: " + req.uuid);
                                Monitor.PulseAll(reslock);
                                Utils.Utils.Log("Event: Pulse Lock, ReqId: " + req.uuid);
                            }
                        }
                    }
                });
                Utils.Utils.Log("Event: Response locked, ReqId: " + req.uuid);
                lock (reslock)
                {
                    while (!resFlag)
                    {
                        Monitor.Wait(reslock);
                    }
                }
                Utils.Utils.Log("Event: Response unlocked, ReqId: " + req.uuid);
                return mRes;
            }, TaskCreationOptions.LongRunning));
        }
Example #11
0
        public Task <ToxResponse> sendRequest(ToxId toxid, ToxRequest req, out bool status)
        {
            if (toxid.ToString() == tox.Id.ToString())
            {
                // request was sent to itself
                status = true;
                return(RequestProxy.sendRequest(this, req));
            }

            byte[] reqContent = req.getBytes();
            int    packageNum = reqContent.Length / MAX_MSG_LENGTH + 1;
            bool   res        = false;

            ToxResponse mRes    = null;
            object      reslock = new object();
            bool        resFlag = false;

            lock (mPendingReqLock) {
                mPendingReqList.Add(req.uuid, (response) => {
                    mRes = response;
                    lock (reslock) {
                        resFlag = true;
                        Utils.Utils.LogUtils("Event: Callback called, ReqId: " + req.uuid);
                        Monitor.PulseAll(reslock);
                        Utils.Utils.LogUtils("Event: Pulse Lock, ReqId: " + req.uuid);
                    }
                });
            }

            for (int i = 0; i < packageNum; i++)
            {
                byte[] mcontent;
                if (i * MAX_MSG_LENGTH + MAX_MSG_LENGTH > reqContent.Length)
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH);
                }
                else
                {
                    mcontent = Utils.Utils.subArray(reqContent, i * MAX_MSG_LENGTH, MAX_MSG_LENGTH);
                }
                res = sendMsg(toxid, new Package {
                    uuid         = req.uuid,
                    totalCount   = packageNum,
                    currentCount = i,
                    content      = mcontent,
                    totalSize    = (uint)reqContent.Length,
                    startIndex   = (uint)(i * MAX_MSG_LENGTH),
                }.toBytes());
                if (!res)
                {
                    status = false;
                    return(Task.Factory.StartNew <ToxResponse> (() => {
                        mPendingReqList.Remove(req.uuid);
                        return null;
                    }, TaskCreationOptions.LongRunning));
                }
            }
            status = res;

            Utils.Utils.LogUtils("Event: return async, ReqId: " + req.uuid);

            return(Task.Factory.StartNew(() => {
                Utils.Utils.LogUtils("Event: Response locked, ReqId: " + req.uuid);
                lock (reslock) {
                    while (!resFlag)
                    {
                        Monitor.Wait(reslock);
                    }
                }
                Utils.Utils.LogUtils("Event: Response unlocked, ReqId: " + req.uuid);
                return mRes;
            }, TaskCreationOptions.LongRunning));
        }