Exemplo n.º 1
0
 public bool AddMessage(NetworkRequest r)
 {
     if (running)
         pendingRequests.Add(r);
     workerEvent.Set();
     return running;
 }
Exemplo n.º 2
0
 public NetworkRequest CreateRequest()
 {
     var req = new NetworkRequest();
     req.Verb = "ADDDOWNLOAD";
     req.Param = URL;
     return req;
 }
Exemplo n.º 3
0
 /// <summary>
 /// Called by a end client to send an update a server
 /// </summary>
 /// <returns></returns>
 public NetworkRequest CreateRequest()
 {
     var req = new NetworkRequest();
     req.Data = Serialize(this);
     req.Verb = "UPDATE";
     return req;
 }
Exemplo n.º 4
0
 public NetworkRequest CreateRequest()
 {
     var r = new NetworkRequest();
     r.Verb = "SEARCH";
     r.Data = Serialize(this);
     return r;
 }
Exemplo n.º 5
0
 public bool ReceiveResponse(NetworkRequest r)
 {
     var search = Deserialise<SearchVerb>(r.Data);
     SearchString = search.SearchString;
     results = search.Results;
     return true;
 }
Exemplo n.º 6
0
 public void AddMessage(NetworkRequest r)
 {
     if (run)
     {
         pendingRequests.Add(r.Clone());
         workerEvent.Set();
     }
 }
Exemplo n.º 7
0
 public bool ReceiveResponse(NetworkRequest r)
 {
     var inc = Deserialise<ChatVerb>(r.Data);
     Nickname = inc.Nickname;
     Message = inc.Message;
     SourceID = inc.SourceID;
     return true;
 }
Exemplo n.º 8
0
 public bool Execute(NetworkRequest req, Node destination, int timeout)
 {
     destination.LastUpdate = Environment.TickCount;
     var output = new NetworkRequest();
     if (!string.IsNullOrEmpty(destination.Secret) && string.IsNullOrEmpty(req.AuthKey))
         req.AuthKey = destination.Secret;
     return DoRequest(destination.Location, req, out output, timeout);
 }
Exemplo n.º 9
0
 public NetworkRequest ProcessRequest(NetworkRequest r)
 {
     var verb = Deserialise<ConnectVerb>(r.Data);
     Address = verb.Address;
     ClientType = verb.ClientType;
     Secret = verb.Secret;
     ClientType = verb.ClientType;
     OverlordID = r.OverlordID;
     r.Data = string.Empty;
     return r;
 }
Exemplo n.º 10
0
 public bool ReceiveResponse(NetworkRequest r)
 {
     try
     {
         var inc = Deserialise<InfoVerb>(r.Data);
         Node = inc.Node;
         return true;
     }
     catch
     {
         return false;
     }
 }
Exemplo n.º 11
0
        public NetworkRequest ProcessRequest(NetworkRequest r)
        {
            var verb = Deserialise<BrowseVerb>(r.Data);

            List<BrowsingFile> results;
            if (_infoService.GetPath(verb.Path, verb.NoCache, true, out results))
                Results = results;

            r.Data = Serialize(this);
            //Clear collection to assist GC
            results.Clear();
            return r;
        }
Exemplo n.º 12
0
        public bool ReceiveResponse(NetworkRequest r)
        {
            try
            {
                var verb = Deserialise<BrowseVerb>(r.Data);
                NoCache = verb.NoCache;
                Path = verb.Path;
                Results = verb.Results;
                return true;
            }
// ReSharper disable EmptyGeneralCatchClause
            catch
// ReSharper restore EmptyGeneralCatchClause
            {
            }
            return false;
        }
Exemplo n.º 13
0
        public NetworkRequest ProcessRequest(NetworkRequest r)
        {
            var verb = Deserialise<SearchVerb>(r.Data);
            SearchString = verb.SearchString;

            long modifiedBefore = 0;
            long modifiedAfter = 0;

            if (DateTime.MinValue != verb.ModifiedBefore)
                modifiedBefore = verb.ModifiedBefore.ToFileTime();
            if (DateTime.MinValue != verb.ModifiedAfter)
                modifiedAfter = verb.ModifiedAfter.ToFileTime();
            if (null != shareInfoService)
                results = shareInfoService.Search(verb.SearchString, Model.MAX_SEARCH_RESULTS, modifiedBefore,
                                                  modifiedAfter, verb.SmallerThan, verb.LargerThan);
            r.Data = Serialize(this);
            results.Clear();
            return r;
        }
Exemplo n.º 14
0
 public NetworkRequest ProcessRequest(NetworkRequest r)
 {
     Allowed = !model.DisableComparision;
     if (Allowed)
     {
         lock (sync)
         {
             if (null == cachedResponse || Environment.TickCount - cacheTime > 1000*300)
             {
                 var si = new SystemInfo();
                 Node = new CompareNode();
                 Node.SetData("COMP-CPUSpeed", si.GetCPUSpeed().ToString());
                 Node.SetData("COMP-CPUType", si.GetCPUType());
                 Node.SetData("COMP-CPUCores", si.GetCPUCores().ToString());
                 Node.SetData("COMP-CPUThreads", si.GetCPUThreads().ToString());
                 Node.SetData("COMP-CPUBits", si.GetCPUBits().ToString());
                 Node.SetData("COMP-MoboBrand", si.GetMoboBrand());
                 Node.SetData("COMP-MoboModel", si.GetMoboModel());
                 Node.SetData("COMP-BIOSVersion", si.GetBIOSVersion());
                 Node.SetData("COMP-RAMSize", si.GetMemorySize().ToString());
                 Node.SetData("COMP-GPUModel", si.GetGPUDescription());
                 Node.SetData("COMP-GPUCount", si.GetGPUCount().ToString());
                 Node.SetData("COMP-GPUTotalMemory", si.GetTotalGPUMemory().ToString());
                 Node.SetData("COMP-DisplayPrimaryHeight", si.GetPrimaryDisplayHeight().ToString());
                 Node.SetData("COMP-DisplayPrimaryWidth", si.GetPrimaryDisplayWidth().ToString());
                 Node.SetData("COMP-DisplayTotalWidth", si.GetTotalDisplayWidth().ToString());
                 Node.SetData("COMP-DisplayTotalHeight", si.GetTotalDisplayHeight().ToString());
                 Node.SetData("COMP-HDDSize", si.GetTotalHDDSize().ToString());
                 Node.SetData("COMP-HDDFree", si.GetTotalHDDFree().ToString());
                 Node.SetData("COMP-HDDCount", si.GetHDDCount().ToString());
                 Node.SetData("COMP-NICSpeed", si.GetNetworkSpeed().ToString());
                 Node.SetData("COMP-SoundCard", si.GetSoundcardName());
                 cachedResponse = new NetworkRequest {Data = Serialize(this)};
                 cacheTime = Environment.TickCount;
             }
         }
         return cachedResponse;
     }
     else
     {
         return new NetworkRequest {Data = Serialize(this)};
     }
 }
Exemplo n.º 15
0
        public static NetworkRequest Decode(IRequest r)
        {
            var req = new NetworkRequest();
            if (!r.Uri.AbsolutePath.StartsWith(preample))
                throw new Exception("Malformed url");
            req.Verb = r.Uri.AbsolutePath.Substring(preample.Length);

            IParameter param = r.Parameters.Where(p => p.Name == "p").FirstOrDefault();
            if (null != param)
            {
                req.Param = Encoding.UTF8.GetString(Convert.FromBase64String(param.Value.Replace('_', '+')));
            }
            if (r.Method == "POST")
            {
                req.Data = GetPostString(r);
            }

            var headers = r.Headers as HeaderCollection;
            if (null != headers)
            {
                foreach (IHeader  h in headers)
                {
                    var header = h as StringHeader;
                    if (null != header)
                    {
                        switch (header.Name.ToUpper())
                        {
                            case "FAP-AUTH":
                                req.AuthKey = header.Value;
                                break;
                            case "FAP-SOURCE":
                                req.SourceID = header.Value;
                                break;
                            case "FAP-OVERLORD":
                                req.OverlordID = header.Value;
                                break;
                        }
                    }
                }
            }
            return req;
        }
Exemplo n.º 16
0
        public bool Execute(IVerb verb, Node destination, int timeout)
        {
            try
            {
                NetworkRequest request = verb.CreateRequest();
                var output = new NetworkRequest();
                destination.LastUpdate = Environment.TickCount;

                if (!string.IsNullOrEmpty(destination.Secret) && string.IsNullOrEmpty(request.AuthKey))
                    request.AuthKey = destination.Secret;

                if (!DoRequest(destination.Location, request, out output, timeout))
                    return false;

                if (!verb.ReceiveResponse(output))
                    return false;
                return true;
            }
            catch
            {
                return false;
            }
        }
Exemplo n.º 17
0
 private bool HandleNOOP(RequestEventArgs e, NetworkRequest req)
 {
     //Noop is usually used as a heartbeat message however if the authkey is set then it came from a overlord
     //Check the authkey is correct for our current overlord just incase we disconnected incorrectly and reconnected elsewhere
     if (string.IsNullOrEmpty(req.AuthKey) || req.AuthKey == model.Network.Overlord.Secret)
         SendOk(e);
     return true;
 }
Exemplo n.º 18
0
 private bool HandleUpdate(RequestEventArgs e, NetworkRequest req)
 {
     if (req.AuthKey == model.Network.Overlord.Secret)
     {
         model.Network.Overlord.LastUpdate = Environment.TickCount;
         var verb = new UpdateVerb();
         verb.ProcessRequest(req);
         foreach (Node node in verb.Nodes)
         {
             Node search = model.Network.Nodes.Where(i => i.ID == node.ID).FirstOrDefault();
             if (search == null)
             {
                 //Dont allow partial updates to create clients.  Only full updates should contain the online flag.
                 if (node.ContainsKey("Online") && node.ContainsKey("Nickname") && node.ContainsKey("ID"))
                     model.Network.Nodes.Add(node);
             }
             else
             {
                 foreach (var param in node.Data)
                     search.SetData(param.Key, param.Value);
                 //Has the client disconnected?
                 if (!search.Online)
                 {
                     model.Network.Nodes.Remove(node);
                     logger.Trace("Client: Node offline update: " + node.ID);
                 }
             }
         }
         SendOk(e);
         return true;
     }
     return false;
 }
Exemplo n.º 19
0
 private bool HandleChat(RequestEventArgs e, NetworkRequest req)
 {
     var verb = new ChatVerb();
     verb.ReceiveResponse(req);
     model.Messages.AddRotate(verb.Nickname + ":" + verb.Message, 50);
     SendOk(e);
     SafeObservingCollectionManager.UpdateNowAsync();
     return true;
 }
Exemplo n.º 20
0
        private bool HandleCompare(RequestEventArgs e, NetworkRequest req)
        {
            var verb = new CompareVerb(model);

            NetworkRequest result = verb.ProcessRequest(req);
            byte[] data = Encoding.UTF8.GetBytes(result.Data);
            var generator = new ResponseWriter();
            e.Response.ContentLength.Value = data.Length;
            generator.SendHeaders(e.Context, e.Response);
            e.Context.Stream.Write(data, 0, data.Length);
            e.Context.Stream.Flush();
            data = null;

            return true;
        }
Exemplo n.º 21
0
 private bool HandleSearch(RequestEventArgs e, NetworkRequest req)
 {
     //We dont do this on a server..
     var verb = new SearchVerb(shareInfoService);
     NetworkRequest result = verb.ProcessRequest(req);
     byte[] data = Encoding.UTF8.GetBytes(result.Data);
     var generator = new ResponseWriter();
     e.Response.ContentLength.Value = data.Length;
     generator.SendHeaders(e.Context, e.Response);
     e.Context.Stream.Write(data, 0, data.Length);
     e.Context.Stream.Flush();
     data = null;
     return true;
 }
Exemplo n.º 22
0
 private bool HandleConversation(RequestEventArgs e, NetworkRequest req)
 {
     try
     {
         var verb = new ConversationVerb();
         verb.ProcessRequest(req);
         if (chatController.HandleMessage(verb.SourceID, verb.Nickname, verb.Message))
         {
             SendOk(e);
             return true;
         }
     }
     catch
     {
     }
     return false;
 }
Exemplo n.º 23
0
 public NetworkRequest CreateRequest()
 {
     var req = new NetworkRequest {Verb = "BROWSE", Data = Serialize(this)};
     return req;
 }
Exemplo n.º 24
0
        private void Process(object o)
        {
            try
            {
                while (run)
                {
                    //If the client has timed out then disconect
                    if (pendingRequests.Count == 0 &&
                        Environment.TickCount - destination.LastUpdate > Model.UPLINK_TIMEOUT)
                    {
                        if (null != OnDisconnect)
                            OnDisconnect(this);
                        var req = new NetworkRequest {Verb = "DISCONNECT", SourceID = serverNode.ID};
                        TransmitRequest(req);
                        return;
                    }
                    //If the client is going to timeout in the next 15 seconds then do an update
                    if (pendingRequests.Count == 0 &&
                        Environment.TickCount - destination.LastUpdate > Model.UPLINK_TIMEOUT - PRE_TIMEOUT_PERIOD)
                        pendingRequests.Add(new NetworkRequest
                                                {
                                                    Data = string.Empty,
                                                    Param = string.Empty,
                                                    Verb = "NOOP",
                                                    SourceID = serverNode.ID
                                                });

                    while (pendingRequests.Count > 0)
                    {
                        NetworkRequest req = pendingRequests[0];
                        TransmitRequest(req);
                        pendingRequests.RemoveAt(0);
                    }
                    workerEvent.WaitOne(5000);
                }
            }
            catch
            {
                if (null != OnDisconnect)
                    OnDisconnect(this);
            }
            //Clean up
            //AutoResetEvent w = workerEvent;
            //workerEvent = null;
            //w.Close();
            pendingRequests.Clear();
        }
Exemplo n.º 25
0
 public NetworkRequest ProcessRequest(NetworkRequest r)
 {
     URL = r.Param;
     return new NetworkRequest();
 }
Exemplo n.º 26
0
        private bool HandleGet(RequestEventArgs e, NetworkRequest req)
        {
            //No url?
            if (string.IsNullOrEmpty(req.Param))
                return false;

            string[] possiblePaths;


            if (shareInfoService.ToLocalPath(req.Param, out possiblePaths))
            {
                foreach (string possiblePath in possiblePaths)
                {
                    if (File.Exists(possiblePath))
                    {
                        var ffu = new FAPFileUploader(bufferService, serverUploadLimiterService);
                        var session = new TransferSession(ffu);
                        model.TransferSessions.Add(session);
                        try
                        {
                            //Try to find the username of the request
                            string userName = e.Context.RemoteEndPoint.Address.ToString();
                            Node search = model.Network.Nodes.ToList().Where(n => n.ID == req.SourceID).FirstOrDefault();
                            if (null != search && !string.IsNullOrEmpty(search.Nickname))
                                userName = search.Nickname;

                            using (
                                FileStream fs = File.Open(possiblePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                ffu.DoUpload(e.Context, fs, userName, possiblePath);
                            }

                            //Add log of upload
                            double seconds = (DateTime.Now - ffu.TransferStart).TotalSeconds;
                            var txlog = new TransferLog();
                            txlog.Nickname = userName;
                            txlog.Completed = DateTime.Now;
                            txlog.Filename = Path.GetFileName(possiblePath);
                            txlog.Path = Path.GetDirectoryName(req.Param);
                            if (!string.IsNullOrEmpty(txlog.Path))
                            {
                                txlog.Path = txlog.Path.Replace('\\', '/');
                                if (txlog.Path.StartsWith("/"))
                                    txlog.Path = txlog.Path.Substring(1);
                            }

                            txlog.Size = ffu.Length - ffu.ResumePoint;
                            if (txlog.Size < 0)
                                txlog.Size = 0;
                            if (0 != seconds)
                                txlog.Speed = (int) (txlog.Size/seconds);
                            model.CompletedUploads.Add(txlog);
                        }
                        finally
                        {
                            model.TransferSessions.Remove(session);
                        }
                        return true;
                    }
                }
            }

            e.Response.Status = HttpStatusCode.NotFound;
            var generator = new ResponseWriter();
            generator.SendHeaders(e.Context, e.Response);
            return true;
        }
Exemplo n.º 27
0
 private bool HandleAddDownload(RequestEventArgs e, NetworkRequest req)
 {
     if (req.AuthKey == model.LocalNode.Secret && !string.IsNullOrEmpty(req.Param))
     {
         model.AddDownloadURL(req.Param);
         SendOk(e);
         return true;
     }
     return false;
 }
Exemplo n.º 28
0
        private void ProcessLanConnection(object o)
        {
            mserver.SendMessage(WhoVerb.CreateRequest());
            Domain.Entities.Network network = model.Network;
            network.PropertyChanged += network_PropertyChanged;
            while (run)
            {
                if (network.State != ConnectionState.Connected)
                {
                    //Not connected so connect automatically..

                    //Regenerate local secret to stop any updates if we reconnecting..
                    network.Overlord = new Node();
                    network.Overlord.Secret = IDService.CreateID();
                    //Clear old peers
                    network.Nodes.Clear();

                    //Build up a prioritised server list
                    var availibleNodes = new List<DetectedNode>();

                    List<DetectedNode> detectedPeers = peerFinder.Peers.ToList();

                    //Prioritise a server we havent connected to already
                    foreach (DetectedNode peer in detectedPeers)
                    {
                        if (attemptedPeers.Where(s => s.Node == peer).Count() == 0)
                            availibleNodes.Add(peer);
                    }
                    foreach (LanPeer peer in attemptedPeers.OrderByDescending(x => x.LastConnectionTime))
                    {
                        availibleNodes.Add(peer.Node);
                    }

                    while (network.State != ConnectionState.Connected && availibleNodes.Count > 0)
                    {
                        DetectedNode node = availibleNodes[0];
                        availibleNodes.RemoveAt(0);
                        if (!Connect(network, node))
                            peerFinder.RemovePeer(node);
                    }
                }
                if (network.State == ConnectionState.Connected)
                {
                    CheckModelChanges();
                    //Check for network timeout

                    if ((Environment.TickCount - model.Network.Overlord.LastUpdate) > Model.UPLINK_TIMEOUT)
                    {
                        //We havent recently sent/recieved so went a noop so check we are still connected.
                        var req = new NetworkRequest
                                      {
                                          Verb = "NOOP",
                                          SourceID = model.LocalNode.ID,
                                          AuthKey = model.Network.Overlord.Secret
                                      };
                        var client = new Client(model.LocalNode);
                        if (!client.Execute(req, model.Network.Overlord, 4000))
                        {
                            if (network.State == ConnectionState.Connected)
                            {
                                Disconnect();
                            }
                        }
                    }

                    workerEvent.WaitOne(10000);
                }
                else
                    workerEvent.WaitOne(100);
            }
        }
Exemplo n.º 29
0
 public bool ReceiveResponse(NetworkRequest r)
 {
     return true;
 }
Exemplo n.º 30
0
        private void Process(object o)
        {
            try
            {
                while (running)
                {
                    while (pendingRequests.Count > 0)
                    {
                        NetworkRequest req = pendingRequests[0];
                        pendingRequests.RemoveAt(0);

                        destination.LastUpdate = Environment.TickCount;
                        var c = new Client(source);
                        if (!c.Execute(req, destination))
                        {
                            //Error
                            running = false;
                            return;
                        }
                    }

                    //Check for client time out
                    if ((Environment.TickCount - destination.LastUpdate) > Model.UPLINK_TIMEOUT)
                    {
                        //We havent recently sent/recieved so went a noop so check we are still connected.
                        var req = new NetworkRequest {Verb = "NOOP", SourceID = source.ID, AuthKey = destination.Secret};
                        var client = new Client(source);
                        if (!client.Execute(req, destination, 4000))
                        {
                            //Error
                            running = false;
                            return;
                        }
                    }

                    //Wait until there is work to do or 5 seconds have elapsed
                    workerEvent.WaitOne(5000);
                }
            }
            catch
            {
            }
            finally
            {
                if (null != OnDisconnect)
                    OnDisconnect(this);
            }
        }