コード例 #1
0
ファイル: FormMain.cs プロジェクト: tanshanli/NetProxy
        private void dataGridViewRoutes_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                RouteGridItem route = null;
                var           hti   = dataGridViewRoutes.HitTest(e.X, e.Y);
                if (hti.RowIndex >= 0)
                {
                    dataGridViewRoutes.ClearSelection();
                    dataGridViewRoutes.Rows[hti.RowIndex].Selected = true;
                    route = dataGridViewRoutes.Rows[hti.RowIndex].DataBoundItem as RouteGridItem;
                }

                ContextMenuStrip menu = new ContextMenuStrip();
                menu.ItemClicked += Menu_ItemClicked;
                menu.Items.Add("Add");
                menu.Items.Add("Refresh");
                menu.Items.Add("-");
                menu.Items.Add("Start").Enabled = route != null && route.IsRunning == false;
                menu.Items.Add("Stop").Enabled  = route != null && route.IsRunning == true;
                menu.Items.Add("Edit");

                if (route != null && (route.TrafficType == TrafficType.Http || route.TrafficType == TrafficType.Https))
                {
                    ToolStripMenuItem bindingMenu = new ToolStripMenuItem("Browse");
                    if (route.ListenOnAllAddresses)
                    {
                        IPHostEntry iphostentry = Dns.GetHostEntry(_connectionInfo.ServerName);
                        foreach (IPAddress ipaddress in iphostentry.AddressList)
                        {
                            if (
                                (route.BindingProtocal == BindingProtocal.Pv4 && ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ||
                                (route.BindingProtocal == BindingProtocal.Pv6 && ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                                )
                            {
                                string address = null;
                                if (route.BindingProtocal == BindingProtocal.Pv4)
                                {
                                    address = ipaddress.ToString();
                                }
                                else
                                {
                                    address = String.Format("[{0}]", ipaddress.ToString());
                                }

                                string url      = String.Format("{0}://{1}:{2}/", (route.TrafficType == TrafficType.Http ? "HTTP" : "HTTPS"), address, route.ListenPort);
                                var    menuItem = bindingMenu.DropDownItems.Add(url);
                                menuItem.Click += Browse_MenuItem_Click;
                                menuItem.Tag    = url;
                            }
                        }
                    }
                    else
                    {
                        foreach (var binding in route.Bindings)
                        {
                            if (binding.Enabled == true)
                            {
                                string address = null;
                                if (route.BindingProtocal == BindingProtocal.Pv4)
                                {
                                    address = binding.Address;
                                }
                                else
                                {
                                    address = String.Format("[{0}]", binding.Address);
                                }

                                string url      = String.Format("{0}://{1}:{2}/", (route.TrafficType == TrafficType.Http ? "HTTP" : "HTTPS"), address, route.ListenPort);
                                var    menuItem = bindingMenu.DropDownItems.Add(url);
                                menuItem.Click += Browse_MenuItem_Click;
                                menuItem.Tag    = url;
                            }
                        }
                    }

                    if (bindingMenu.DropDownItems.Count > 0)
                    {
                        menu.Items.Add("-");
                        menu.Items.Add(bindingMenu);
                    }
                }

                menu.Items.Add("-");
                menu.Items.Add("Delete").Enabled = route != null;
                menu.Show(dataGridViewRoutes, e.X, e.Y);
            }
        }
コード例 #2
0
ファイル: Management.cs プロジェクト: tanshanli/NetProxy
        private void Packeteer_OnMessageReceived(Packeteer sender, NetProxy.Hub.Common.Peer peer, NetProxy.Hub.Common.Packet packet)
        {
            //Console.WriteLine("{0}:{1}", packet.Label, packet.Payload);

            if (_loggedInPeers.Contains(peer.Id) == false)
            {
                if (packet.Label == Constants.CommandLables.GuiRequestLogin)
                {
                    try
                    {
                        lock (_config)
                        {
                            var userLogin = JsonConvert.DeserializeObject <UserLogin>(packet.Payload);

                            var singleUser = (from o in _config.Users.List
                                              where o.UserName.ToLower() == userLogin.UserName.ToLower() &&
                                              o.PasswordHash.ToLower() == userLogin.PasswordHash.ToLower()
                                              select o).FirstOrDefault();

                            if (singleUser != null)
                            {
                                _loggedInPeers.Add(peer.Id);
                                Console.WriteLine("Logged in session: {0}, User: {1} (Logged in users {2}).", peer.Id, userLogin.UserName.ToLower(), _loggedInPeers.Count());
                            }
                            else
                            {
                                Console.WriteLine("Failed Login session: {0}, User: {1} (Logged in users {2}).", peer.Id, userLogin.UserName.ToLower(), _loggedInPeers.Count());
                            }

                            _packeteer.SendTo(peer.Id, packet.Label, JsonConvert.SerializeObject(new GenericBooleanResult()
                            {
                                Value = singleUser != null
                            }));
                        }
                    }
                    catch (Exception ex)
                    {
                        Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                        {
                            Severity   = EventLogging.Severity.Error,
                            CustomText = "An error occured while logging in.",
                            Exception  = ex
                        });

                        _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                    }
                }

                return; //If the peer is not logged in, don't go any further.
            }

            if (packet.Label == Constants.CommandLables.GuiRequestRouteList)
            {
                try
                {
                    List <RouteGridItem> routes = new List <RouteGridItem>();

                    lock (_config)
                    {
                        foreach (var router in _routers.List)
                        {
                            RouteGridItem augmentedRoute = new RouteGridItem()
                            {
                                Id                   = router.Route.Id,
                                Name                 = router.Route.Name,
                                TrafficType          = router.Route.TrafficType,
                                RouterType           = router.Route.TrafficType.ToString() + " / " + router.Route.BindingProtocal.ToString(),
                                BindingProtocal      = router.Route.BindingProtocal,
                                Description          = router.Route.Description,
                                IsRunning            = router.IsRunning,
                                ListenPort           = router.Route.ListenPort,
                                ListenOnAllAddresses = router.Route.ListenOnAllAddresses,
                                Bindings             = router.Route.Bindings
                            };

                            routes.Add(augmentedRoute);
                        }
                    }

                    _packeteer.SendTo(peer.Id, packet.Label, JsonConvert.SerializeObject(routes));
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to get route list.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiRequestRouteStatsList)
            {
                try
                {
                    List <RouteGridStats> stats = new List <RouteGridStats>();

                    lock (_config)
                    {
                        foreach (var router in _routers.List)
                        {
                            RouteGridStats augmentedRoute = new RouteGridStats()
                            {
                                Id                 = router.Route.Id,
                                IsRunning          = router.IsRunning,
                                BytesReceived      = router.Stats.BytesReceived,
                                BytesSent          = router.Stats.BytesSent,
                                TotalConnections   = router.Stats.TotalConnections,
                                CurrentConnections = router.CurrentConnectionCount
                            };
                            stats.Add(augmentedRoute);
                        }
                    }

                    _packeteer.SendTo(peer.Id, packet.Label, JsonConvert.SerializeObject(stats));
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to get route stats list.",
                        Exception  = ex
                    });
                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiRequestRoute)
            {
                try
                {
                    lock (_config)
                    {
                        Guid   routerId = Guid.Parse(packet.Payload);
                        Router router   = _routers[routerId];
                        if (router != null)
                        {
                            string value = JsonConvert.SerializeObject(router.Route);
                            _packeteer.SendTo(peer.Id, packet.Label, value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to get route.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiRequestUserList)
            {
                try
                {
                    lock (_config)
                    {
                        string value = JsonConvert.SerializeObject(_config.Users);
                        _packeteer.SendTo(peer.Id, packet.Label, value);
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to get user list.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiPersistUserList)
            {
                try
                {
                    var value = JsonConvert.DeserializeObject <Users>(packet.Payload);

                    lock (_config)
                    {
                        _config.Users.List.Clear();

                        foreach (var user in value.List)
                        {
                            _config.Users.Add(user);
                        }
                        SaveConfiguration();
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to save user list.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiPersistUpsertRoute)
            {
                try
                {
                    var value = JsonConvert.DeserializeObject <Route>(packet.Payload);

                    lock (_config)
                    {
                        var existingRoute = (from o in _routers.List
                                             where o.Route.Id == value.Id
                                             select o).FirstOrDefault();

                        if (existingRoute != null)
                        {
                            existingRoute.Stop();
                            _routers.List.Remove(existingRoute);
                        }

                        var newRouter = new Router(value);

                        _routers.Add(newRouter);

                        SaveConfiguration();

                        if (newRouter.Route.AutoStart)
                        {
                            newRouter.Start();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to upsert route.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiPersistDeleteRoute)
            {
                try
                {
                    Guid routeId = Guid.Parse(packet.Payload);

                    lock (_config)
                    {
                        var existingRoute = (from o in _routers.List
                                             where o.Route.Id == routeId
                                             select o).FirstOrDefault();

                        if (existingRoute != null)
                        {
                            existingRoute.Stop();
                            _routers.List.Remove(existingRoute);
                        }
                        SaveConfiguration();
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to get delete route.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "The operation failed: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiPersistStopRoute)
            {
                try
                {
                    Guid routeId = Guid.Parse(packet.Payload);

                    lock (_config)
                    {
                        var existingRoute = (from o in _routers.List
                                             where o.Route.Id == routeId
                                             select o).FirstOrDefault();

                        if (existingRoute != null)
                        {
                            existingRoute.Stop();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to get stop route.",
                        Exception  = ex
                    });

                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "Failed to stop route: " + ex.Message);
                }
            }
            else if (packet.Label == Constants.CommandLables.GuiPersistStartRoute)
            {
                try
                {
                    Guid routeId = Guid.Parse(packet.Payload);

                    lock (_config)
                    {
                        var existingRoute = (from o in _routers.List
                                             where o.Route.Id == routeId
                                             select o).FirstOrDefault();

                        if (existingRoute != null)
                        {
                            if (existingRoute.Start() == false)
                            {
                                _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "Failed to start route.");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Singletons.EventLog.WriteEvent(new EventLogging.EventPayload
                    {
                        Severity   = EventLogging.Severity.Error,
                        CustomText = "Failed to start route.",
                        Exception  = ex
                    });
                    _packeteer.SendTo(peer.Id, Constants.CommandLables.GuiSendMessage, "Failed to start route: " + ex.Message);
                }
            }
        }